Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Minor improvements to scala akka server #5823

Merged
merged 3 commits into from
Apr 5, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
add samples
  • Loading branch information
wing328 committed Apr 4, 2020
commit ec0147af8f385e80339dea2b91617c5c60da7102
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator

# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.

# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs

# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux

# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux

# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
4.3.1-SNAPSHOT
54 changes: 54 additions & 0 deletions samples/server/petstore/scala-akka-http-server/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# OpenAPI Petstore

This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.


## API

### Pet

|Name|Role|
|----|----|
|`org.openapitools.server.api.PetController`|akka-http API controller|
|`org.openapitools.server.api.PetApi`|Representing trait|
|`org.openapitools.server.api.PetApiImpl`|Default implementation|

* `POST /v2/pet` - Add a new pet to the store
* `DELETE /v2/pet/{petId}` - Deletes a pet
* `GET /v2/pet/findByStatus?status=[value]` - Finds Pets by status
* `GET /v2/pet/findByTags?tags=[value]` - Finds Pets by tags
* `GET /v2/pet/{petId}` - Find pet by ID
* `PUT /v2/pet` - Update an existing pet
* `POST /v2/pet/{petId}` - Updates a pet in the store with form data
* `POST /v2/pet/{petId}/uploadImage` - uploads an image

### Store

|Name|Role|
|----|----|
|`org.openapitools.server.api.StoreController`|akka-http API controller|
|`org.openapitools.server.api.StoreApi`|Representing trait|
|`org.openapitools.server.api.StoreApiImpl`|Default implementation|

* `DELETE /v2/store/order/{orderId}` - Delete purchase order by ID
* `GET /v2/store/inventory` - Returns pet inventories by status
* `GET /v2/store/order/{orderId}` - Find purchase order by ID
* `POST /v2/store/order` - Place an order for a pet

### User

|Name|Role|
|----|----|
|`org.openapitools.server.api.UserController`|akka-http API controller|
|`org.openapitools.server.api.UserApi`|Representing trait|
|`org.openapitools.server.api.UserApiImpl`|Default implementation|

* `POST /v2/user` - Create user
* `POST /v2/user/createWithArray` - Creates list of users with given input array
* `POST /v2/user/createWithList` - Creates list of users with given input array
* `DELETE /v2/user/{username}` - Delete user
* `GET /v2/user/{username}` - Get user by user name
* `GET /v2/user/login?username=[value]&password=[value]` - Logs user into the system
* `GET /v2/user/logout` - Logs out current logged in user session
* `PUT /v2/user/{username}` - Updated user

9 changes: 9 additions & 0 deletions samples/server/petstore/scala-akka-http-server/build.sbt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
version := "1.0.0"
name := "openapi-scala-akka-http-server"
organization := "org.openapitools"
scalaVersion := "2.12.8"

libraryDependencies ++= Seq(
"com.typesafe.akka" %% "akka-stream" % "2.5.21",
"com.typesafe.akka" %% "akka-http" % "10.1.10"
)
32 changes: 32 additions & 0 deletions samples/server/petstore/scala-akka-http-server/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>org.openapitools</groupId>
<artifactId>scala-akka-http-server</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>Scala Play server</name>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.5.0</version>
<executions>
<execution>
<id>sbt-test</id>
<phase>integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>sbt</executable>
<arguments>
<argument>test</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
sbt.version=1.1.6
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package org.openapitools.server

import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{PathMatcher, PathMatcher1}
import scala.util.{Failure, Success, Try}
import scala.util.control.NoStackTrace

