akka.http.scaladsl.server.Directives Scala Examples
The following examples show how to use akka.http.scaladsl.server.Directives.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: AbstractWebServer.scala From ohara with Apache License 2.0 | 6 votes |
package oharastream.ohara.shabondi.common import akka.Done import akka.actor.ActorSystem import akka.event.Logging import akka.http.scaladsl.Http import akka.http.scaladsl.Http.ServerBinding import akka.http.scaladsl.server.{Directives, Route} import akka.http.scaladsl.settings.ServerSettings import oharastream.ohara.common.util.Releasable import scala.concurrent._ import scala.concurrent.duration.Duration import scala.io.StdIn import scala.util.{Failure, Success} private[shabondi] abstract class AbstractWebServer extends Directives with Releasable { implicit protected val actorSystem: ActorSystem = ActorSystem(Logging.simpleName(this).replaceAll("\\$", "")) protected def routes: Route protected def postBinding(binding: ServerBinding): Unit = { val hostname = binding.localAddress.getHostName val port = binding.localAddress.getPort actorSystem.log.info(s"Server online at http://$hostname:$port/") } protected def postBindingFailure(cause: Throwable): Unit = { actorSystem.log.error(cause, s"Error starting the server ${cause.getMessage}") } protected def waitForShutdownSignal()(implicit ec: ExecutionContext): Future[Done] = { val promise = Promise[Done]() sys.addShutdownHook { promise.trySuccess(Done) } Future { blocking { if (StdIn.readLine("Press <RETURN> to stop Shabondi WebServer...\n") != null) promise.trySuccess(Done) } } promise.future } protected def postServerShutdown(): Unit = actorSystem.log.info("Shutting down the server") def start(bindInterface: String, port: Int): Unit = { start(bindInterface, port, ServerSettings(actorSystem)) } def start(bindInterface: String, port: Int, settings: ServerSettings): Unit = { implicit val executionContext: ExecutionContextExecutor = actorSystem.dispatcher val bindingFuture: Future[Http.ServerBinding] = Http().bindAndHandle( handler = routes, interface = bindInterface, port = port, settings = settings ) bindingFuture.onComplete { case Success(binding) => postBinding(binding) case Failure(cause) => postBindingFailure(cause) } Await.ready( bindingFuture.flatMap(_ => waitForShutdownSignal()), Duration.Inf ) bindingFuture .flatMap(_.unbind()) .onComplete { _ => postServerShutdown() actorSystem.terminate() } } override def close(): Unit = actorSystem.terminate() }
Example 2
Source File: ExampleApp.scala From akka-http-json with Apache License 2.0 | 5 votes |
package de.heikoseeberger.akkahttpjackson import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.model.HttpRequest import akka.http.scaladsl.server.Directives import akka.http.scaladsl.unmarshalling.Unmarshal import akka.stream.scaladsl.Source import scala.concurrent.Await import scala.concurrent.duration._ import scala.io.StdIn object ExampleApp { final case class Foo(bar: String) def main(args: Array[String]): Unit = { implicit val system = ActorSystem() // provide an implicit ObjectMapper if you want serialization/deserialization to use it // instead of a default ObjectMapper configured only with DefaultScalaModule provided // by JacksonSupport // // for example: // // implicit val objectMapper = new ObjectMapper() // .registerModule(DefaultScalaModule) // .registerModule(new GuavaModule()) Http().bindAndHandle(route, "127.0.0.1", 8000) StdIn.readLine("Hit ENTER to exit") Await.ready(system.terminate(), Duration.Inf) } def route(implicit sys: ActorSystem) = { import Directives._ import JacksonSupport._ pathSingleSlash { post { entity(as[Foo]) { foo => complete { foo } } } } ~ pathPrefix("stream") { post { entity(as[SourceOf[Foo]]) { fooSource: SourceOf[Foo] => complete(fooSource.throttle(1, 2.seconds)) } } ~ get { pathEndOrSingleSlash { complete( Source(0 to 5) .throttle(1, 1.seconds) .map(i => Foo(s"bar-$i")) ) } ~ pathPrefix("remote") { onSuccess(Http().singleRequest(HttpRequest(uri = "http://localhost:8000/stream"))) { response => complete(Unmarshal(response).to[SourceOf[Foo]]) } } } } } }
Example 3
Source File: ExampleApp.scala From akka-http-json with Apache License 2.0 | 5 votes |
package de.heikoseeberger.akkahttpcirce import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.marshalling.Marshal import akka.http.scaladsl.model.{ HttpRequest, RequestEntity } import akka.http.scaladsl.server.Directives import akka.http.scaladsl.unmarshalling.Unmarshal import akka.stream.scaladsl.Source import scala.io.StdIn import scala.concurrent.duration._ object ExampleApp { private final case class Foo(bar: String) def main(args: Array[String]): Unit = { implicit val system = ActorSystem() Http().bindAndHandle(route, "127.0.0.1", 8000) StdIn.readLine("Hit ENTER to exit") system.terminate() } private def route(implicit sys: ActorSystem) = { import Directives._ import FailFastCirceSupport._ import io.circe.generic.auto._ pathSingleSlash { post { entity(as[Foo]) { foo => complete { foo } } } } ~ pathPrefix("stream") { post { entity(as[SourceOf[Foo]]) { fooSource: SourceOf[Foo] => import sys._ Marshal(Source.single(Foo("a"))).to[RequestEntity] complete(fooSource.throttle(1, 2.seconds)) } } ~ get { pathEndOrSingleSlash { complete( Source(0 to 5) .throttle(1, 1.seconds) .map(i => Foo(s"bar-$i")) ) } ~ pathPrefix("remote") { onSuccess(Http().singleRequest(HttpRequest(uri = "http://localhost:8000/stream"))) { response => complete(Unmarshal(response).to[SourceOf[Foo]]) } } } } } }
Example 4
Source File: WebService.scala From sbt-web-scalajs with Apache License 2.0 | 5 votes |
package com.example.akkahttpscalajs import akka.http.scaladsl.server.Directives import com.example.akkahttpscalajs.shared.SharedMessages import com.example.akkahttpscalajs.twirl.Implicits._ class WebService() extends Directives { val route = { pathSingleSlash { get { complete { com.example.akkahttpscalajs.html.index.render(SharedMessages.itWorks) } } } ~ pathPrefix("assets" / Remaining) { file => // optionally compresses the response with Gzip or Deflate // if the client accepts compressed responses encodeResponse { getFromResource("public/" + file) } } } }
Example 5
Source File: BaseEndpointsSpec.scala From service-container with Apache License 2.0 | 5 votes |
package com.github.vonnagy.service.container.http import java.net.InetAddress import akka.http.scaladsl.model.headers.`Remote-Address` import akka.http.scaladsl.model.{RemoteAddress, StatusCodes} import akka.http.scaladsl.server.Directives import com.github.vonnagy.service.container.Specs2RouteTest import com.github.vonnagy.service.container.http.routing.Rejection.NotFoundRejection import org.specs2.mutable.Specification class BaseEndpointsSpec extends Specification with Directives with Specs2RouteTest { val endpoints = new BaseEndpoints "The base routing infrastructure" should { "return no content for favicon.ico" in { Get("/favicon.ico") ~> endpoints.route ~> check { status must be equalTo StatusCodes.NoContent } } "support a call to ping" in { Get("/ping") ~> endpoints.route ~> check { responseAs[String] must startWith("pong") status must beEqualTo(StatusCodes.OK) } } "a call to shutdown should return and error due to CIDR rules" in { Post("/shutdown").withHeaders(`Remote-Address`(RemoteAddress(InetAddress.getByName("192.168.1.1")))) ~> endpoints.route ~> check { handled must beFalse rejections.size must beEqualTo(1) rejections.head must be equalTo(NotFoundRejection("The requested resource could not be found")) } } } }
Example 6
Source File: RoutedServiceSpec.scala From service-container with Apache License 2.0 | 5 votes |
package com.github.vonnagy.service.container.http.routing import akka.actor._ import akka.http.scaladsl.model.{HttpEntity, MediaTypes, StatusCodes} import akka.http.scaladsl.server.{Directives, Route} import akka.testkit.{TestActorRef, TestProbe} import com.github.vonnagy.service.container.Specs2RouteTest import com.github.vonnagy.service.container.http.{DefaultMarshallers, RejectionResponse} import org.specs2.mutable.Specification class RoutedServiceSpec extends Specification with Directives with Specs2RouteTest { case class TestEntity(id: Int, name: String) val probe = new TestProbe(system) val httpAct = TestActorRef(Props(new Actor with RoutedService with DefaultMarshallers { def receive = routeReceive }), "http") val svc = httpAct.underlyingActor.asInstanceOf[RoutedService] def echoComplete[T]: T => Route = { x ⇒ complete(x.toString) } "The RoutedService" should { "allow for routes to be added after the system is already loaded" in { // This should create the actor and register the endpoints val r = new RoutedEndpoints { def route = { path("test2") { complete("test2") } } } probe.send(httpAct, AddRoute(r)) probe.expectMsg(RouteAdded) Get("/test2") ~> svc.buildRoute(svc.routes) ~> check { responseAs[String] must be equalTo "test2" } } "respond with UnprocessableEntity for requests resulting in a MalformedFormFieldRejection" in { implicit val unmarsh = svc.jsonUnmarshaller[TestEntity] implicit val rejMarsh = svc.jsonUnmarshaller[RejectionResponse] val postRoute = new RoutedEndpoints { def route = { post { path("test4") { entity(as[TestEntity]) { echoComplete } } } } } probe.send(httpAct, AddRoute(postRoute)) probe.expectMsg(RouteAdded) import svc.defaultJsonFormats val ent = TestEntity(100, "product") Post("/test4", HttpEntity(MediaTypes.`application/json`, svc.serialization.write(ent))) ~> handleRejections(svc.rejectionHandler)(svc.buildRoute(svc.routes)) ~> check { status === StatusCodes.UnprocessableEntity mediaType === MediaTypes.`application/json` responseAs[RejectionResponse] must not beNull } } "respond with RejectionResponse for requests that error out" in { implicit val rejMarsh = svc.jsonUnmarshaller[RejectionResponse] val postRoute = new RoutedEndpoints { def route = { get { path("test5") { ctx => throw new Exception("test") } } } } probe.send(httpAct, AddRoute(postRoute)) probe.expectMsg(RouteAdded) Get("/test5") ~> Route.seal(svc.buildRoute(svc.routes))(svc.routeSettings, exceptionHandler = svc.exceptionHandler, rejectionHandler = svc.rejectionHandler) ~> check { mediaType === MediaTypes.`application/json` responseAs[RejectionResponse] must not beNull } } } }
Example 7
Source File: RoutingHandlerSpec.scala From service-container with Apache License 2.0 | 5 votes |
package com.github.vonnagy.service.container.http.routing import akka.http.scaladsl.model.StatusCodes._ import akka.http.scaladsl.model.ContentTypes._ import akka.http.scaladsl.server.{Directives, MalformedRequestContentRejection, MissingCookieRejection, Route} import com.github.vonnagy.service.container.Specs2RouteTest import com.github.vonnagy.service.container.http.routing.Rejection.DuplicateRejection import org.specs2.mutable.Specification class RoutingHandlerSpec extends Specification with Specs2RouteTest with Directives { val handler = new RoutingHandler { def conf = system.settings.config } val dummyRoute = pathPrefix("test") { get { path("duplicate") { reject(DuplicateRejection("test")) } ~ path("malformed") { reject(MalformedRequestContentRejection("test", new Exception("test"))) } ~ path("cookie") { reject(MissingCookieRejection("test")) } ~ path("exception") { throw new NullPointerException("test") } } } "the routing handler" should { "provide custom rejection handlers" in { implicit val rejHandler = handler.rejectionHandler val sr = Route.seal(dummyRoute) Get("/test/duplicate") ~> sr ~> check { status must be equalTo BadRequest responseAs[String] must be equalTo( """{"code":400,"message":"The request contains bad syntax or cannot be fulfilled.","details":"\"test\""}""") } Get("/test/malformed") ~> sr ~> check { status must be equalTo UnprocessableEntity responseAs[String] must be equalTo( """{"code":422,"message":"The request was well-formed but was unable to be followed due to semantic errors.","details":"\"test\""}""") } } "use the default rejection handler as a fallback" in { implicit val rejHandler = handler.rejectionHandler val sr = Route.seal(dummyRoute) Get("/test/cookie") ~> sr ~> check { status must be equalTo BadRequest responseAs[String] must be equalTo( """{"code":400,"message":"The request contains bad syntax or cannot be fulfilled.","details":"Request is missing required cookie 'test'"}""") } } "provide custom exception handlers" in { implicit val exHandler = handler.exceptionHandler val sr = Route.seal(dummyRoute) Get("/test/exception") ~> sr ~> check { status must be equalTo InternalServerError contentType must be equalTo `application/json` responseAs[String] must be equalTo( """{"code":500,"message":"There was an internal server error.","details":"Something bad happened"}""") } } } }
Example 8
Source File: EchoEnumService.scala From swagger-akka-http-sample with Apache License 2.0 | 5 votes |
package com.example.akka.echoenum import akka.http.scaladsl.server.{Directives, Route} import com.example.akka.DefaultJsonFormats import com.fasterxml.jackson.core.`type`.TypeReference import com.fasterxml.jackson.module.scala.JsonScalaEnumeration import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.media.{Content, Schema} import io.swagger.v3.oas.annotations.parameters.RequestBody import io.swagger.v3.oas.annotations.responses.ApiResponse import javax.ws.rs.core.MediaType import javax.ws.rs.{Consumes, POST, Path, Produces} import spray.json.{DeserializationException, JsString, JsValue, RootJsonFormat} @Path("/echoenum") object EchoEnumService extends Directives with DefaultJsonFormats { //case class EchoEnum(@Schema(required = true, `type` = "string", allowableValues = Array("TALL", "GRANDE", "VENTI")) // enumValue: SizeEnum.Value) class SizeEnumTypeClass extends TypeReference[SizeEnum.type] case class EchoEnum(@JsonScalaEnumeration(classOf[SizeEnumTypeClass]) enumValue: SizeEnum.Value) implicit val enumFormat: RootJsonFormat[SizeEnum.Value] = new RootJsonFormat[SizeEnum.Value] { def write(obj: SizeEnum.Value): JsValue = JsString(obj.toString) def read(json: JsValue): SizeEnum.Value = { json match { case JsString(txt) => SizeEnum.withName(txt) case somethingElse => throw DeserializationException(s"Expected a value from enum $SizeEnum instead of $somethingElse") } } } implicit val echoEnumFormat: RootJsonFormat[EchoEnum] = jsonFormat1(EchoEnum) val route: Route = echo @POST @Consumes(Array(MediaType.APPLICATION_JSON)) @Produces(Array(MediaType.APPLICATION_JSON)) @Operation(summary = "Echo Enum", description = "Echo Enum", requestBody = new RequestBody(content = Array(new Content(schema = new Schema(implementation = classOf[EchoEnum])))), responses = Array( new ApiResponse(responseCode = "200", description = "Echo Enum", content = Array(new Content(schema = new Schema(implementation = classOf[EchoEnum])))), new ApiResponse(responseCode = "400", description = "Bad Request")) ) def echo: Route = path("echoenum") { post { entity(as[EchoEnum]) { request => complete(request) } } } }
Example 9
Source File: HelloService.scala From swagger-akka-http-sample with Apache License 2.0 | 5 votes |
package com.example.akka.hello import javax.ws.rs.{GET, Path, Produces} import akka.actor.ActorRef import akka.http.scaladsl.server.{Directives, Route} import akka.pattern.ask import akka.util.Timeout import com.example.akka.DefaultJsonFormats import com.example.akka.hello.HelloActor._ import io.swagger.v3.oas.annotations.enums.ParameterIn import io.swagger.v3.oas.annotations.media.{Content, Schema} import io.swagger.v3.oas.annotations.responses.ApiResponse import io.swagger.v3.oas.annotations.{Operation, Parameter} import javax.ws.rs.core.MediaType import spray.json.RootJsonFormat import scala.concurrent.ExecutionContext import scala.concurrent.duration.DurationInt @Path("/hello") class HelloService(hello: ActorRef)(implicit executionContext: ExecutionContext) extends Directives with DefaultJsonFormats { implicit val timeout: Timeout = Timeout(2.seconds) implicit val greetingFormat: RootJsonFormat[Greeting] = jsonFormat1(Greeting) val route: Route = getHello ~ getHelloSegment @GET @Produces(Array(MediaType.APPLICATION_JSON)) @Operation(summary = "Return Hello greeting (anonymous)", description = "Return Hello greeting for anonymous request", responses = Array( new ApiResponse(responseCode = "200", description = "Hello response", content = Array(new Content(schema = new Schema(implementation = classOf[Greeting])))), new ApiResponse(responseCode = "500", description = "Internal server error")) ) def getHello: Route = path("hello") { get { complete { (hello ? AnonymousHello).mapTo[Greeting] } } } @GET @Produces(Array(MediaType.APPLICATION_JSON)) @Operation(summary = "Return Hello greeting", description = "Return Hello greeting for named user", parameters = Array(new Parameter(name = "name", in = ParameterIn.PATH, description = "user name")), responses = Array( new ApiResponse(responseCode = "200", description = "Hello response", content = Array(new Content(schema = new Schema(implementation = classOf[Greeting])))), new ApiResponse(responseCode = "500", description = "Internal server error")) ) def getHelloSegment: Route = path("hello" / Segment) { name => get { complete { (hello ? Hello(name)).mapTo[Greeting] } } } }
Example 10
Source File: AddOptionService.scala From swagger-akka-http-sample with Apache License 2.0 | 5 votes |
package com.example.akka.addoption import javax.ws.rs.{Consumes, POST, Path, Produces} import akka.actor.ActorRef import akka.http.scaladsl.server.{Directives, Route} import akka.pattern.ask import akka.util.Timeout import com.example.akka.DefaultJsonFormats import com.example.akka.addoption.AddOptionActor._ import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.media.{Content, Schema} import io.swagger.v3.oas.annotations.parameters.RequestBody import io.swagger.v3.oas.annotations.responses.ApiResponse import javax.ws.rs.core.MediaType import spray.json.RootJsonFormat import scala.concurrent.ExecutionContext import scala.concurrent.duration.DurationInt @Path("/addOption") class AddOptionService(addActor: ActorRef)(implicit executionContext: ExecutionContext) extends Directives with DefaultJsonFormats { implicit val timeout: Timeout = Timeout(2.seconds) implicit val requestFormat: RootJsonFormat[AddOptionRequest] = jsonFormat2(AddOptionRequest) implicit val responseFormat: RootJsonFormat[AddOptionResponse] = jsonFormat1(AddOptionResponse) val route: Route = addOption @POST @Consumes(Array(MediaType.APPLICATION_JSON)) @Produces(Array(MediaType.APPLICATION_JSON)) @Operation(summary = "Add integers", description = "Add integers", requestBody = new RequestBody(content = Array(new Content(schema = new Schema(implementation = classOf[AddOptionRequest])))), responses = Array( new ApiResponse(responseCode = "200", description = "Add response", content = Array(new Content(schema = new Schema(implementation = classOf[AddOptionResponse])))), new ApiResponse(responseCode = "500", description = "Internal server error")) ) def addOption: Route = path("addOption") { post { entity(as[AddOptionRequest]) { request => complete { (addActor ? request).mapTo[AddOptionResponse] } } } } }
Example 11
Source File: EchoEnumeratumService.scala From swagger-akka-http-sample with Apache License 2.0 | 5 votes |
package com.example.akka.echoenumeratum import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport import akka.http.scaladsl.server.{Directives, Route} import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.media.{Content, Schema} import io.swagger.v3.oas.annotations.parameters.RequestBody import io.swagger.v3.oas.annotations.responses.ApiResponse import javax.ws.rs.core.MediaType import javax.ws.rs.{Consumes, POST, Path, Produces} import pl.iterators.kebs.json.{KebsEnumFormats, KebsSpray} import spray.json.{DefaultJsonProtocol, RootJsonFormat} @Path("/echoenumeratum") object EchoEnumeratumService extends Directives with SprayJsonSupport with DefaultJsonProtocol with KebsSpray with KebsEnumFormats { case class EchoEnumeratum(enumValue: SizeEnum) implicit val echoEnumeratumFormat: RootJsonFormat[EchoEnumeratum] = jsonFormatN[EchoEnumeratum] val route: Route = echo @POST @Consumes(Array(MediaType.APPLICATION_JSON)) @Produces(Array(MediaType.APPLICATION_JSON)) @Operation(summary = "Echo Enumeratum", description = "Echo Enumeratum", requestBody = new RequestBody(content = Array(new Content(schema = new Schema(implementation = classOf[EchoEnumeratum])))), responses = Array( new ApiResponse(responseCode = "200", description = "Echo Enumeratum", content = Array(new Content(schema = new Schema(implementation = classOf[EchoEnumeratum])))), new ApiResponse(responseCode = "400", description = "Bad Request")) ) def echo: Route = path("echoenumeratum") { post { entity(as[EchoEnumeratum]) { request => complete(request) } } } }
Example 12
Source File: AddService.scala From swagger-akka-http-sample with Apache License 2.0 | 5 votes |
package com.example.akka.add import javax.ws.rs.{Consumes, POST, Path, Produces} import akka.actor.ActorRef import akka.http.scaladsl.server.{Directives, Route} import akka.pattern.ask import akka.util.Timeout import com.example.akka.DefaultJsonFormats import com.example.akka.add.AddActor._ import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.media.{Content, Schema} import io.swagger.v3.oas.annotations.parameters.RequestBody import io.swagger.v3.oas.annotations.responses.ApiResponse import javax.ws.rs.core.MediaType import spray.json.RootJsonFormat import scala.concurrent.ExecutionContext import scala.concurrent.duration.DurationInt @Path("/add") class AddService(addActor: ActorRef)(implicit executionContext: ExecutionContext) extends Directives with DefaultJsonFormats { implicit val timeout: Timeout = Timeout(2.seconds) implicit val requestFormat: RootJsonFormat[AddRequest] = jsonFormat1(AddRequest) implicit val responseFormat: RootJsonFormat[AddResponse] = jsonFormat1(AddResponse) val route: Route = add @POST @Consumes(Array(MediaType.APPLICATION_JSON)) @Produces(Array(MediaType.APPLICATION_JSON)) @Operation(summary = "Add integers", description = "Add integers", requestBody = new RequestBody(content = Array(new Content(schema = new Schema(implementation = classOf[AddRequest])))), responses = Array( new ApiResponse(responseCode = "200", description = "Add response", content = Array(new Content(schema = new Schema(implementation = classOf[AddResponse])))), new ApiResponse(responseCode = "500", description = "Internal server error")) ) def add: Route = path("add") { post { entity(as[AddRequest]) { request => complete { (addActor ? request).mapTo[AddResponse] } } } } }
Example 13
Source File: EchoListService.scala From swagger-akka-http-sample with Apache License 2.0 | 5 votes |
package com.example.akka.echolist import akka.http.scaladsl.server.{Directives, Route} import com.example.akka.DefaultJsonFormats import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.media.{Content, Schema} import io.swagger.v3.oas.annotations.parameters.RequestBody import io.swagger.v3.oas.annotations.responses.ApiResponse import javax.ws.rs.core.MediaType import javax.ws.rs.{Consumes, POST, Path, Produces} import pl.iterators.kebs.json.KebsSpray import spray.json.RootJsonFormat @Path("/echolist") object EchoListService extends Directives with DefaultJsonFormats with KebsSpray { case class EchoList(listName: String, values: Seq[String]) implicit val echoListFormat: RootJsonFormat[EchoList] = jsonFormatN[EchoList] val route: Route = echo @POST @Consumes(Array(MediaType.APPLICATION_JSON)) @Produces(Array(MediaType.APPLICATION_JSON)) @Operation(summary = "Echo List", description = "Echo List", requestBody = new RequestBody(content = Array(new Content(schema = new Schema(implementation = classOf[EchoList])))), responses = Array( new ApiResponse(responseCode = "200", description = "Echo List", content = Array(new Content(schema = new Schema(implementation = classOf[EchoList])))), new ApiResponse(responseCode = "400", description = "Bad Request")) ) def echo: Route = path("echolist") { post { entity(as[EchoList]) { request => complete(request) } } } }
Example 14
Source File: StatsEndpoint.scala From akka-kubernetes-tests with Apache License 2.0 | 5 votes |
package akka.kubernetes.soak import akka.actor.{ActorRef, ActorSystem} import akka.event.Logging import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.server.{Directives, Route} import spray.json.DefaultJsonProtocol import akka.pattern.ask import akka.util.Timeout import scala.concurrent.duration._ import scala.util.{Failure, Success} // collect your json format instances into a support trait: trait StatsJsonSupport extends SprayJsonSupport with DefaultJsonProtocol { implicit val testResultFormat = jsonFormat2(TestResult) implicit val testResultsFormat = jsonFormat7(TestResults) } class StatsEndpoint(system: ActorSystem, client: ActorRef) extends Directives with StatsJsonSupport { private implicit val askTimeout = Timeout(5.seconds) private val log = Logging(system, getClass) val route: Route = path("stats") { get { onComplete(client.ask(GetTestResults()).mapTo[TestResults]) { case Failure(t) => log.error(t, "Failed to get test results") complete(StatusCodes.InternalServerError) case Success(value) => complete(value) } } } }
Example 15
Source File: CorsBenchmark.scala From akka-http-cors with Apache License 2.0 | 5 votes |
package ch.megard.akka.http.cors import java.util.concurrent.TimeUnit import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.Http.ServerBinding import akka.http.scaladsl.model.headers.{Origin, `Access-Control-Request-Method`} import akka.http.scaladsl.model.{HttpMethods, HttpRequest} import akka.http.scaladsl.server.Directives import akka.http.scaladsl.unmarshalling.Unmarshal import ch.megard.akka.http.cors.scaladsl.CorsDirectives import ch.megard.akka.http.cors.scaladsl.settings.CorsSettings import com.typesafe.config.ConfigFactory import org.openjdk.jmh.annotations._ import scala.concurrent.duration._ import scala.concurrent.{Await, ExecutionContext} @State(Scope.Benchmark) @OutputTimeUnit(TimeUnit.SECONDS) @BenchmarkMode(Array(Mode.Throughput)) class CorsBenchmark extends Directives with CorsDirectives { private val config = ConfigFactory.parseString("akka.loglevel = ERROR").withFallback(ConfigFactory.load()) implicit private val system: ActorSystem = ActorSystem("CorsBenchmark", config) implicit private val ec: ExecutionContext = scala.concurrent.ExecutionContext.global private val http = Http() private val corsSettings = CorsSettings.default private var binding: ServerBinding = _ private var request: HttpRequest = _ private var requestCors: HttpRequest = _ private var requestPreflight: HttpRequest = _ @Setup def setup(): Unit = { val route = { path("baseline") { get { complete("ok") } } ~ path("cors") { cors(corsSettings) { get { complete("ok") } } } } val origin = Origin("http://example.com") binding = Await.result(http.bindAndHandle(route, "127.0.0.1", 0), 1.second) val base = s"http://${binding.localAddress.getHostString}:${binding.localAddress.getPort}" request = HttpRequest(uri = base + "/baseline") requestCors = HttpRequest( method = HttpMethods.GET, uri = base + "/cors", headers = List(origin) ) requestPreflight = HttpRequest( method = HttpMethods.OPTIONS, uri = base + "/cors", headers = List(origin, `Access-Control-Request-Method`(HttpMethods.GET)) ) } @TearDown def shutdown(): Unit = { val f = for { _ <- http.shutdownAllConnectionPools() _ <- binding.terminate(1.second) _ <- system.terminate() } yield () Await.ready(f, 5.seconds) } @Benchmark def baseline(): Unit = { val f = http.singleRequest(request).flatMap(r => Unmarshal(r.entity).to[String]) assert(Await.result(f, 1.second) == "ok") } @Benchmark def default_cors(): Unit = { val f = http.singleRequest(requestCors).flatMap(r => Unmarshal(r.entity).to[String]) assert(Await.result(f, 1.second) == "ok") } @Benchmark def default_preflight(): Unit = { val f = http.singleRequest(requestPreflight).flatMap(r => Unmarshal(r.entity).to[String]) assert(Await.result(f, 1.second) == "") } }
Example 16
Source File: Webservice.scala From akka-http-scala-js-websocket-chat with MIT License | 5 votes |
package example.akkawschat import java.util.Date import akka.actor.ActorSystem import akka.http.scaladsl.model.ws.{ Message, TextMessage } import scala.concurrent.duration._ import akka.http.scaladsl.server.Directives import akka.stream.scaladsl.Flow import upickle.default._ import shared.Protocol import shared.Protocol._ import scala.util.Failure class Webservice(implicit system: ActorSystem) extends Directives { val theChat = Chat.create() import system.dispatcher system.scheduler.scheduleAtFixedRate(15.second, 15.second) { () => theChat.injectMessage(ChatMessage(sender = "clock", s"Bling! The time is ${new Date().toString}.")) } def route = get { pathSingleSlash { getFromResource("web/index.html") } ~ // Scala-JS puts them in the root of the resource directory per default, // so that's where we pick them up path("frontend-launcher.js")(getFromResource("frontend-launcher.js")) ~ path("frontend-fastopt.js")(getFromResource("frontend-fastopt.js")) ~ path("chat") { parameter("name") { name => handleWebSocketMessages(websocketChatFlow(sender = name)) } } } ~ getFromResourceDirectory("web") def websocketChatFlow(sender: String): Flow[Message, Message, Any] = Flow[Message] .collect { case TextMessage.Strict(msg) => msg // unpack incoming WS text messages... // This will lose (ignore) messages not received in one chunk (which is // unlikely because chat messages are small) but absolutely possible // FIXME: We need to handle TextMessage.Streamed as well. } .via(theChat.chatFlow(sender)) // ... and route them through the chatFlow ... .map { case msg: Protocol.Message => TextMessage.Strict(write(msg)) // ... pack outgoing messages into WS JSON messages ... } .via(reportErrorsFlow) // ... then log any processing errors on stdin def reportErrorsFlow[T]: Flow[T, T, Any] = Flow[T] .watchTermination()((_, f) => f.onComplete { case Failure(cause) => println(s"WS stream failed with $cause") case _ => // ignore regular completion }) }
Example 17
Source File: GrpcInteropSpec.scala From akka-grpc with Apache License 2.0 | 5 votes |
package akka.grpc.interop import akka.stream.{ Materializer, SystemMaterializer } import akka.http.scaladsl.model._ import akka.http.scaladsl.server.RouteResult.Complete import akka.http.scaladsl.server.{ Directive0, Directives, Route } import io.grpc.testing.integration.TestServiceHandlerFactory import io.grpc.testing.integration.test.TestService import org.scalatest.WordSpec import scala.collection.immutable // Generated by our plugin import io.grpc.testing.integration.test.TestServiceHandler class GrpcInteropIoWithAkkaSpec extends GrpcInteropTests(IoGrpcJavaServerProvider, AkkaHttpClientProviderScala) class GrpcInteropAkkaScalaWithIoSpec extends GrpcInteropTests(AkkaHttpServerProviderScala, IoGrpcJavaClientProvider) class GrpcInteropAkkaScalaWithAkkaSpec extends GrpcInteropTests(AkkaHttpServerProviderScala, AkkaHttpClientProviderScala) class GrpcInteropAkkaJavaWithIoSpec extends GrpcInteropTests(AkkaHttpServerProviderJava, IoGrpcJavaClientProvider) class GrpcInteropAkkaJavaWithAkkaSpec extends GrpcInteropTests(AkkaHttpServerProviderJava, AkkaHttpClientProviderScala) object AkkaHttpServerProviderScala extends AkkaHttpServerProvider { import Directives._ val label: String = "akka-grpc server scala" val pendingCases = Set() val server = AkkaGrpcServerScala(implicit sys => { implicit val ec = sys.dispatcher val requestHandler = TestServiceHandler(new TestServiceImpl()) val route: Route = (pathPrefix(TestService.name) & echoHeaders) { ctx => requestHandler(ctx.request).map(Complete) } implicit val mat: Materializer = SystemMaterializer(sys).materializer Route.asyncHandler(Route.seal(route)) }) val echoHeaders: Directive0 = extractRequest.flatMap(request => { val initialHeaderToEcho = request.headers.find(_.name() == "x-grpc-test-echo-initial") val trailingHeaderToEcho = request.headers.find(_.name() == "x-grpc-test-echo-trailing-bin") mapResponseHeaders(h => h ++ initialHeaderToEcho) & mapTrailingResponseHeaders(h => h ++ trailingHeaderToEcho) }) // TODO to be moved to the runtime lib (or even akka-http itself?) def mapTrailingResponseHeaders(f: immutable.Seq[HttpHeader] => immutable.Seq[HttpHeader]) = mapResponse(response => response.withEntity(response.entity match { case HttpEntity.Chunked(contentType, data) => { HttpEntity.Chunked(contentType, data.map { case chunk: HttpEntity.Chunk => chunk case last: HttpEntity.LastChunk => HttpEntity.LastChunk(last.extension, f(last.trailer)) }) } case _ => throw new IllegalArgumentException("Trailing response headers are only supported on Chunked responses") })) } object AkkaHttpServerProviderJava extends AkkaHttpServerProvider { val label: String = "akka-grpc server java" val pendingCases = Set( "custom_metadata" ) val server = new AkkaGrpcServerJava((mat, sys) => { TestServiceHandlerFactory.create(new JavaTestServiceImpl(mat), sys) }) } object AkkaHttpClientProviderScala extends AkkaHttpClientProvider { val label: String = "akka-grpc scala client tester" def client = AkkaGrpcClientScala(settings => implicit sys => new AkkaGrpcClientTester(settings)) }
Example 18
Source File: DevApi.scala From mist with Apache License 2.0 | 5 votes |
package io.hydrosphere.mist.master.interfaces.http import akka.http.scaladsl.marshalling import akka.http.scaladsl.model import akka.http.scaladsl.model.{HttpResponse, StatusCodes} import akka.http.scaladsl.server.Directives import akka.http.scaladsl.server.directives.ParameterDirectives import cats.data._ import cats.implicits._ import io.hydrosphere.mist.master.{JobDetails, MainService} import io.hydrosphere.mist.master.interfaces.JsonCodecs import io.hydrosphere.mist.master.interfaces.http.HttpV2Base.completeOpt import io.hydrosphere.mist.master.models.DevJobStartRequestModel object DevApi { import Directives._ import JsonCodecs._ import ParameterDirectives.ParamMagnet import akka.http.scaladsl.server._ import scala.concurrent.ExecutionContext.Implicits.global def devRoutes(masterService: MainService): Route = { val exceptionHandler = ExceptionHandler { case iae: IllegalArgumentException => complete((StatusCodes.BadRequest, s"Bad request: ${iae.getMessage}")) case ex => complete(HttpResponse(StatusCodes.InternalServerError, entity = s"Server error: ${ex.getMessage}")) } path( "v2" / "hidden" / "devrun" ) { post( parameter('force ? false) { force => entity(as[DevJobStartRequestModel]) { req => handleExceptions(exceptionHandler) { val execInfo = masterService.devRun(req.toCommon, JobDetails.Source.Http) if (force) complete(execInfo.map(_.toJobResult)) else complete(execInfo.map(_.toJobStartResponse)) } } }) } } }
Example 19
Source File: HttpUi.scala From mist with Apache License 2.0 | 5 votes |
package io.hydrosphere.mist.master.interfaces.http import akka.http.scaladsl.model._ import akka.http.scaladsl.server.directives.ContentTypeResolver.Default import akka.http.scaladsl.server.{Directives, RejectionHandler, Route} private val fallbackToSpa = RejectionHandler.newBuilder() .handleNotFound(getFromFile(index)) .result() val route: Route = { pathPrefix("ui") { get { pathEnd { redirect("/ui/", PermanentRedirect) } ~ pathSingleSlash { getFromFile(index) } ~ handleRejections(fallbackToSpa) { getFromDirectory(path) } } } } }
Example 20
Source File: MultiParamSpec.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.akkaHttp import akka.http.scaladsl.server.{Directives, MissingQueryParamRejection} import akka.http.scaladsl.testkit.ScalatestRouteTest import ru.tinkoff.tschema.akkaHttp.MultiParamSpec.{Page, route} import ru.tinkoff.tschema.param.HttpParam import shapeless.Witness import scala.language.reflectiveCalls import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class MultiParamSpec extends AnyFlatSpec with Matchers with ScalatestRouteTest { "Multi parameter case class" should "require first param" in { Get("/required") ~> route ~> check { rejections should contain(MissingQueryParamRejection("from")) } } it should "require second param" in { Get("/required?from=3") ~> route ~> check { rejections should contain(MissingQueryParamRejection("to")) } } it should "not require optional field" in { Get("/required?from=3&to=5") ~> route ~> check { responseAs[String] shouldBe Page(3, 5).toString } } it should "supply optional field" in { Get("/required?from=3&to=5&hmm=true") ~> route ~> check { responseAs[String] shouldBe Page(3, 5, Some(true)).toString } } it should "not require whole optional record" in { Get("/optional?from=3") ~> route ~> check { responseAs[String] shouldBe None.toString } Get("/optional?to=3") ~> route ~> check { responseAs[String] shouldBe None.toString } Get("/optional") ~> route ~> check { responseAs[String] shouldBe None.toString } } it should "supply optional record" in { Get("/optional?from=3&to=5&hmm=false") ~> route ~> check { responseAs[String] shouldBe Some(Page(3, 5, Some(false))).toString } } it should "supply partial optional record with optional fields" in { Get("/optional?from=3&to=5") ~> route ~> check { responseAs[String] shouldBe Some(Page(3, 5)).toString } } } object MultiParamSpec { val page = Witness.`"page"` final case class Page(from: Int, to: Long, hmm: Option[Boolean] = None) object Page { implicit val pageParam: HttpParam[Page] = HttpParam.generate } val api = { import ru.tinkoff.tschema.syntax._ (operation("required") |> queryParam[Page]("page") |> complete[String]) <|> (operation("optional") |> queryParam[Option[Page]]("page") |> complete[String]) } val handler = new { def required(page: Page): String = page.toString def optional(page: Option[Page]): String = page.toString } val route = MkRoute(api)(handler) import Directives._ val kek = Directives.parameter("kek".as[Option[String]])(os => complete(os)) parameters(("raw".as[Boolean], "offset".as[Int], "pageSize".as[Int])) }
Example 21
Source File: Api.scala From whirlwind-tour-akka-typed with Apache License 2.0 | 5 votes |
package de.heikoseeberger.wtat import akka.actor.{ ActorSystem, Scheduler } import akka.http.scaladsl.Http import akka.http.scaladsl.Http.ServerBinding import akka.http.scaladsl.model.StatusCodes.{ Conflict, Created, NoContent, NotFound } import akka.http.scaladsl.server.{ Directives, Route } import akka.stream.Materializer import akka.actor.typed.scaladsl.Actor import akka.actor.typed.scaladsl.AskPattern.Askable import akka.actor.typed.{ ActorRef, Behavior } import akka.util.Timeout import de.heikoseeberger.akkahttpcirce.ErrorAccumulatingCirceSupport import java.net.InetSocketAddress import org.apache.logging.log4j.scala.Logging import scala.concurrent.duration.FiniteDuration import scala.util.{ Failure, Success } object Api extends Logging { sealed trait Command private final case object HandleBindFailure extends Command private final case class HandleBound(address: InetSocketAddress) extends Command final val Name = "api" def apply(address: String, port: Int, userRepository: ActorRef[UserRepository.Command], userView: ActorRef[UserView.Command], askTimeout: FiniteDuration)(implicit mat: Materializer): Behavior[Command] = Actor.deferred { context => import akka.actor.typed.scaladsl.adapter._ import context.executionContext implicit val s: ActorSystem = context.system.toUntyped val self = context.self Http() .bindAndHandle(route(userRepository, userView)(askTimeout, context.system.scheduler), address, port) .onComplete { case Failure(_) => self ! HandleBindFailure case Success(ServerBinding(address)) => self ! HandleBound(address) } Actor.immutable { case (_, HandleBindFailure) => logger.error(s"Stopping, because cannot bind to $address:$port!") Actor.stopped case (_, HandleBound(address)) => logger.info(s"Bound to $address") Actor.ignore } } def route( userRepository: ActorRef[UserRepository.Command], userView: ActorRef[UserView.Command] )(implicit askTimeout: Timeout, scheduler: Scheduler): Route = { import Directives._ import ErrorAccumulatingCirceSupport._ import io.circe.generic.auto._ import io.circe.refined._ pathEndOrSingleSlash { get { complete { import UserView._ (userView ? GetUsers).mapTo[Users] } } ~ post { entity(as[User]) { user => import UserRepository._ onSuccess(userRepository ? addUser(user)) { case UsernameTaken(_) => complete(Conflict) case UserAdded(_) => complete(Created) } } } } ~ path(Segment) { username => delete { import UserRepository._ onSuccess(userRepository ? removeUser(username)) { case UsernameUnknown(_) => complete(NotFound) case UserRemoved(_) => complete(NoContent) } } } } }
Example 22
Source File: Api.scala From full-scala-stack with Apache License 2.0 | 5 votes |
package api import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.server.directives.DebuggingDirectives import akka.http.scaladsl.server.{ Directives, Route, RouteConcatenation } import core.{ Core, CoreActors } import routes.{ HTMLRoute, ModelRoutes } trait Api extends RouteConcatenation with Directives with LiveEnvironment with HTMLRoute with ModelRoutes with ZIODirectives { this: CoreActors with Core => private implicit val _ = actorSystem.dispatcher //TODO This particular example app doesn't use sessions, look up "com.softwaremill.akka-http-session" if you want sessions val sessionResult = Option("validsession") val routes: Route = DebuggingDirectives.logRequest("Request") { extractLog { log => unauthRoute ~ { extractRequestContext { requestContext => sessionResult match { case Some(session) => apiRoute(session) case None => log.info( s"Unauthorized request of ${requestContext.unmatchedPath}, redirecting to login" ) redirect("/loginForm", StatusCodes.Found) } } } ~ htmlRoute } } }
Example 23
Source File: HTMLRoute.scala From full-scala-stack with Apache License 2.0 | 5 votes |
package routes import akka.http.scaladsl.server.directives.ContentTypeResolver import akka.http.scaladsl.server.{ Directives, Route } import api.Config import util.ModelPickler trait HTMLRoute extends Directives with ModelPickler with Config { val staticContentDir: String = config.getString("full-scala-stack.staticContentDir") override def getFromDirectory( directoryName: String )(implicit resolver: ContentTypeResolver): Route = extractUnmatchedPath { unmatchedPath => getFromFile(s"$staticContentDir/$unmatchedPath") } def htmlRoute: Route = extractLog { log => pathEndOrSingleSlash { get { log.info("GET /") log.debug(s"GET $staticContentDir/index.html") getFromFile(s"$staticContentDir/index.html") } } ~ get { extractUnmatchedPath { path => log.debug(s"GET $path") encodeResponse { getFromDirectory(staticContentDir) } } } } }
Example 24
Source File: ModelRoutes.scala From full-scala-stack with Apache License 2.0 | 5 votes |
package routes import akka.http.scaladsl.server.{ Directives, Route } import api.LiveEnvironment import util.ModelPickler trait ModelRoutes extends Directives with ModelPickler { private val sampleModelObjectRouteRoute = new SampleModelObjectRoute with LiveEnvironment {} private val crudRoutes: List[CRUDRoute[_, _, _, Any]] = List( sampleModelObjectRouteRoute ) def unauthRoute: Route = crudRoutes.map(_.crudRoute.unauthRoute).reduceOption(_ ~ _).getOrElse(reject) //TODO: it would be nice to be able to do this, but it's hard to define the readers and writers for marshalling // def apiRoute(session: Any): Route = // pathPrefix("api") { // crudRoutes.map(_.crudRoute.route(session)).reduceOption(_ ~ _).getOrElse(reject) // } def apiRoute(session: Any): Route = pathPrefix("api") { sampleModelObjectRouteRoute.crudRoute.route(session) } }
Example 25
Source File: AkkaHttpServerTests.scala From tapir with Apache License 2.0 | 5 votes |
package sttp.tapir.server.akkahttp import cats.implicits._ import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.server.Route import akka.http.scaladsl.server.Directives import akka.http.scaladsl.server.Directives._ import cats.data.NonEmptyList import cats.effect.{IO, Resource} import sttp.client._ import com.typesafe.scalalogging.StrictLogging import sttp.tapir.{Endpoint, endpoint, stringBody} import sttp.tapir.server.tests.ServerTests import sttp.tapir._ import sttp.tapir.server.{DecodeFailureHandler, ServerDefaults, ServerEndpoint} import sttp.tapir.tests.{Port, PortCounter} import scala.concurrent.duration._ import scala.concurrent.{Await, Future} import scala.reflect.ClassTag class AkkaHttpServerTests extends ServerTests[Future, AkkaStream, Route] with StrictLogging { private implicit var actorSystem: ActorSystem = _ override protected def beforeAll(): Unit = { super.beforeAll() actorSystem = ActorSystem() } override protected def afterAll(): Unit = { Await.result(actorSystem.terminate(), 5.seconds) super.afterAll() } override def route[I, E, O]( e: ServerEndpoint[I, E, O, AkkaStream, Future], decodeFailureHandler: Option[DecodeFailureHandler] = None ): Route = { implicit val serverOptions: AkkaHttpServerOptions = AkkaHttpServerOptions.default.copy( decodeFailureHandler = decodeFailureHandler.getOrElse(ServerDefaults.decodeFailureHandler) ) e.toRoute } override def routeRecoverErrors[I, E <: Throwable, O](e: Endpoint[I, E, O, AkkaStream], fn: I => Future[O])(implicit eClassTag: ClassTag[E] ): Route = { e.toRouteRecoverErrors(fn) } override def server(routes: NonEmptyList[Route], port: Port): Resource[IO, Unit] = { val bind = IO.fromFuture(IO(Http().bindAndHandle(routes.toList.reduce(_ ~ _), "localhost", port))) Resource.make(bind)(binding => IO.fromFuture(IO(binding.unbind())).void).void } override def pureResult[T](t: T): Future[T] = Future.successful(t) override def suspendResult[T](t: => T): Future[T] = { import scala.concurrent.ExecutionContext.Implicits.global Future { t } } override lazy val portCounter: PortCounter = new PortCounter(57000) if (testNameFilter.isEmpty) { test("endpoint nested in a path directive") { val e = endpoint.get.in("test" and "directive").out(stringBody).serverLogic(_ => pureResult("ok".asRight[Unit])) val port = portCounter.next() val route = Directives.pathPrefix("api")(e.toRoute) server(NonEmptyList.of(route), port).use { _ => basicRequest.get(uri"http://localhost:$port/api/test/directive").send().map(_.body shouldBe Right("ok")) }.unsafeRunSync } } }
Example 26
Source File: RestPi.scala From apache-spark-test with Apache License 2.0 | 5 votes |
package com.github.dnvriend import akka.actor.ActorSystem import akka.event.{ Logging, LoggingAdapter } import akka.http.scaladsl._ import akka.http.scaladsl.common.{ EntityStreamingSupport, JsonEntityStreamingSupport } import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport import akka.http.scaladsl.server.{ Directives, Route } import akka.stream.scaladsl.{ Flow, Source } import akka.stream.{ ActorMaterializer, Materializer } import akka.util.ByteString import com.github.dnvriend.spark.CalculatePi import org.apache.spark.SparkContext import org.apache.spark.sql.SparkSession import spray.json.DefaultJsonProtocol import scala.concurrent.{ ExecutionContext, Future } object RestPi extends App with Directives with SprayJsonSupport with DefaultJsonProtocol { implicit val system: ActorSystem = ActorSystem() implicit val mat: Materializer = ActorMaterializer() implicit val ec: ExecutionContext = system.dispatcher implicit val log: LoggingAdapter = Logging(system, this.getClass) val spark = SparkSession.builder() .config("spark.sql.warehouse.dir", "file:/tmp/spark-warehouse") .config("spark.scheduler.mode", "FAIR") .config("spark.sql.crossJoin.enabled", "true") .master("local") // use as many threads as cores .appName("RestPi") // The appName parameter is a name for your application to show on the cluster UI. .getOrCreate() final case class Pi(pi: Double) implicit val piJsonFormat = jsonFormat1(Pi) val start = ByteString.empty val sep = ByteString("\n") val end = ByteString.empty implicit val jsonStreamingSupport: JsonEntityStreamingSupport = EntityStreamingSupport.json() .withFramingRenderer(Flow[ByteString].intersperse(start, sep, end)) .withParallelMarshalling(parallelism = 8, unordered = true) def sparkContext: SparkContext = spark.newSession().sparkContext def calculatePi(num: Long = 1000000, slices: Int = 2): Future[Double] = Future(CalculatePi(sparkContext, num, slices)).map(count => slices.toDouble * count / (num - 1)) val route: Route = pathEndOrSingleSlash { complete(calculatePi().map(Pi)) } ~ path("pi" / LongNumber / IntNumber) { (num, slices) => complete(calculatePi(num, slices).map(Pi)) } ~ path("stream" / "pi" / LongNumber) { num => complete(Source.fromFuture(calculatePi()).map(Pi) .flatMapConcat(Source.repeat).take(num)) } Http().bindAndHandle(route, "0.0.0.0", 8008) sys.addShutdownHook { spark.stop() system.terminate() } }
Example 27
Source File: ExampleModule.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.examples import akka.http.scaladsl.server.{Directives, Route} import cats.kernel.Monoid import ru.tinkoff.tschema.swagger.{MkSwagger, SwaggerBuilder} import Directives._ trait ExampleModule { def route: Route def swag: SwaggerBuilder } object ExampleModule { implicit val monoidInstance: Monoid[ExampleModule] = new Monoid[ExampleModule] { override def empty = new ExampleModule { override def route = reject() override def swag = SwaggerBuilder.empty } override def combine(x: ExampleModule, y: ExampleModule) = new ExampleModule { override def route = x.route ~ y.route override def swag = x.swag ++ y.swag } } }
Example 28
Source File: DebugParams.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema package examples import akka.http.scaladsl.server.Directives import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport._ import io.circe.Encoder import derevo.circe.{decoder, encoder} import derevo.derive import ru.tinkoff.tschema.akkaHttp.RoutableIn import ru.tinkoff.tschema.swagger.Swagger import shapeless._ import shapeless.labelled.FieldType @derive(encoder, decoder, Swagger) final case class DebugParams[T](value: T, params: Map[String, String]) object DebugParams { implicit def routable[In <: HList, T: Encoder](implicit im: InputParamMap[In]): RoutableIn[In, T, DebugParams[T]] = (in, res) => Directives.complete(DebugParams[T](res, im(in))) } trait InputParamMap[L <: HList] { def apply(l: L): Map[String, String] } trait LowLevelInputParamMap { implicit def simpleCons[L <: HList, A](implicit tail: InputParamMap[L]): InputParamMap[A :: L] = l => tail(l.tail) } object InputParamMap extends LowLevelInputParamMap { def apply[L <: HList](implicit im: InputParamMap[L]): InputParamMap[L] = im implicit val hnil: InputParamMap[HNil] = _ => Map.empty implicit def keyValueCons[L <: HList, K <: Symbol, V]( implicit witness: Witness.Aux[K], tail: InputParamMap[L] ): InputParamMap[FieldType[K, V] :: L] = l => tail(l.tail) + (witness.value.name -> l.head.toString) }
Example 29
Source File: WSApi.scala From mist with Apache License 2.0 | 5 votes |
package io.hydrosphere.mist.master.interfaces.http import akka.http.scaladsl.model.ws._ import akka.http.scaladsl.server.{Directives, Route} import akka.stream.ActorAttributes.supervisionStrategy import akka.stream.Supervision.resumingDecider import akka.stream.{ActorAttributes, Supervision} import akka.stream.scaladsl.{Flow, Sink} import io.hydrosphere.mist.master.EventsStreamer import io.hydrosphere.mist.master.Messages.StatusMessages._ import io.hydrosphere.mist.master.interfaces.JsonCodecs import scala.concurrent.duration._ import spray.json._ import scala.language.postfixOps class WSApi(streamer: EventsStreamer)(implicit val keepAliveTimeout: FiniteDuration) { import Directives._ import JsonCodecs._ val route: Route = { pathPrefix("v2" / "api"/ "ws" ) { parameter('withLogs ? false) { withLogs => path("all") { get { handleWebSocketMessagesWithKeepAlive(allEventsWsFlow(withLogs)) } } ~ path("jobs" / Segment) { jobId => get { handleWebSocketMessagesWithKeepAlive(jobWsFlow(jobId, withLogs)) } } }} } private def handleWebSocketMessagesWithKeepAlive(handler: Flow[Message, Message, akka.NotUsed]): Route = handleWebSocketMessages(handler .withAttributes(supervisionStrategy(resumingDecider)) .keepAlive( keepAliveTimeout, () => TextMessage.Strict(KeepAliveEvent.asInstanceOf[SystemEvent].toJson.toString()) )) private def jobWsFlow(id: String, withLogs: Boolean): Flow[Message, Message, akka.NotUsed] = { val source = streamer.eventsSource() .filter({ case e: UpdateStatusEvent => e.id == id case e: ReceivedLogs if withLogs => e.id == id case _ => false }) .map(toWsMessage) val sink = Sink.ignore Flow.fromSinkAndSource(sink, source) } private def allEventsWsFlow(withLogs: Boolean): Flow[Message, Message, akka.NotUsed] = { val source = streamer.eventsSource() .filter({ case _: ReceivedLogs => withLogs case _ => true }) .map(toWsMessage) val sink = Sink.ignore Flow.fromSinkAndSource(sink, source) } private def toWsMessage(e: SystemEvent): Message = TextMessage.Strict(e.toJson.toString()) }
Example 30
Source File: package.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema import akka.http.scaladsl.model.StatusCodes.BadRequest import akka.http.scaladsl.server.{Directives, Rejection, Route} package object akkaHttp { def rejectionHandler: PartialFunction[Rejection, Route] = { case NotFoundPathRejection(name) => Directives.complete(BadRequest, s"could not find path parameter $name") case MalformedPathRejection(name, formatError) => Directives.complete(BadRequest, s"could not parse path parameter $name : $formatError") } } package akkaHttp { final case class NotFoundPathRejection(name: String) extends Rejection final case class MalformedPathRejection(name: String, formatError: String) extends Rejection }
Example 31
Source File: ExampleApp.scala From akka-http-json with Apache License 2.0 | 5 votes |
package de.heikoseeberger.akkahttpupickle import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.model.HttpRequest import akka.http.scaladsl.server.Directives import akka.http.scaladsl.unmarshalling.Unmarshal import akka.stream.scaladsl.Source import scala.concurrent.Await import scala.concurrent.duration._ import scala.io.StdIn import upickle.default.{ ReadWriter, macroRW } object ExampleApp { final object Foo { implicit val rw: ReadWriter[Foo] = macroRW } final case class Foo(bar: String) def main(args: Array[String]): Unit = { implicit val system = ActorSystem() Http().bindAndHandle(route, "127.0.0.1", 8000) StdIn.readLine("Hit ENTER to exit") Await.ready(system.terminate(), Duration.Inf) } def route(implicit system: ActorSystem) = { import Directives._ import UpickleSupport._ pathSingleSlash { post { entity(as[Foo]) { foo => complete { foo } } } } ~ pathPrefix("stream") { post { entity(as[SourceOf[Foo]]) { fooSource: SourceOf[Foo] => complete(fooSource.throttle(1, 2.seconds)) } } ~ get { pathEndOrSingleSlash { complete( Source(0 to 5) .throttle(1, 1.seconds) .map(i => Foo(s"bar-$i")) ) } ~ pathPrefix("remote") { onSuccess(Http().singleRequest(HttpRequest(uri = "http://localhost:8000/stream"))) { response => complete(Unmarshal(response).to[SourceOf[Foo]]) } } } } } }
Example 32
Source File: ExampleApp.scala From akka-http-json with Apache License 2.0 | 5 votes |
package de.heikoseeberger.akkahttpargonaut import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.marshalling.Marshal import akka.http.scaladsl.model.{ HttpRequest, RequestEntity } import akka.http.scaladsl.server.Directives import akka.http.scaladsl.unmarshalling.Unmarshal import akka.stream.scaladsl.Source import argonaut.Argonaut.casecodec1 import argonaut.CodecJson import scala.concurrent.Await import scala.concurrent.duration._ import scala.io.StdIn object ExampleApp { final object Foo { implicit val fooCodec: CodecJson[Foo] = casecodec1(Foo.apply, Foo.unapply)("bar") } final case class Foo(bar: String) def main(args: Array[String]): Unit = { implicit val system = ActorSystem() Http().bindAndHandle(route, "127.0.0.1", 8000) StdIn.readLine("Hit ENTER to exit") Await.ready(system.terminate(), Duration.Inf) } def route(implicit sys: ActorSystem) = { import ArgonautSupport._ import Directives._ pathSingleSlash { post { entity(as[Foo]) { foo => complete { foo } } } } ~ pathPrefix("stream") { post { entity(as[SourceOf[Foo]]) { fooSource: SourceOf[Foo] => import sys._ Marshal(Source.single(Foo("a"))).to[RequestEntity] complete(fooSource.throttle(1, 2.seconds)) } } ~ get { pathEndOrSingleSlash { complete( Source(0 to 5) .throttle(1, 1.seconds) .map(i => Foo(s"bar-$i")) ) } ~ pathPrefix("remote") { onSuccess(Http().singleRequest(HttpRequest(uri = "http://localhost:8000/stream"))) { response => complete(Unmarshal(response).to[SourceOf[Foo]]) } } } } } }
Example 33
Source File: ExampleApp.scala From akka-http-json with Apache License 2.0 | 5 votes |
package de.heikoseeberger.akkahttpjsoniterscala import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.model.HttpRequest import akka.http.scaladsl.server.{ Directives, Route } import akka.http.scaladsl.unmarshalling.Unmarshal import akka.stream.scaladsl.Source import scala.concurrent.Await import scala.concurrent.duration._ import scala.io.StdIn object ExampleApp { final case class Foo(bar: String) def main(args: Array[String]): Unit = { implicit val system: ActorSystem = ActorSystem() Http().bindAndHandle(route, "127.0.0.1", 8000) StdIn.readLine("Hit ENTER to exit") Await.ready(system.terminate(), Duration.Inf) } def route(implicit sys: ActorSystem): Route = { import Directives._ import JsoniterScalaSupport._ import com.github.plokhotnyuk.jsoniter_scala.core._ import com.github.plokhotnyuk.jsoniter_scala.macros._ // here you should provide implicit codecs for in/out messages of all routes implicit val codec: JsonValueCodec[Foo] = JsonCodecMaker.make[Foo](CodecMakerConfig) // also, you can provide an implicit reader/writer configs to override defaults: // // implicit val readerConfig = ReaderConfig.withThrowReaderExceptionWithStackTrace(true) // implicit val writerConfig = WriterConfig.withIndentionStep(2) pathSingleSlash { post { entity(as[Foo]) { foo => complete { foo } } } } ~ pathPrefix("stream") { post { entity(as[SourceOf[Foo]]) { fooSource: SourceOf[Foo] => complete(fooSource.throttle(1, 2.seconds)) } } ~ get { pathEndOrSingleSlash { complete( Source(0 to 5) .throttle(1, 1.seconds) .map(i => Foo(s"bar-$i")) ) } ~ pathPrefix("remote") { onSuccess(Http().singleRequest(HttpRequest(uri = "http://localhost:8000/stream"))) { response => complete(Unmarshal(response).to[SourceOf[Foo]]) } } } } } }
Example 34
Source File: ExampleApp.scala From akka-http-json with Apache License 2.0 | 5 votes |
package de.heikoseeberger.akkahttpplayjson import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.model.HttpRequest import akka.http.scaladsl.server.Directives import akka.http.scaladsl.unmarshalling.Unmarshal import akka.stream.scaladsl.Source import play.api.libs.json.{ Format, JsValue, Json } import scala.concurrent.Await import scala.concurrent.duration._ import scala.io.StdIn object ExampleApp { final object Foo { implicit val fooFormat: Format[Foo] = Json.format[Foo] } final case class Foo(bar: String) def main(args: Array[String]): Unit = { implicit val system = ActorSystem() Http().bindAndHandle(route, "127.0.0.1", 8000) StdIn.readLine("Hit ENTER to exit") Await.ready(system.terminate(), Duration.Inf) } def route(implicit sys: ActorSystem) = { import Directives._ import PlayJsonSupport._ implicit val prettyPrint: JsValue => String = Json.prettyPrint pathSingleSlash { post { entity(as[Foo]) { foo => complete { foo } } } } ~ pathPrefix("stream") { post { entity(as[SourceOf[Foo]]) { fooSource: SourceOf[Foo] => complete(fooSource.throttle(1, 2.seconds)) } } ~ get { pathEndOrSingleSlash { complete( Source(0 to 5) .throttle(1, 1.seconds) .map(i => Foo(s"bar-$i")) ) } ~ pathPrefix("remote") { onSuccess(Http().singleRequest(HttpRequest(uri = "http://localhost:8000/stream"))) { response => complete(Unmarshal(response).to[SourceOf[Foo]]) } } } } } }
Example 35
Source File: ExampleApp.scala From akka-http-json with Apache License 2.0 | 5 votes |
package de.heikoseeberger.akkahttpavsystemgencodec import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.server.Directives import akka.stream.{ Materialzer, Materializer } import com.avsystem.commons.serialization.GenCodec import scala.concurrent.Await import scala.concurrent.duration.Duration import scala.io.StdIn object ExampleApp { final object Foo { implicit val codec: GenCodec[Foo] = GenCodec.materialize[Foo] } final case class Foo(bar: String) def main(args: Array[String]): Unit = { implicit val system = ActorSystem() implicit val mat = Materialzer() Http().bindAndHandle(route, "127.0.0.1", 8000) StdIn.readLine("Hit ENTER to exit") Await.ready(system.terminate(), Duration.Inf) } def route(implicit mat: Materializer) = { import Directives._ import GenCodecSupport._ pathSingleSlash { post { entity(as[Foo]) { foo => complete { foo } } } } } }
Example 36
Source File: ExampleApp.scala From akka-http-json with Apache License 2.0 | 5 votes |
package de.heikoseeberger.akkahttpjson4s import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.model.HttpRequest import akka.http.scaladsl.server.Directives import akka.http.scaladsl.unmarshalling.Unmarshal import akka.stream.scaladsl.Source import org.json4s.{ DefaultFormats, jackson } import scala.concurrent.Await import scala.concurrent.duration._ import scala.io.StdIn object ExampleApp { final case class Foo(bar: String) def main(args: Array[String]): Unit = { implicit val system = ActorSystem() Http().bindAndHandle(route, "127.0.0.1", 8000) StdIn.readLine("Hit ENTER to exit") Await.ready(system.terminate(), Duration.Inf) } def route(implicit sys: ActorSystem) = { import Directives._ import Json4sSupport._ implicit val serialization = jackson.Serialization // or native.Serialization implicit val formats = DefaultFormats pathSingleSlash { post { entity(as[Foo]) { foo => complete { foo } } } } ~ pathPrefix("stream") { post { entity(as[SourceOf[Foo]]) { fooSource: SourceOf[Foo] => complete(fooSource.throttle(1, 2.seconds)) } } ~ get { pathEndOrSingleSlash { complete( Source(0 to 5) .throttle(1, 1.seconds) .map(i => Foo(s"bar-$i")) ) } ~ pathPrefix("remote") { onSuccess(Http().singleRequest(HttpRequest(uri = "http://localhost:8000/stream"))) { response => complete(Unmarshal(response).to[SourceOf[Foo]]) } } } } } }
Example 37
Source File: ExampleApp.scala From akka-http-json with Apache License 2.0 | 5 votes |
package de.heikoseeberger.akkahttpavro4s import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.marshalling.Marshal import akka.http.scaladsl.model.{ HttpRequest, RequestEntity } import akka.http.scaladsl.server.Directives import akka.http.scaladsl.unmarshalling.Unmarshal import akka.stream.scaladsl.Source import com.sksamuel.avro4s.{ FromRecord, SchemaFor, ToRecord } import scala.concurrent.Await import scala.concurrent.duration._ import scala.io.StdIn object ExampleApp { final object Foo { implicit val schemaFor = SchemaFor[Foo] implicit val toRecord = ToRecord[Foo] implicit val fromRecord = FromRecord[Foo] } final case class Foo(bar: String) def main(args: Array[String]): Unit = { implicit val system = ActorSystem() Http().bindAndHandle(route, "127.0.0.1", 8000) StdIn.readLine("Hit ENTER to exit") Await.ready(system.terminate(), Duration.Inf) } def route(implicit sys: ActorSystem) = { import AvroSupport._ import Directives._ pathSingleSlash { post { entity(as[Foo]) { foo => complete { foo } } } } ~ pathPrefix("stream") { post { entity(as[SourceOf[Foo]]) { fooSource: SourceOf[Foo] => import sys._ Marshal(Source.single(Foo("a"))).to[RequestEntity] complete(fooSource.throttle(1, 2.seconds)) } } ~ get { pathEndOrSingleSlash { complete( Source(0 to 5) .throttle(1, 1.seconds) .map(i => Foo(s"bar-$i")) ) } ~ pathPrefix("remote") { onSuccess(Http().singleRequest(HttpRequest(uri = "http://localhost:8000/stream"))) { response => complete(Unmarshal(response).to[SourceOf[Foo]]) } } } } } }
Example 38
Source File: Entities.scala From openwhisk with Apache License 2.0 | 5 votes |
package org.apache.openwhisk.core.controller import scala.concurrent.Future import scala.language.postfixOps import scala.util.Try import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ import akka.http.scaladsl.model.StatusCodes.PayloadTooLarge import akka.http.scaladsl.model.headers.RawHeader import akka.http.scaladsl.server.Directive0 import akka.http.scaladsl.server.Directives import akka.http.scaladsl.server.RequestContext import akka.http.scaladsl.server.Route import akka.http.scaladsl.server.RouteResult import spray.json.JsonPrinter import org.apache.openwhisk.common.TransactionId import org.apache.openwhisk.core.entitlement.Privilege._ import org.apache.openwhisk.core.entitlement.Privilege import org.apache.openwhisk.core.entitlement.Privilege.READ import org.apache.openwhisk.core.entitlement.Resource import org.apache.openwhisk.core.entity._ import org.apache.openwhisk.core.entity.ActivationEntityLimit import org.apache.openwhisk.core.entity.size._ import org.apache.openwhisk.http.ErrorResponse.terminate import org.apache.openwhisk.http.Messages protected[controller] trait ValidateRequestSize extends Directives { protected def validateSize(check: => Option[SizeError])(implicit tid: TransactionId, jsonPrinter: JsonPrinter) = new Directive0 { override def tapply(f: Unit => Route) = { check map { case e: SizeError => terminate(PayloadTooLarge, Messages.entityTooBig(e)) } getOrElse f(None) } } protected final def isEntity(n: String) = Try { EntityName(n) } isSuccess }
Example 39
Source File: ChunkedEntities.scala From endpoints4s with MIT License | 5 votes |
package endpoints4s.akkahttp.server import akka.http.scaladsl.marshalling.Marshaller import akka.http.scaladsl.model.{ContentType, ContentTypes, HttpEntity, HttpRequest, MessageEntity} import akka.http.scaladsl.server.Directives import akka.http.scaladsl.unmarshalling.Unmarshaller import akka.stream.scaladsl.Source import akka.util.ByteString import endpoints4s.algebra import scala.concurrent.Future trait ChunkedJsonEntities extends algebra.ChunkedJsonEntities with ChunkedEntities with JsonEntitiesFromCodecs { def jsonChunksRequest[A](implicit codec: JsonCodec[A] ): RequestEntity[Chunks[A]] = { val decoder = stringCodec(codec) chunkedRequestEntity { byteString => val string = byteString.utf8String decoder .decode(string) .toEither .left .map(errors => new Throwable(errors.mkString(". "))) } } def jsonChunksResponse[A](implicit codec: JsonCodec[A] ): ResponseEntity[Chunks[A]] = { val encoder = stringCodec(codec) chunkedResponseEntity( ContentTypes.`application/json`, a => ByteString(encoder.encode(a)) ) } }
Example 40
Source File: BasicAuthentication.scala From endpoints4s with MIT License | 5 votes |
package endpoints4s.akkahttp.server import akka.http.scaladsl.model.headers.{ Authorization, BasicHttpCredentials, HttpChallenges, `WWW-Authenticate` } import akka.http.scaladsl.model.{HttpHeader, HttpResponse, StatusCodes => AkkaStatusCodes} import akka.http.scaladsl.server.{Directive, Directive1, Directives} import endpoints4s.{Tupler, algebra} import endpoints4s.algebra.BasicAuthentication.Credentials import endpoints4s.algebra.Documentation trait BasicAuthentication extends algebra.BasicAuthentication with EndpointsWithCustomErrors { private[endpoints4s] def authenticatedRequest[U, E, H, UE, HCred, Out]( method: Method, url: Url[U], entity: RequestEntity[E], headers: RequestHeaders[H], requestDocs: Documentation )(implicit tuplerUE: Tupler.Aux[U, E, UE], tuplerHCred: Tupler.Aux[H, Credentials, HCred], tuplerUEHCred: Tupler.Aux[UE, HCred, Out] ): Request[Out] = { val extractCredentials: HttpHeader => Option[Credentials] = { case Authorization(BasicHttpCredentials(username, password)) => Some(Credentials(username, password)) case _ => None } val authHeader: Directive1[Credentials] = Directives.optionalHeaderValue(extractCredentials).flatMap { case Some(credentials) => Directives.provide(credentials) case None => Directive[Tuple1[Credentials]] { _ => //inner is ignored Directives.complete( HttpResponse( AkkaStatusCodes.Unauthorized, collection.immutable.Seq[HttpHeader]( `WWW-Authenticate`(HttpChallenges.basic("Realm")) ) ) ) } } joinDirectives( joinDirectives( joinDirectives( convToDirective1(Directives.method(method)), url.directive ), entity ), headers ++ authHeader ) } }
Example 41
Source File: TryRoute.scala From akka-http-test with Apache License 2.0 | 5 votes |
package com.github.dnvriend.component.simpleserver.route import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport import akka.http.scaladsl.server.{ Directives, Route } import spray.json.DefaultJsonProtocol import scala.util.Try object TryRoute extends Directives with SprayJsonSupport with DefaultJsonProtocol { def route: Route = { pathPrefix("try") { (get & path("failure")) { complete(Try((1 / 0).toString)) } ~ (get & path("success")) { complete(Try(1.toString)) } } } }
Example 42
Source File: JsonStreamingRoute.scala From akka-http-test with Apache License 2.0 | 5 votes |
package com.github.dnvriend.component.simpleserver.route import akka.event.LoggingAdapter import akka.http.scaladsl.common.{ EntityStreamingSupport, JsonEntityStreamingSupport } import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport import akka.http.scaladsl.server.{ Directives, Route } import akka.stream.Materializer import akka.stream.scaladsl.Flow import akka.util.ByteString import com.github.dnvriend.component.repository.PersonRepository import com.github.dnvriend.component.simpleserver.dto.http.Person import com.github.dnvriend.component.simpleserver.marshaller.Marshallers import scala.concurrent.ExecutionContext object JsonStreamingRoute extends Directives with SprayJsonSupport with Marshallers { val start = ByteString.empty val sep = ByteString("\n") val end = ByteString.empty implicit val jsonStreamingSupport: JsonEntityStreamingSupport = EntityStreamingSupport.json() .withFramingRenderer(Flow[ByteString].intersperse(start, sep, end)) .withParallelMarshalling(parallelism = 8, unordered = true) def route(dao: PersonRepository)(implicit mat: Materializer, ec: ExecutionContext): Route = path("stream" / IntNumber) { numberOfPersons => (get & pathEnd) { complete(dao.people(numberOfPersons)) } } ~ (post & path("stream") & entity(asSourceOf[Person])) { people => val total = people.log("people").runFold(0) { case (c, _) => c + 1 } complete(total.map(n => s"Received $n number of person")) } }
Example 43
Source File: SimpleServerRestRoutes.scala From akka-http-test with Apache License 2.0 | 5 votes |
package com.github.dnvriend.component.simpleserver.route import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.server.{ Directives, Route } import akka.pattern.CircuitBreaker import akka.stream.Materializer import com.github.dnvriend.component.repository.PersonRepository import com.github.dnvriend.component.simpleserver.dto.http.{ Person, Ping } import com.github.dnvriend.component.simpleserver.marshaller.Marshallers import com.github.dnvriend.util.TimeUtil import scala.concurrent.ExecutionContext object SimpleServerRestRoutes extends Directives with Marshallers { def routes(dao: PersonRepository, cb: CircuitBreaker)(implicit mat: Materializer, ec: ExecutionContext): Route = logRequestResult("akka-http-test") { pathPrefix("person") { path("sync") { get { complete(dao.personSync) } } ~ path("async") { get { complete(cb.withCircuitBreaker(dao.personAsync)) } } ~ path("failed") { get { complete(cb.withCircuitBreaker(dao.personAsyncFailed)) } } ~ pathEnd { get { complete(cb.withSyncCircuitBreaker(dao.personSync)) } } ~ (post & entity(as[Person])) { person => complete(StatusCodes.Created) } } ~ pathPrefix("persons") { pathPrefix("strict" / IntNumber) { numberOfPersons => pathEnd { get { complete(cb.withSyncCircuitBreaker(dao.listOfPersons(numberOfPersons))) } } } ~ JsonStreamingRoute.route(dao) ~ CsvStreamingRoute.route(dao) } ~ (get & pathPrefix("ping")) { complete(Ping(TimeUtil.timestamp)) } ~ SimpleDisjunctionRoute.route ~ TryRoute.route } }
Example 44
Source File: SimpleDisjunctionRoute.scala From akka-http-test with Apache License 2.0 | 5 votes |
package com.github.dnvriend.component.simpleserver.route import akka.http.scaladsl.server.{ Directives, Route } import com.github.dnvriend.component.simpleserver.dto.http.OrderDto import com.github.dnvriend.component.simpleserver.marshaller.DisjunctionMarshaller.{ ErrorMessage, FatalError, NonFatalError } import com.github.dnvriend.component.simpleserver.marshaller.{ DisjunctionMarshaller, Marshallers, ValidationMarshaller } object SimpleDisjunctionRoute extends Directives with DisjunctionMarshaller with ValidationMarshaller with Marshallers { import scalaz._ import Scalaz._ final case class MyFatalError(description: String) extends FatalError final case class MyNonFatalError(description: String) extends NonFatalError def route: Route = pathPrefix("disjunction" / "simple") { (get & path("failure")) { complete("failure-left".left[String]) } ~ (get & path("success")) { complete("success-right".right[String]) } } ~ pathPrefix("disjunction" / "nel") { (get & path("string" / "failure")) { complete(("failure1".failureNel[String] *> "failure2".failureNel[String]).disjunction) } ~ (get & path("nonfatal" / "failure")) { complete((MyNonFatalError("my-non-fatal-error-1").failureNel[OrderDto] *> MyNonFatalError("my-non-fatal-error-2").failureNel[OrderDto]).disjunction) } ~ (get & path("fatal" / "failure")) { complete((MyFatalError("my-fatal-error-1").failureNel[OrderDto] *> MyFatalError("my-fatal-error-2").failureNel[OrderDto]).disjunction) } ~ (get & path("combined" / "failure")) { complete((Validation.failureNel[ErrorMessage, OrderDto](MyFatalError("my-fatal-error-1")) *> Validation.failureNel[ErrorMessage, OrderDto](MyNonFatalError("my-non-fatal-error-1"))).disjunction) } ~ (get & path("nonfatal" / "success")) { complete(OrderDto(1, "test-OrderDto").successNel[ErrorMessage].disjunction) } } ~ pathPrefix("validation") { (get & path("failure")) { complete("failure".failureNel[String]) } ~ (get & path("success")) { complete("success".successNel[String]) } } }
Example 45
Source File: CsvStreamingRoute.scala From akka-http-test with Apache License 2.0 | 5 votes |
package com.github.dnvriend.component.simpleserver.route import akka.http.scaladsl.common.{ CsvEntityStreamingSupport, EntityStreamingSupport } import akka.http.scaladsl.marshalling.{ Marshaller, Marshalling } import akka.http.scaladsl.model.ContentTypes import akka.http.scaladsl.server.{ Directives, Route } import akka.util.ByteString import com.github.dnvriend.component.repository.PersonRepository import com.github.dnvriend.component.simpleserver.dto.http.Person import de.heikoseeberger.akkahttpplayjson.PlayJsonSupport object CsvStreamingRoute extends Directives with PlayJsonSupport { implicit val personAsCsv = Marshaller.strict[Person, ByteString] { person => Marshalling.WithFixedContentType(ContentTypes.`text/csv(UTF-8)`, () => { ByteString(List(person.name.replace(",", "."), person.age, person.married).mkString(",")) }) } implicit val csvStreamingSupport: CsvEntityStreamingSupport = EntityStreamingSupport.csv() def route(dao: PersonRepository): Route = path("stream" / IntNumber) { numberOfPeople => pathEnd { get { complete(dao.people(numberOfPeople)) } } } }
Example 46
Source File: RestRoute.scala From akka-http-test with Apache License 2.0 | 5 votes |
package com.github.dnvriend.component.highlevelserver.route import akka.actor.ActorRef import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport import akka.http.scaladsl.marshalling.ToResponseMarshaller import akka.http.scaladsl.model.{ StatusCodes, Uri } import akka.http.scaladsl.server.{ Directives, Route } import akka.http.scaladsl.unmarshalling.FromRequestUnmarshaller import akka.pattern.ask import akka.util.Timeout import com.github.dnvriend.component.highlevelserver.dto.PersonWithId import com.github.dnvriend.component.highlevelserver.marshaller.Marshaller import com.github.dnvriend.component.simpleserver.dto.http.Person import scala.concurrent.Future // see: akka.http.scaladsl.marshalling.ToResponseMarshallable // see: akka.http.scaladsl.marshalling.PredefinedToResponseMarshallers object RestRoute extends Directives with SprayJsonSupport with Marshaller { def routes(personDb: ActorRef)(implicit timeout: Timeout, trmSingle: ToResponseMarshaller[PersonWithId], trmList: ToResponseMarshaller[List[PersonWithId]], fru: FromRequestUnmarshaller[Person]): Route = { pathEndOrSingleSlash { redirect(Uri("/api/person"), StatusCodes.PermanentRedirect) } ~ pathPrefix("api" / "person") { get { path(IntNumber) { id => println(s"PathEndsInNumber=$id") complete((personDb ? "findAll").mapTo[List[PersonWithId]]) } ~ pathEndOrSingleSlash { parameter("foo") { foo => println(s"foo=$foo") complete((personDb ? "findAll").mapTo[List[PersonWithId]]) } ~ parameter('bar) { bar => println(s"bar=$bar") complete((personDb ? "findAll").mapTo[List[PersonWithId]]) } ~ complete((personDb ? "findAll").mapTo[List[PersonWithId]]) } } ~ (post & pathEndOrSingleSlash & entity(as[Person])) { person => complete((personDb ? person).mapTo[PersonWithId]) } } ~ path("failure") { pathEnd { complete(Future.failed[String](new RuntimeException("Simulated Failure"))) } } ~ path("success") { pathEnd { complete(Future.successful("Success!!")) } } } }
Example 47
Source File: JsonEntities.scala From endpoints4s with MIT License | 5 votes |
package endpoints4s.akkahttp.server import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller} import akka.http.scaladsl.model.{HttpEntity, MediaTypes} import akka.http.scaladsl.server.{Directive1, Directives} import akka.http.scaladsl.unmarshalling.{ FromEntityUnmarshaller, FromRequestUnmarshaller, Unmarshaller } import endpoints4s.{Codec, Decoder, Encoder, Invalid, Valid, Validated, algebra} trait JsonEntitiesFromEncodersAndDecoders extends algebra.JsonEntities with EndpointsWithCustomErrors { type JsonRequest[A] = Decoder[String, A] type JsonResponse[A] = Encoder[A, String] def jsonRequest[A](implicit decoder: Decoder[String, A]): RequestEntity[A] = JsonEntities.decodeJsonRequest(this)(decoder) def jsonResponse[A](implicit encoder: Encoder[A, String]): ResponseEntity[A] = JsonEntities.encodeJsonResponse(encoder) } private object JsonEntities { def decodeJsonRequest[A]( endpoints: EndpointsWithCustomErrors )(decoder: Decoder[String, A]): Directive1[A] = { implicit val fromEntityUnmarshaller: FromEntityUnmarshaller[Validated[A]] = Unmarshaller.stringUnmarshaller .forContentTypes(MediaTypes.`application/json`) .map(data => decoder.decode(data)) Directives.entity[Validated[A]](implicitly).flatMap { case Valid(a) => Directives.provide(a) case inv: Invalid => endpoints.handleClientErrors(inv) } } def encodeJsonResponse[A]( encoder: Encoder[A, String] ): ToEntityMarshaller[A] = Marshaller.withFixedContentType(MediaTypes.`application/json`) { value => HttpEntity(MediaTypes.`application/json`, encoder.encode(value)) } }
Example 48
Source File: Limits.scala From openwhisk with Apache License 2.0 | 5 votes |
package org.apache.openwhisk.core.controller import akka.http.scaladsl.model.StatusCodes._ import akka.http.scaladsl.server.{Directive1, Directives} import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport.sprayJsonMarshaller import org.apache.openwhisk.common.TransactionId import org.apache.openwhisk.core.WhiskConfig import org.apache.openwhisk.core.entitlement.{Collection, Privilege, Resource} import org.apache.openwhisk.core.entitlement.Privilege.READ import org.apache.openwhisk.core.entity.Identity trait WhiskLimitsApi extends Directives with AuthenticatedRouteProvider with AuthorizedRouteProvider { protected val whiskConfig: WhiskConfig protected override val collection = Collection(Collection.LIMITS) protected val invocationsPerMinuteSystemDefault = whiskConfig.actionInvokePerMinuteLimit.toInt protected val concurrentInvocationsSystemDefault = whiskConfig.actionInvokeConcurrentLimit.toInt protected val firePerMinuteSystemDefault = whiskConfig.triggerFirePerMinuteLimit.toInt override protected lazy val entityOps = get protected override def dispatchOp(user: Identity, op: Privilege, resource: Resource)( implicit transid: TransactionId) = { resource.entity match { case Some(_) => //TODO: Process entity level requests for an individual limit here reject //should never get here case None => op match { case READ => val limits = user.limits.copy( Some(user.limits.invocationsPerMinute.getOrElse(invocationsPerMinuteSystemDefault)), Some(user.limits.concurrentInvocations.getOrElse(concurrentInvocationsSystemDefault)), Some(user.limits.firesPerMinute.getOrElse(firePerMinuteSystemDefault))) pathEndOrSingleSlash { complete(OK, limits) } case _ => reject //should never get here } } } protected override def entityname(n: String): Directive1[String] = { validate(false, "Inner entity level routes for limits are not yet implemented.") & extract(_ => n) } }
Example 49
Source File: KafkaMetrics.scala From openwhisk with Apache License 2.0 | 5 votes |
package org.apache.openwhisk.connector.kafka import akka.http.scaladsl.server.{Directives, Route} import org.apache.kafka.common.{Metric, MetricName => JMetricName} import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ import spray.json._ import spray.json.DefaultJsonProtocol._ import scala.collection.JavaConverters._ import scala.concurrent.{ExecutionContext, Future} import scala.util.{Success, Try} trait KafkaMetricsProvider { def metrics(): Future[Map[JMetricName, Metric]] } object KafkaMetricRoute extends Directives { def apply(provider: KafkaMetricsProvider)(implicit ec: ExecutionContext): Route = { path("metrics" / "kafka") { val metrics = provider.metrics().map(m => KafkaMetrics.toJson(m)) complete(metrics) } } }
Example 50
Source File: DarwinService.scala From darwin with Apache License 2.0 | 5 votes |
package it.agilelab.darwin.server.rest import akka.actor.ActorSystem import akka.http.scaladsl.model.{HttpResponse, StatusCodes} import akka.http.scaladsl.server.directives.DebuggingDirectives import akka.http.scaladsl.server.{Directives, Route} import akka.stream.ActorMaterializer import akka.stream.Attributes.LogLevels import it.agilelab.darwin.manager.AvroSchemaManager import org.apache.avro.Schema trait DarwinService extends Service with Directives with DebuggingDirectives with JsonSupport { val manager: AvroSchemaManager override def route: Route = logRequestResult(("darwin", LogLevels.Debug)) { get { path("schemas" / LongNumber.?) { case Some(id) => manager.getSchema(id) match { case Some(schema) => complete(schema) case None => complete { HttpResponse(StatusCodes.NotFound) } } case None => complete(manager.getAll) } } ~ post { path("schemas" / PathEnd) { entity(as[Seq[Schema]]) { schemas => complete { manager.registerAll(schemas).map(_._1) } } } } } } object DarwinService { def apply(asm: AvroSchemaManager)(implicit s: ActorSystem, m: ActorMaterializer): DarwinService = new DarwinService { override implicit val materializer: ActorMaterializer = m override implicit val system: ActorSystem = s override val manager: AvroSchemaManager = asm } }
Example 51
Source File: DemoApp.scala From constructr-consul with Apache License 2.0 | 5 votes |
package com.tecsisa.constructr.coordination package demo import akka.actor.{ ActorRef, ActorSystem, Address } import akka.http.scaladsl.Http import akka.http.scaladsl.server.Directives import akka.pattern.ask import akka.stream.ActorMaterializer import akka.util.Timeout import com.typesafe.config.ConfigFactory import scala.concurrent.duration.{ Duration, MILLISECONDS } object DemoApp { val conf = ConfigFactory.load() val hostname = conf.getString("demo.hostname") val httpPort = conf.getInt("demo.port") def main(args: Array[String]): Unit = { // Create an Akka system implicit val system = ActorSystem("ConstructR-Consul") import system.dispatcher implicit val mat = ActorMaterializer() // Create an actor that handles cluster domain events val cluster = system.actorOf(SimpleClusterListener.props, SimpleClusterListener.Name) Http().bindAndHandle(route(cluster), hostname, httpPort) } private def route(cluster: ActorRef) = { import Directives._ implicit val timeout = Timeout( Duration( conf.getDuration("demo.cluster-view-timeout").toMillis, MILLISECONDS ) ) path("member-nodes") { // List cluster nodes get { onSuccess( (cluster ? SimpleClusterListener.GetMemberNodes).mapTo[Set[Address]] )(addresses => complete(addresses.mkString("\n"))) } } } }
Example 52
Source File: ApiError.scala From EncryCore with GNU General Public License v3.0 | 5 votes |
package encry.api.http import akka.http.scaladsl.model.{StatusCode, StatusCodes} import akka.http.scaladsl.server.{Directives, Route} import scala.language.implicitConversions case class ApiError(statusCode: StatusCode, reason: String = "") { def apply(detail: String): Route = complete(detail) def defaultRoute: Route = complete() def complete(detail: String = ""): Route = { val nonEmptyReason = if (reason.isEmpty) statusCode.reason else reason val body = if (detail.isEmpty) nonEmptyReason else s"$nonEmptyReason $detail" Directives.complete(statusCode.intValue() -> body) } } object ApiError { def apply(s: String): Route = InternalError(s) def apply(e: Throwable): Route = InternalError(e.getMessage) def apply(causes: Seq[Throwable]): Route = InternalError(mkString(causes)) def mkString(causes: Seq[Throwable]): String = causes.map(_.getMessage).mkString(", ") implicit def toRoute(error: ApiError): Route = error.defaultRoute object InternalError extends ApiError(StatusCodes.InternalServerError, "internal.error") object InvalidJson extends ApiError(StatusCodes.BadRequest, "invalid.json") object BadRequest extends ApiError(StatusCodes.BadRequest, "bad.request") object ApiKeyNotValid extends ApiError(StatusCodes.Forbidden, "invalid.api-key") object NotExists extends ApiError(StatusCodes.NotFound, "not-found") }
Example 53
Source File: App.scala From avoin-voitto with MIT License | 5 votes |
package liigavoitto import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.server.Directives import akka.stream.ActorMaterializer import liigavoitto.api.{ ApiRoutes, BaseRoutes } import liigavoitto.util.Logging import scala.util.Properties object App extends Directives with ApiRoutes with Logging { implicit lazy val system = ActorSystem("liiga-voitto") lazy val port = Properties.envOrElse("APP_PORT", "45258").toInt def main(args: Array[String]) { implicit val executionContext = system.dispatcher implicit val fm = ActorMaterializer() Http().bindAndHandle(routes, "0.0.0.0", port) log.info(s"Server online at http://0.0.0.0:$port/") } val routes = BaseRoutes.baseRoutes ~ apiRoutes ~ localRoute }
Example 54
Source File: TracingDirectiveSpec.scala From opencensus-scala with Apache License 2.0 | 5 votes |
package io.opencensus.scala.akka.http import akka.http.scaladsl.server.Directives import io.opencensus.scala.http.ServiceData class TracingDirectiveSpec extends ServiceRequirementsSpec { "traceRequest" should behave like tracedService( routeFromTracingDirectiveAndResult = directive => completeWith => directive.traceRequest(_ => completeWith()), serviceData = None ) it should "pass the span to the inner route" in { val path = "/my/fancy/path" val (directive, _) = directiveWithMock() Get(path) ~> directive.traceRequest(span => Directives.complete(span.getContext.toString) ) ~> check { entityAs[String] should include("SpanContext") } } "traceRequestNoSpan" should behave like tracedService( routeFromTracingDirectiveAndResult = directive => completeWith => directive.traceRequestNoSpan(completeWith()), serviceData = None ) val data = ServiceData("Name", "X.X.Y") "traceRequestForService" should behave like tracedService( routeFromTracingDirectiveAndResult = directive => completeWith => directive.traceRequestForService(data)(_ => completeWith()), serviceData = Some(data) ) "traceRequestForServiceNoSpan" should behave like tracedService( routeFromTracingDirectiveAndResult = directive => completeWith => directive.traceRequestForServiceNoSpan(data)(completeWith()), serviceData = Some(data) ) }
Example 55
Source File: StaticContentEndpoints.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.http import akka.http.scaladsl.model._ import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.directives.ContentTypeResolver.Default import akka.http.scaladsl.server.{Directives, RoutingLog} import akka.http.scaladsl.settings.{ParserSettings, RoutingSettings} import akka.stream.Materializer import com.typesafe.scalalogging.StrictLogging import scalaz.syntax.show._ import scala.concurrent.Future object StaticContentEndpoints { def all(config: StaticContentConfig)( implicit routingSettings: RoutingSettings, parserSettings: ParserSettings, materializer: Materializer, routingLog: RoutingLog): HttpRequest PartialFunction Future[HttpResponse] = new StaticContentRouter(config) } private class StaticContentRouter(config: StaticContentConfig)( implicit routingSettings: RoutingSettings, parserSettings: ParserSettings, materializer: Materializer, routingLog: RoutingLog) extends PartialFunction[HttpRequest, Future[HttpResponse]] with StrictLogging { private val pathPrefix: Uri.Path = Uri.Path("/" + config.prefix) logger.warn(s"StaticContentRouter configured: ${config.shows}") logger.warn("DO NOT USE StaticContentRouter IN PRODUCTION, CONSIDER SETTING UP REVERSE PROXY!!!") private val fn = akka.http.scaladsl.server.Route.asyncHandler( Directives.rawPathPrefix(Slash ~ config.prefix)( Directives.getFromDirectory(config.directory.getAbsolutePath) )) override def isDefinedAt(x: HttpRequest): Boolean = x.uri.path.startsWith(pathPrefix) override def apply(x: HttpRequest): Future[HttpResponse] = fn(x) }
Example 56
Source File: WebService.scala From akka-http-scalajs.g8 with Apache License 2.0 | 5 votes |
package $package$ import akka.http.scaladsl.server.Directives import $package$.shared.SharedMessages import $package$.twirl.Implicits._ class WebService() extends Directives { val route = { pathSingleSlash { get { complete { $package$.html.index.render(SharedMessages.itWorks) } } } ~ pathPrefix("assets" / Remaining) { file => // optionally compresses the response with Gzip or Deflate // if the client accepts compressed responses encodeResponse { getFromResource("public/" + file) } } } }
Example 57
Source File: PermissionControllers.scala From akka-http-extensions with Mozilla Public License 2.0 | 5 votes |
package akka.http.extensions import akka.http.extensions.security._ import akka.http.scaladsl.server.{Directives, Route} import scala.collection.mutable case object SpecialRealm extends Realm case object VIPRealm extends Realm trait PermissionControllers extends RegistrationControllers { class Permissions(sessionController: TestSessionController,loginController: TestLoginController) extends AuthDirectives with Directives { case object OtherRealm extends Realm var drugs:Set[String] = Set.empty val permissions = new mutable.HashMap[Realm, mutable.Set[LoginInfo]] with mutable.MultiMap[Realm, LoginInfo] def checkRights(user:LoginInfo,realm:Realm):Boolean = if(realm==UserRealm) loginController.exists(user) else permissions.get(realm).exists(_.contains(user)) def add2realm(user:LoginInfo,realm: Realm) ={ permissions.addBinding(realm,user) } def removeFromRealm(user:LoginInfo,realm: Realm) ={ permissions.removeBinding(realm,user) } lazy val realms: Map[String, Realm] = Map("user"->UserRealm,"vip"->VIPRealm,"special"->SpecialRealm,""->UserRealm) def routes: Route = pathPrefix("add") { pathPrefix("drug") { put { parameter("name","kind"){ (name,kind)=> authenticate(sessionController.userByToken _){ user=> val realm: Realm = realms.getOrElse(kind, realms("user")) allow(user,realm, checkRights _) { drugs = drugs + name complete(s"drug $name added!") } } } } } } } }
Example 58
Source File: Registration.scala From akka-http-extensions with Mozilla Public License 2.0 | 5 votes |
package akka.http.extensions.stubs import akka.http.extensions.security._ import akka.http.scaladsl.server.{Directives, _} import scala.concurrent.Future class Registration( usernameLogin:(String,String)=>Future[LoginResult], emailLogin:(String,String)=>Future[LoginResult], register:(String,String,String)=>Future[RegistrationResult], userByToken:String=>Option[LoginInfo], makeToken:LoginInfo=>Future[String] ) extends AuthDirectives with Directives with WithLoginRejections with WithRegistrationRejections { def routes: Route = pathPrefix("users") { pathPrefix("login") { put { handleRejections(loginRejectionHandlers) { login(usernameLogin, emailLogin) { user => startSession(user, makeToken) { complete(s"The user ${user.username} was logged in") } } } } } ~ pathPrefix("register") { put { handleRejections(registerRejectionHandlers) { registration(register) { user => startSession(user, makeToken) { complete(s"The user ${user.username} has been registered") } } } } } ~ pathPrefix("logout") { logout{ c => c.complete(s"The user was logged out") } } ~ pathPrefix("status"){ this.authenticate(userByToken){user=> complete(user.username) } } } }
Example 59
Source File: Webservice.scala From akka-viz with MIT License | 5 votes |
package akkaviz.server import akka.actor.{ActorRef, ActorSystem, Kill, PoisonPill} import akka.http.scaladsl.coding.Gzip import akka.http.scaladsl.model._ import akka.http.scaladsl.model.ws.{BinaryMessage, Message} import akka.http.scaladsl.server.Directives import akka.stream.scaladsl._ import akka.stream.{Materializer, OverflowStrategy} import akkaviz.config.Config import akkaviz.events._ import akkaviz.events.types._ import akkaviz.persistence.{PersistenceSources, ReceivedRecord} import akkaviz.protocol import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration._ class Webservice(implicit materializer: Materializer, system: ActorSystem) extends Directives with SubscriptionSession with ReplSupport with AkkaHttpHelpers with ArchiveSupport with FrontendResourcesSupport with ProtocolSerializationSupport with BackendEventsMarshalling { def route: Flow[HttpRequest, HttpResponse, Any] = encodeResponseWith(Gzip) { get { path("stream") { handleWebSocketMessages(tracingEventsFlow.mapMaterializedValue(EventSystem.subscribe)) } } ~ archiveRouting ~ replRouting ~ frontendResourcesRouting } def tracingEventsFlow: Flow[Message, Message, ActorRef] = { val eventSrc = Source.actorRef[BackendEvent](Config.bufferSize, OverflowStrategy.dropNew) val wsIn = Flow[Message] .via(websocketMessageToClientMessage) .via(handleUserCommand) .scan(defaultSettings)(updateSettings) .expand(r => Iterator.continually(r)) val out = wsIn.zipMat(eventSrc)((_, m) => m) .collect { case (settings, r: BackendEvent) if settings.eventAllowed(r) => r }.via(backendEventToProtocolFlow) .keepAlive(10.seconds, () => protocol.Ping) .via(protocolServerMessageToByteString) .map(BinaryMessage.Strict(_)) out } private[this] val handleUserCommand: Flow[protocol.ApiClientMessage, ChangeSubscriptionSettings, _] = Flow[protocol.ApiClientMessage].mapConcat { case protocol.SetAllowedMessages(classNames) => system.log.debug(s"Set allowed messages to $classNames") List(SetAllowedClasses(classNames)) case protocol.ObserveActors(actors) => system.log.debug(s"Set observed actors to $actors") List(SetActorEventFilter(actors)) case protocol.SetReceiveDelay(duration) => system.log.debug(s"Setting receive delay to $duration") EventSystem.setReceiveDelay(duration) Nil case protocol.SetEnabled(isEnabled) => system.log.info(s"Setting EventSystem.setEnabled($isEnabled)") EventSystem.setEnabled(isEnabled) Nil case protocol.RefreshInternalState(actor) => ActorSystems.refreshActorState(actor) Nil case protocol.PoisonPillActor(actor) => ActorSystems.tell(actor, PoisonPill) Nil case protocol.KillActor(actor) => ActorSystems.tell(actor, Kill) Nil } override def receivedOf(ref: String): Source[ReceivedRecord, _] = PersistenceSources.of(ref) override def receivedBetween(ref: String, ref2: String): Source[ReceivedRecord, _] = PersistenceSources.between(ref, ref2) override def isArchiveEnabled: Boolean = Config.enableArchive }
Example 60
Source File: AkkaHttpHelpers.scala From akka-viz with MIT License | 5 votes |
package akkaviz.server import akka.http.scaladsl.marshalling.{Marshal, Marshaller} import akka.http.scaladsl.model.HttpEntity.ChunkStreamPart import akka.http.scaladsl.model.{HttpEntity, HttpResponse, MediaTypes} import akka.http.scaladsl.server.{Directives, StandardRoute} import akka.stream.scaladsl.{Flow, Source} import scala.concurrent.ExecutionContext trait AkkaHttpHelpers { def asJsonArray[T](implicit m: Marshaller[T, String], ec: ExecutionContext): Flow[T, HttpEntity.ChunkStreamPart, _] = { Flow.apply[T] .mapAsync[String](4)(t => Marshal(t).to[String]) .scan[Option[ChunkStreamPart]](None) { case (None, s: String) => Some(ChunkStreamPart(s)) case (_, s: String) => Some(ChunkStreamPart(s",${s}")) }.mapConcat(_.toList) .prepend(Source.single(ChunkStreamPart("["))) .concat(Source.single(ChunkStreamPart("]"))) } def completeAsJson[T](source: Source[T, _])(implicit m: Marshaller[T, String], ec: ExecutionContext): StandardRoute = { Directives.complete(HttpResponse( entity = HttpEntity.Chunked(MediaTypes.`application/json`, source.via(asJsonArray)) )) } } object AkkaHttpHelpers extends AkkaHttpHelpers
Example 61
Source File: HealthCheckRouting.scala From vinyldns with Apache License 2.0 | 5 votes |
package vinyldns.api.route import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.server.{Directives, Route} import akka.util.Timeout import vinyldns.core.health.HealthService import scala.concurrent.duration._ trait PingRoute extends Directives { val pingRoute: Route = (get & path("ping")) { complete("PONG") } } trait HealthCheckRoute extends Directives { val healthService: HealthService implicit val healthCheckTimeout = Timeout(5.seconds) // perform a query against, fail with an ok if we can get zones from the zone manager val healthCheckRoute = (get & path("health")) { onSuccess(healthService.checkHealth().unsafeToFuture()) { case head :: _ => failWith(head) case _ => complete(StatusCodes.OK) } } }
Example 62
Source File: StatusRouting.scala From vinyldns with Apache License 2.0 | 5 votes |
package vinyldns.api.route import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.server.Directives import akka.util.Timeout import cats.effect.IO import fs2.concurrent.SignallingRef import vinyldns.api.VinylDNSConfig import scala.concurrent.duration._ case class CurrentStatus( processingDisabled: Boolean, color: String, keyName: String, version: String ) object CurrentStatus { val color = VinylDNSConfig.vinyldnsConfig.getString("color") val vinyldnsKeyName = VinylDNSConfig.configuredDnsConnections.defaultZoneConnection.keyName val version = VinylDNSConfig.vinyldnsConfig.getString("version") } trait StatusRoute extends Directives { this: VinylDNSJsonProtocol => import CurrentStatus._ implicit val timeout = Timeout(10.seconds) def processingDisabled: SignallingRef[IO, Boolean] val statusRoute = (get & path("status")) { onSuccess(processingDisabled.get.unsafeToFuture()) { isProcessingDisabled => complete( StatusCodes.OK, CurrentStatus(isProcessingDisabled, color, vinyldnsKeyName, version) ) } } ~ (post & path("status")) { parameters("processingDisabled".as[Boolean]) { isProcessingDisabled => onSuccess(processingDisabled.set(isProcessingDisabled).unsafeToFuture()) { complete( StatusCodes.OK, CurrentStatus(isProcessingDisabled, color, vinyldnsKeyName, version) ) } } } }
Example 63
Source File: PrometheusRouting.scala From vinyldns with Apache License 2.0 | 5 votes |
package vinyldns.api.route import java.io.StringWriter import akka.http.scaladsl.model._ import akka.http.scaladsl.server.Directives import io.prometheus.client.CollectorRegistry import io.prometheus.client.exporter.common.TextFormat import scala.collection.JavaConverters._ trait PrometheusRoute extends Directives { def collectorRegistry: CollectorRegistry private val `text/plain; version=0.0.4; charset=utf-8` = ContentType { MediaType.customWithFixedCharset( "text", "plain", HttpCharsets.`UTF-8`, params = Map("version" -> "0.0.4") ) } def renderMetrics(registry: CollectorRegistry, names: Set[String]): String = { val writer = new StringWriter() TextFormat.write004(writer, registry.filteredMetricFamilySamples(names.toSet.asJava)) writer.toString } val prometheusRoute = (get & path("metrics" / "prometheus") & parameter('name.*)) { names => val content = renderMetrics(collectorRegistry, names.toSet) complete { HttpResponse(entity = HttpEntity(`text/plain; version=0.0.4; charset=utf-8`, content)) } } }
Example 64
Source File: ClusterHttpInspector.scala From simple-akka-downing with Apache License 2.0 | 5 votes |
package com.ajjpj.simpleakkadowning.util import akka.actor.Actor import akka.cluster.{Cluster, MemberStatus} import akka.http.scaladsl.Http import akka.http.scaladsl.server.Directives import akka.stream.ActorMaterializer import scala.concurrent.Await class ClusterHttpInspector(httpPort: Int) extends Actor { val cluster = Cluster.get(context.system) val routes = { import Directives._ pathPrefix("cluster-members") { path("up") { complete { cluster.state.members.filter(_.status == MemberStatus.Up).map(_.address.port.get).mkString(" ") }} ~ path("unreachable") { complete { cluster.state.unreachable.map(_.address.port.get).mkString(" ") }} } } import context.dispatcher implicit val mat = ActorMaterializer() val fServerBinding = Http(context.system) .bindAndHandle(routes, "localhost", httpPort) override def postStop () = { import scala.concurrent.duration._ super.postStop () fServerBinding.foreach(sb => Await.ready (sb.unbind(), 5.seconds)) } override def receive = Actor.emptyBehavior }
Example 65
Source File: Router.scala From akka-http-extensions with Mozilla Public License 2.0 | 5 votes |
package org.denigma.preview.routes import akka.http.extensions.security.LoginInfo import akka.http.extensions.stubs._ import akka.http.scaladsl.server.Directives class Router extends Directives { val sessionController:SessionController = new InMemorySessionController val loginController: InMemoryLoginController = new InMemoryLoginController() loginController.addUser(LoginInfo("admin","test2test","test@email")) def routes = new Head().routes ~ new Registration( loginController.loginByName, loginController.loginByEmail, loginController.register, sessionController.userByToken, sessionController.makeToken ) .routes ~ new Pages().routes }
Example 66
Source File: OAuth2RouteProvider.scala From slick-akka-http-oauth2 with Apache License 2.0 | 5 votes |
package rest import akka.http.scaladsl.model.StatusCodes._ import akka.http.scaladsl.server.Directives import akka.http.scaladsl.server.directives.Credentials import rest.OAuth2RouteProvider.TokenResponse import spray.json.DefaultJsonProtocol import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future import scala.util.{Failure, Success} import scalaoauth2.provider._ trait OAuth2RouteProvider[U] extends Directives with DefaultJsonProtocol{ import OAuth2RouteProvider.tokenResponseFormat import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ val oauth2DataHandler : DataHandler[U] val tokenEndpoint = new TokenEndpoint { override val handlers = Map( OAuthGrantType.CLIENT_CREDENTIALS -> new ClientCredentials, OAuthGrantType.PASSWORD -> new Password, OAuthGrantType.AUTHORIZATION_CODE -> new AuthorizationCode, OAuthGrantType.REFRESH_TOKEN -> new RefreshToken ) } def grantResultToTokenResponse(grantResult : GrantHandlerResult[U]) : TokenResponse = TokenResponse(grantResult.tokenType, grantResult.accessToken, grantResult.expiresIn.getOrElse(1L), grantResult.refreshToken.getOrElse("")) def oauth2Authenticator(credentials: Credentials): Future[Option[AuthInfo[U]]] = credentials match { case [email protected](token) => oauth2DataHandler.findAccessToken(token).flatMap { case Some(token) => oauth2DataHandler.findAuthInfoByAccessToken(token) case None => Future.successful(None) } case _ => Future.successful(None) } def accessTokenRoute = pathPrefix("oauth") { path("access_token") { post { formFieldMap { fields => onComplete(tokenEndpoint.handleRequest(new AuthorizationRequest(Map(), fields.map(m => m._1 -> Seq(m._2))), oauth2DataHandler)) { case Success(maybeGrantResponse) => maybeGrantResponse.fold(oauthError => complete(Unauthorized), grantResult => complete(tokenResponseFormat.write(grantResultToTokenResponse(grantResult))) ) case Failure(ex) => complete(InternalServerError, s"An error occurred: ${ex.getMessage}") } } } } } } object OAuth2RouteProvider extends DefaultJsonProtocol{ case class TokenResponse(token_type : String, access_token : String, expires_in : Long, refresh_token : String) implicit val tokenResponseFormat = jsonFormat4(TokenResponse) }
Example 67
Source File: MyResource.scala From quiz-management-service with Apache License 2.0 | 5 votes |
package com.danielasfregola.quiz.management.routing import akka.http.scaladsl.marshalling.{ToResponseMarshaller, ToResponseMarshallable} import scala.concurrent.{ExecutionContext, Future} import akka.http.scaladsl.model.headers.Location import akka.http.scaladsl.server.{Directives, Route} import com.danielasfregola.quiz.management.serializers.JsonSupport trait MyResource extends Directives with JsonSupport { implicit def executionContext: ExecutionContext def completeWithLocationHeader[T](resourceId: Future[Option[T]], ifDefinedStatus: Int, ifEmptyStatus: Int): Route = onSuccess(resourceId) { case Some(t) => completeWithLocationHeader(ifDefinedStatus, t) case None => complete(ifEmptyStatus, None) } def completeWithLocationHeader[T](status: Int, resourceId: T): Route = extractRequestContext { requestContext => val request = requestContext.request val location = request.uri.copy(path = request.uri.path / resourceId.toString) respondWithHeader(Location(location)) { complete(status, None) } } def complete[T: ToResponseMarshaller](resource: Future[Option[T]]): Route = onSuccess(resource) { case Some(t) => complete(ToResponseMarshallable(t)) case None => complete(404, None) } def complete(resource: Future[Unit]): Route = onSuccess(resource) { complete(204, None) } }
Example 68
Source File: LeagueService.scala From eventsourcing-intro with Apache License 2.0 | 5 votes |
package eu.reactivesystems.league.api import akka.Done import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport import akka.http.scaladsl.server.Directives import scala.concurrent.Future trait LeagueService extends Directives with SprayJsonSupport { val routes = pathPrefix("league") { path(Segment / "club") { leagueId => post { entity(as[Club]) { club => complete(addClub(leagueId, club)) } } } ~ path(Segment / "game") { leagueId => post { entity(as[Game]) { game => complete(addGame(leagueId, game)) } } ~ put { entity(as[Game]) { game => complete(changeGame(leagueId, game)) } } } } def addClub(leagueId: String, club: Club): Future[Done] def addGame(leagueId: String, game: Game): Future[Done] def changeGame(leagueId: String, game: Game): Future[Done] }
Example 69
Source File: ExtraDirectives.scala From eclair with Apache License 2.0 | 5 votes |
package fr.acinq.eclair.api import akka.http.scaladsl.marshalling.ToResponseMarshaller import akka.http.scaladsl.model.StatusCodes.NotFound import akka.http.scaladsl.model.{ContentTypes, HttpResponse} import akka.http.scaladsl.server.{Directive1, Directives, MalformedFormFieldRejection, Route} import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.Crypto.PublicKey import fr.acinq.eclair.ApiTypes.ChannelIdentifier import fr.acinq.eclair.api.FormParamExtractors._ import fr.acinq.eclair.api.JsonSupport._ import fr.acinq.eclair.payment.PaymentRequest import fr.acinq.eclair.{MilliSatoshi, ShortChannelId} import scala.concurrent.Future import scala.util.{Failure, Success} trait ExtraDirectives extends Directives { // named and typed URL parameters used across several routes val shortChannelIdFormParam = "shortChannelId".as[ShortChannelId](shortChannelIdUnmarshaller) val shortChannelIdsFormParam = "shortChannelIds".as[List[ShortChannelId]](shortChannelIdsUnmarshaller) val channelIdFormParam = "channelId".as[ByteVector32](sha256HashUnmarshaller) val channelIdsFormParam = "channelIds".as[List[ByteVector32]](sha256HashesUnmarshaller) val nodeIdFormParam = "nodeId".as[PublicKey] val nodeIdsFormParam = "nodeIds".as[List[PublicKey]](pubkeyListUnmarshaller) val paymentHashFormParam = "paymentHash".as[ByteVector32](sha256HashUnmarshaller) val fromFormParam = "from".as[Long] val toFormParam = "to".as[Long] val amountMsatFormParam = "amountMsat".as[MilliSatoshi] val invoiceFormParam = "invoice".as[PaymentRequest] // custom directive to fail with HTTP 404 (and JSON response) if the element was not found def completeOrNotFound[T](fut: Future[Option[T]])(implicit marshaller: ToResponseMarshaller[T]): Route = onComplete(fut) { case Success(Some(t)) => complete(t) case Success(None) => complete(HttpResponse(NotFound).withEntity(ContentTypes.`application/json`, serialization.writePretty(ErrorResponse("Not found")))) case Failure(_) => reject } def withChannelIdentifier: Directive1[ChannelIdentifier] = formFields(channelIdFormParam.?, shortChannelIdFormParam.?).tflatMap { case (Some(channelId), None) => provide(Left(channelId)) case (None, Some(shortChannelId)) => provide(Right(shortChannelId)) case _ => reject(MalformedFormFieldRejection("channelId/shortChannelId", "Must specify either the channelId or shortChannelId (not both)")) } def withChannelsIdentifier: Directive1[List[ChannelIdentifier]] = formFields(channelIdFormParam.?, channelIdsFormParam.?, shortChannelIdFormParam.?, shortChannelIdsFormParam.?).tflatMap { case (None, None, None, None) => reject(MalformedFormFieldRejection("channelId(s)/shortChannelId(s)", "Must specify channelId, channelIds, shortChannelId or shortChannelIds")) case (channelId_opt, channelIds_opt, shortChannelId_opt, shortChannelIds_opt) => val channelId: List[ChannelIdentifier] = channelId_opt.map(cid => Left(cid)).toList val channelIds: List[ChannelIdentifier] = channelIds_opt.map(_.map(cid => Left(cid))).toList.flatten val shortChannelId: List[ChannelIdentifier] = shortChannelId_opt.map(scid => Right(scid)).toList val shortChannelIds: List[ChannelIdentifier] = shortChannelIds_opt.map(_.map(scid => Right(scid))).toList.flatten provide((channelId ++ channelIds ++ shortChannelId ++ shortChannelIds).distinct) } }
Example 70
Source File: HttpService.scala From ddd-leaven-akka-v2 with MIT License | 5 votes |
package ecommerce.shipping import akka.actor.{Actor, ActorLogging, Props} import akka.http.scaladsl.Http import akka.http.scaladsl.server.Directives import pl.newicom.dddd.streams.ImplicitMaterializer import akka.util.Timeout import com.typesafe.config.Config import ecommerce.shipping.app.ShipmentViewEndpoint import org.json4s.Formats import pl.newicom.dddd.serialization.JsonSerHints._ import pl.newicom.dddd.view.sql.SqlViewStore import scala.concurrent.duration.FiniteDuration import slick.jdbc.PostgresProfile object HttpService { def props(interface: String, port: Int, askTimeout: FiniteDuration): Props = Props(new HttpService(interface, port)(askTimeout)) } class HttpService(interface: String, port: Int)(implicit askTimeout: Timeout) extends Actor with ActorLogging with ShippingReadFrontConfiguration with ImplicitMaterializer with Directives { import context.dispatcher implicit val formats: Formats = fromConfig(config) implicit val profile = PostgresProfile Http(context.system).bindAndHandle(route, interface, port) log.info(s"Listening on $interface:$port") override def receive: Receive = Actor.emptyBehavior override def config: Config = context.system.settings.config lazy val endpoints: ShipmentViewEndpoint = new ShipmentViewEndpoint private def route = (provide(new SqlViewStore(config)) & pathPrefix("ecommerce" / "shipping"))(endpoints) }
Example 71
Source File: HttpService.scala From ddd-leaven-akka-v2 with MIT License | 5 votes |
package ecommerce.sales import akka.actor.{Actor, ActorLogging, Props} import akka.http.scaladsl.Http import akka.http.scaladsl.server.Directives import pl.newicom.dddd.streams.ImplicitMaterializer import akka.util.Timeout import com.typesafe.config.Config import ecommerce.sales.app.ReservationViewEndpoint import io.github.lhotari.akka.http.health.HealthEndpoint.createDefaultHealthRoute import org.json4s.Formats import pl.newicom.dddd.serialization.JsonSerHints._ import pl.newicom.dddd.view.sql.SqlViewStore import scala.concurrent.duration.FiniteDuration import slick.jdbc.{JdbcProfile, PostgresProfile} object HttpService { def props(interface: String, port: Int, askTimeout: FiniteDuration): Props = Props(new HttpService(interface, port)(askTimeout)) } class HttpService(interface: String, port: Int)(implicit askTimeout: Timeout) extends Actor with ActorLogging with SalesReadFrontConfiguration with ImplicitMaterializer with Directives { import context.dispatcher implicit val formats: Formats = fromConfig(config) implicit val profile: JdbcProfile = PostgresProfile Http(context.system).bindAndHandle(route, interface, port) log.info(s"Listening on $interface:$port") override def receive: Receive = Actor.emptyBehavior override def config: Config = context.system.settings.config lazy val endpoints: ReservationViewEndpoint = new ReservationViewEndpoint private def route = pathPrefix("ecommerce" / "sales") { createDefaultHealthRoute() ~ provide(new SqlViewStore(config))(endpoints) } }
Example 72
Source File: OAuth2Provider.scala From akka-http-oauth2-provider with MIT License | 5 votes |
package scalaoauth2.provider import akka.http.scaladsl.model.StatusCodes._ import akka.http.scaladsl.server.Directives import akka.http.scaladsl.server.directives.Credentials import scalaoauth2.provider.OAuth2Provider.TokenResponse import spray.json.{JsValue, DefaultJsonProtocol} import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future import scala.util.{Failure, Success} trait OAuth2Provider[U] extends Directives with DefaultJsonProtocol { import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ val oauth2DataHandler: DataHandler[U] val tokenEndpoint: TokenEndpoint def grantResultToTokenResponse(grantResult: GrantHandlerResult[U]): JsValue = OAuth2Provider.tokenResponseFormat.write( TokenResponse( grantResult.tokenType, grantResult.accessToken, grantResult.expiresIn.getOrElse(1L), grantResult.refreshToken.getOrElse("") ) ) def oauth2Authenticator( credentials: Credentials ): Future[Option[AuthInfo[U]]] = credentials match { case Credentials.Provided(token) => oauth2DataHandler.findAccessToken(token).flatMap { case Some(token) => oauth2DataHandler.findAuthInfoByAccessToken(token) case None => Future.successful(None) } case _ => Future.successful(None) } def accessTokenRoute = pathPrefix("oauth") { path("access_token") { post { formFieldMap { fields => onComplete( tokenEndpoint.handleRequest( new AuthorizationRequest( Map(), fields.map(m => m._1 -> Seq(m._2)) ), oauth2DataHandler ) ) { case Success(maybeGrantResponse) => maybeGrantResponse.fold( oauthError => complete(Unauthorized), grantResult => complete(grantResultToTokenResponse(grantResult)) ) case Failure(ex) => complete( InternalServerError, s"An error occurred: ${ex.getMessage}" ) } } } } } } object OAuth2Provider extends DefaultJsonProtocol { case class TokenResponse( token_type: String, access_token: String, expires_in: Long, refresh_token: String ) implicit val tokenResponseFormat = jsonFormat4(TokenResponse) }