object AkkaHttpHelper {
def optToTry[T](opt: Option[T], err: => String): Try[T] =
opt.map[Try[T]](Success(_)) getOrElse Failure(new RuntimeException(err) with NoStackTrace)

/**
* A PathMatcher that matches and extracts a Float value. The matched string representation is the pure decimal,
* optionally signed form of a float value, i.e. without exponent.
*
* @group pathmatcher
*/
val FloatNumber: PathMatcher1[Float] =
PathMatcher("""[+-]?\d*\.?\d*""".r) flatMap { string =>
try Some(java.lang.Float.parseFloat(string))
catch { case _: NumberFormatException => None }
}

/**
* A PathMatcher that matches and extracts a Boolean value.
*
* @group pathmatcher
*/
val Boolean: PathMatcher1[Boolean] =
Segment.flatMap { string =>
try Some(string.toBoolean)
catch { case _: IllegalArgumentException => None }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package org.openapitools.server

import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Route
import org.openapitools.server.api.PetApi
import org.openapitools.server.api.StoreApi
import org.openapitools.server.api.UserApi

import akka.http.scaladsl.server.Directives._
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer

class Controller(pet: PetApi, store: StoreApi, user: UserApi)(implicit system: ActorSystem, materializer: ActorMaterializer) {

lazy val routes: Route = pet.route ~ store.route ~ user.route

Http().bindAndHandle(routes, "0.0.0.0", 9000)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package org.openapitools.server

import java.io.File

import akka.annotation.ApiMayChange
import akka.http.scaladsl.model.Multipart.FormData
import akka.http.scaladsl.model.{ContentType, HttpEntity, Multipart}
import akka.http.scaladsl.server.Directive1
import akka.http.scaladsl.server.directives._
import akka.stream.Materializer
import akka.stream.scaladsl._

import scala.collection.immutable
import scala.concurrent.{ExecutionContextExecutor, Future}

trait MultipartDirectives {

import akka.http.scaladsl.server.directives.BasicDirectives._
import akka.http.scaladsl.server.directives.FutureDirectives._
import akka.http.scaladsl.server.directives.MarshallingDirectives._

@ApiMayChange
def formAndFiles(fileFields: FileField*): Directive1[PartsAndFiles] =
entity(as[Multipart.FormData]).flatMap {
formData =>
extractRequestContext.flatMap { ctx =>
implicit val mat: Materializer = ctx.materializer
implicit val ec: ExecutionContextExecutor = ctx.executionContext

val uploadingSink: Sink[FormData.BodyPart, Future[PartsAndFiles]] =
Sink.foldAsync[PartsAndFiles, Multipart.FormData.BodyPart](PartsAndFiles.Empty) {
(acc, part) =>
def discard(p: Multipart.FormData.BodyPart): Future[PartsAndFiles] = {
p.entity.discardBytes()
Future.successful(acc)
}

part.filename.map {
fileName =>
fileFields.find(_.fieldName == part.name)
.map {
case FileField(_, destFn) =>
val fileInfo = FileInfo(part.name, fileName, part.entity.contentType)
val dest = destFn(fileInfo)

part.entity.dataBytes.runWith(FileIO.toPath(dest.toPath)).map { _ =>
acc.addFile(fileInfo, dest)
}
}.getOrElse(discard(part))
} getOrElse {
part.entity match {
case HttpEntity.Strict(ct: ContentType.NonBinary, data) =>
val charsetName = ct.charset.nioCharset.name
val partContent = data.decodeString(charsetName)

Future.successful(acc.addForm(part.name, partContent))
case _ =>
discard(part)
}
}
}

val uploadedF = formData.parts.runWith(uploadingSink)

onSuccess(uploadedF)
}
}
}

object MultipartDirectives extends MultipartDirectives with FileUploadDirectives {
val tempFileFromFileInfo: FileInfo => File = {
file: FileInfo => File.createTempFile(file.fileName, ".tmp")
}
}

final case class FileField(fieldName: String, fileNameF: FileInfo => File = MultipartDirectives.tempFileFromFileInfo)

final case class PartsAndFiles(form: immutable.Map[String, String], files: Map[String, (FileInfo, File)]) {
def addForm(fieldName: String, content: String): PartsAndFiles = this.copy(form.updated(fieldName, content))

def addFile(info: FileInfo, file: File): PartsAndFiles = this.copy(
files = files.updated(info.fieldName, (info, file))
)
}

object PartsAndFiles {
val Empty: PartsAndFiles = PartsAndFiles(immutable.Map.empty, immutable.Map.empty)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
package org.openapitools.server

import akka.http.scaladsl.common._
import akka.http.scaladsl.server.{Directive, Directive0, Directive1, InvalidRequiredValueForQueryParamRejection, MalformedFormFieldRejection, MissingFormFieldRejection, MissingQueryParamRejection, UnsupportedRequestContentTypeRejection}
import akka.http.scaladsl.server.directives.BasicDirectives
import akka.http.scaladsl.unmarshalling.Unmarshaller.UnsupportedContentTypeException

import scala.concurrent.Future
import scala.util.{Failure, Success}

trait StringDirectives {
implicit def _symbol2NR(symbol: Symbol): NameReceptacle[String] = new NameReceptacle[String](symbol.name)
implicit def _string2NR(string: String): NameReceptacle[String] = new NameReceptacle[String](string)

import StringDirectives._
type StringValueProvider = Map[String, String]

def stringField(pdm: StringMagnet): pdm.Out = pdm()

def stringFields(pdm: StringMagnet): pdm.Out = pdm()

}

object StringDirectives extends StringDirectives {

sealed trait StringMagnet {
type Out
def apply(): Out
}
object StringMagnet {
implicit def apply[T](value: T)(implicit sdef: StringDef[T]): StringMagnet { type Out = sdef.Out } =
new StringMagnet {
type Out = sdef.Out
def apply(): sdef.Out = sdef(value)
}
}

type StringDefAux[A, B] = StringDef[A] { type Out = B }
sealed trait StringDef[T] {
type Out
def apply(value: T): Out
}
object StringDef {
protected def stringDef[A, B](f: A => B): StringDefAux[A, B] =
new StringDef[A] {
type Out = B

def apply(value: A): B = f(value)
}

import akka.http.scaladsl.server.directives.BasicDirectives._
import akka.http.scaladsl.server.directives.FutureDirectives._
import akka.http.scaladsl.server.directives.RouteDirectives._
import akka.http.scaladsl.unmarshalling._

type FSU[T] = FromStringUnmarshaller[T]
type FSOU[T] = Unmarshaller[Option[String], T]
type SFVP = StringValueProvider

protected def extractField[A, B](f: A => Directive1[B]): StringDefAux[A, Directive1[B]] = stringDef(f)

protected def handleFieldResult[T](fieldName: String, result: Future[T]): Directive1[T] = onComplete(result).flatMap {
case Success(x) => provide(x)
case Failure(Unmarshaller.NoContentException) => reject(MissingFormFieldRejection(fieldName))
case Failure(x: UnsupportedContentTypeException) => reject(UnsupportedRequestContentTypeRejection(x.supported, x.actualContentType))
case Failure(x) => reject(MalformedFormFieldRejection(fieldName, if (x.getMessage == null) "" else x.getMessage, Option(x.getCause)))
}

private def filter[T](paramName: String, fsou: FSOU[T])(implicit vp: SFVP): Directive1[T] = {
extract { ctx =>
import ctx.{executionContext, materializer}
handleFieldResult(paramName, fsou(vp.get(paramName)))
}.flatMap(identity)
}

implicit def forString(implicit fsu: FSU[String], vp: SFVP): StringDefAux[String, Directive1[String]] =
extractField[String, String] { string => filter(string, fsu) }
implicit def forSymbol(implicit fsu: FSU[String], vp: SFVP): StringDefAux[Symbol, Directive1[String]] =
extractField[Symbol, String] { symbol => filter(symbol.name, fsu) }
implicit def forNR[T](implicit fsu: FSU[T], vp: SFVP): StringDefAux[NameReceptacle[T], Directive1[T]] =
extractField[NameReceptacle[T], T] { nr => filter(nr.name, fsu) }
implicit def forNUR[T](implicit vp: SFVP): StringDefAux[NameUnmarshallerReceptacle[T], Directive1[T]] =
extractField[NameUnmarshallerReceptacle[T], T] { nr => filter(nr.name, nr.um) }
implicit def forNOR[T](implicit fsou: FSOU[T], vp: SFVP): StringDefAux[NameOptionReceptacle[T], Directive1[Option[T]]] =
extractField[NameOptionReceptacle[T], Option[T]] { nr => filter[Option[T]](nr.name, fsou) }
implicit def forNDR[T](implicit fsou: FSOU[T], vp: SFVP): StringDefAux[NameDefaultReceptacle[T], Directive1[T]] =
extractField[NameDefaultReceptacle[T], T] { nr => filter[T](nr.name, fsou withDefaultValue nr.default) }
implicit def forNOUR[T](implicit vp: SFVP): StringDefAux[NameOptionUnmarshallerReceptacle[T], Directive1[Option[T]]] =
extractField[NameOptionUnmarshallerReceptacle[T], Option[T]] { nr => filter(nr.name, nr.um: FSOU[T]) }
implicit def forNDUR[T](implicit vp: SFVP): StringDefAux[NameDefaultUnmarshallerReceptacle[T], Directive1[T]] =
extractField[NameDefaultUnmarshallerReceptacle[T], T] { nr => filter[T](nr.name, (nr.um: FSOU[T]) withDefaultValue nr.default) }

//////////////////// required parameter support ////////////////////

private def requiredFilter[T](paramName: String, fsou: FSOU[T], requiredValue: Any)(implicit vp: SFVP): Directive0 = {
extract { ctx =>
import ctx.{executionContext, materializer}
onComplete(fsou(vp.get(paramName))) flatMap {
case Success(value) if value == requiredValue => pass
case Success(value) => reject(InvalidRequiredValueForQueryParamRejection(paramName, requiredValue.toString, value.toString)).toDirective[Unit]
case _ => reject(MissingQueryParamRejection(paramName)).toDirective[Unit]
}
}.flatMap(identity)
}

implicit def forRVR[T](implicit fsu: FSU[T], vp: SFVP): StringDefAux[RequiredValueReceptacle[T], Directive0] =
stringDef[RequiredValueReceptacle[T], Directive0] { rvr => requiredFilter(rvr.name, fsu, rvr.requiredValue) }

implicit def forRVDR[T](implicit vp: SFVP): StringDefAux[RequiredValueUnmarshallerReceptacle[T], Directive0] =
stringDef[RequiredValueUnmarshallerReceptacle[T], Directive0] { rvr => requiredFilter(rvr.name, rvr.um, rvr.requiredValue) }

//////////////////// tuple support ////////////////////

import akka.http.scaladsl.server.util.BinaryPolyFunc
import akka.http.scaladsl.server.util.TupleOps._

implicit def forTuple[T](implicit fold: FoldLeft[Directive0, T, ConvertStringDefAndConcatenate.type]): StringDefAux[T, fold.Out] =
stringDef[T, fold.Out](fold(BasicDirectives.pass, _))

object ConvertStringDefAndConcatenate extends BinaryPolyFunc {
implicit def from[P, TA, TB](implicit sdef: StringDef[P] {type Out = Directive[TB]}, ev: Join[TA, TB]): BinaryPolyFunc.Case[Directive[TA], P, ConvertStringDefAndConcatenate.type] {type Out = Directive[ev.Out]} =
at[Directive[TA], P] { (a, t) => a & sdef(t) }
}

}
}
Loading