本文整理汇总了Scala中spray.routing.Route类的典型用法代码示例。如果您正苦于以下问题:Scala Route类的具体用法?Scala Route怎么用?Scala Route使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Route类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: addManifest
//设置package包名称以及导入依赖的类
package com.pacbio.common.services
import scala.collection.mutable.ArrayBuffer
import spray.routing.{Route, RouteConcatenation}
import com.pacbio.common.models.PacBioComponentManifest
import com.pacbio.common.dependency.Singleton
import scala.collection.mutable
trait ServiceComposer extends RouteConcatenation with RouteProvider {
val services = ArrayBuffer.empty[Singleton[PacBioService]]
private val _manifests = mutable.Set.empty[PacBioComponentManifest]
// Enable loading manifests that are "external" to the system (e.g., SL, SL UI)
def addManifest(m: PacBioComponentManifest): PacBioComponentManifest = {
_manifests.add(m)
m
}
def addManifests(ms: Set[PacBioComponentManifest]): Set[PacBioComponentManifest] = {
_manifests ++= ms
ms
}
def addService(service: Singleton[PacBioService]) = {
services += service
}
def routes(): Route = {
services.map(_().prefixedRoutes).reduce(_ ~ _)
}
// This is a clumsy way to create a Set with 'id' being the
// single component to compute equality
def manifests(): Set[PacBioComponentManifest] = {
(services.map(_().manifest).toSet ++ _manifests)
.toList
.map(x => (x.id, x))
.toMap.values.toSet
}
}
示例2: CreditApprovalsServiceActor
//设置package包名称以及导入依赖的类
package org.kda.credit.service
import akka.actor.Actor
import spray.httpx.SprayJsonSupport
import spray.routing.{HttpService, Route}
import org.kda.credit.model._
import spray.httpx.SprayJsonSupport._
class CreditApprovalsServiceActor extends Actor with CreditApprovalsService {
def actorRefFactory = {
context
}
def receive = {
runRoute( applicationRoute )
}
}
trait CreditApprovalsService extends HttpService with SprayJsonSupport {
import spray.http.MediaTypes._
import org.kda.credit.model.{ApprovedApplication, PendingApplication, CreditLine, Customer}
import org.kda.credit.service.CreditApprovalJSonProtocol._
//@formatter:off
val applicationRoute: Route =
path( "credit-approvals" ) {
get {
complete {
PendingApplication( "123" ) // you can POST this payload to the service to convert it into an approved application
}
} ~
post {
respondWithMediaType( `application/json` )
entity( as[ PendingApplication ] ) { application =>
detach() {
// in Part 4 this code will be integrated with the rules engine to actually perform the business logic
val customer = Customer( application.customerId, 400 )
val credit = CreditLine( customer, BigDecimal( 5000 ) )
complete {
ApprovedApplication( customer.id, Some( credit ) )
}
}
}
}
}
}
示例3: sending
//设置package包名称以及导入依赖的类
package eu.shiftforward.apso.spray
import akka.actor.ActorSystem
import akka.io.IO
import spray.can.Http
import spray.http.{ HttpHeader, HttpRequest, RemoteAddress, Uri }
import spray.http.HttpHeaders.{ `Remote-Address`, `X-Forwarded-For` }
import spray.routing.{ Directive1, RequestContext, Route }
trait ProxySupport extends ClientIPDirectives {
private def sending(f: RequestContext => HttpRequest)(implicit system: ActorSystem): Route = {
val transport = IO(Http)(system)
ctx => transport.tell(f(ctx), ctx.responder)
}
private def getHeaders(ip: Option[RemoteAddress], headers: List[HttpHeader] = Nil) = {
// filter `Host` header
val hs = headers.filterNot(header => header.is("host"))
// add `X-Forwarded-For` header
ip.fold(hs)(addForwardedFor(_, hs))
}
private def addForwardedFor(ip: RemoteAddress, headers: List[HttpHeader]): List[HttpHeader] = {
headers match {
case Nil =>
// No `X-Forwarded-For` found in headers, so just add the new one
`X-Forwarded-For`(ip) :: Nil
case `X-Forwarded-For`(ips) :: tail =>
`X-Forwarded-For`(ips :+ ip) :: tail
case notForwardedFor :: tail =>
notForwardedFor :: addForwardedFor(ip, tail)
}
}
private val optionalRemoteAddress: Directive1[Option[RemoteAddress]] =
headerValuePF { case `Remote-Address`(address) => Some(address) } | provide(None)
def proxyTo(uri: Uri)(implicit system: ActorSystem): Route = {
optionalRemoteAddress { ip =>
sending(ctx => ctx.request.copy(
uri = uri,
headers = getHeaders(ip, ctx.request.headers)))
}
}
def proxyToUnmatchedPath(uri: Uri)(implicit system: ActorSystem): Route = {
optionalRemoteAddress { ip =>
sending { ctx =>
ctx.request.copy(
uri = uri.withPath(uri.path.++(ctx.unmatchedPath)).withQuery(ctx.request.uri.query),
headers = getHeaders(ip, ctx.request.headers))
}
}
}
}
示例4: SSServer
//设置package包名称以及导入依赖的类
package com.server
import com.services.StorageService
import akka.actor.ActorSystem
import com.support.CORSSupport
import spray.http.MediaTypes
import spray.routing.{Route, SimpleRoutingApp}
object SSServer extends App with SimpleRoutingApp with CORSSupport{
implicit val actorSystem = ActorSystem()
//Custom directive to replace the inclcusion of the stated return type header
def getJson(route: Route) = get{
respondWithMediaType(MediaTypes.`application/json`){
route
}
}
//Define Each route independently as lazy vals to keep code clean
//Link the names of each route in the start server method
lazy val helloRoute = get {
cors{
path("hello") {
complete {
"Welcome to the AWS Storage Service \n here are a list of the available routes:"
}
}
}
}
lazy val store_pcs_processA = get {
cors{
path("storageServices" / "s3" / "processControllers" / "processA" / "withObject" / Segment / "andDestination" / Segment ) { (data, fileName) =>
complete {
StorageService.writeObjectToS3(data,fileName)
}
}
}
}
startServer(interface = "localhost", port = 8084) {
helloRoute~
store_pcs_processA
}
}
示例5: RestRoutingSpecs
//设置package包名称以及导入依赖的类
package com.cart.routing
import java.util.UUID
import org.scalatest.FlatSpec
import org.scalatest.Matchers
import com.cart.Cart
import com.cart.Carts
import com.cart.GetCarts
import com.cart.RestMessage
import akka.testkit.TestActorRef
import akka.testkit.TestProbe
import spray.routing.Route
import spray.testkit.ScalatestRouteTest
class RestRoutingSpecs extends FlatSpec with ScalatestRouteTest with Matchers {
val getCartsService = TestProbe()
def restRouting = TestActorRef(new RestRouting() {
override def carts(message: RestMessage): Route =
ctx => perRequest(ctx, getCartsService.ref, message)
})
"RestRouting" should "get Carts" in {
val getCarts = Get("/carts") ~> restRouting.underlyingActor.route
getCartsService.expectMsg(GetCarts())
val uuid = UUID.randomUUID().toString()
getCartsService.reply(Carts(Seq(Cart(uuid))))
getCarts ~> check {
responseAs[String] should equal(s"""{"carts":[{"id":"$uuid"}]}""")
}
}
}
示例6: RestService
//设置package包名称以及导入依赖的类
package com.me.finalization
import akka.actor.{Actor, ActorRef}
import akka.io.IO
import akka.pattern.ask
import com.me.finalization.Domain.{Container, Junction}
import com.me.finalization.Messages.{Go, WhereShouldIGo}
import spray.can.Http
import spray.routing.{HttpServiceBase, Route}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
class RestService(nextActorRef: ActorRef, exposedPort: Int) extends Actor with RestInterface {
implicit val system = context.system
override def decider: ActorRef = nextActorRef
def receive = runRoute(route)
IO(Http) ! Http.Bind(self, interface = "0.0.0.0", port = exposedPort)
}
trait RestInterface extends HttpServiceBase {
import spray.httpx.SprayJsonSupport._
val route: Route = {
path("junctions" / IntNumber / "decisionForContainer" / IntNumber) { (junctionId, containerId) =>
get {
complete {
//println(s"Request for junction $junctionId and container $containerId")
val junction = Junction(junctionId)
val container = Container(containerId)
//val decision = Decisions.whereShouldContainerGo(junction, container)
decider.ask(WhereShouldIGo(junction, container))(5 seconds).mapTo[Go]
}
}
}
}
def decider: ActorRef = ???
}
示例7: RoutedHttpService
//设置package包名称以及导入依赖的类
package com.example.spray
import scala.util.control.NonFatal
import akka.actor.{Actor, ActorLogging, Props}
import spray.routing.{ExceptionHandler, HttpService, RejectionHandler, Route, RouteConcatenation, RoutingSettings}
import spray.util.LoggingContext
import spray.http.StatusCodes.InternalServerError
import com.example.spray.add.AddService
import com.example.spray.hello.HelloService
import com.example.spray.swagger.SwaggerDocService
class RoutedHttpService(route: Route) extends Actor with HttpService with ActorLogging {
implicit def actorRefFactory = context
implicit val handler = ExceptionHandler {
case NonFatal(ErrorResponseException(statusCode, entity)) => ctx =>
ctx.complete((statusCode, entity))
case NonFatal(e) => ctx => {
log.error(e, InternalServerError.defaultMessage)
ctx.complete(InternalServerError)
}
}
def receive: Receive =
runRoute(route)(handler, RejectionHandler.Default, context, RoutingSettings.default, LoggingContext.fromActorRefFactory)
}
示例8: ApiActor
//设置package包名称以及导入依赖的类
package org.xiaon
package hashservice
package http
import akka.actor.{ ActorRef, Props, ActorLogging }
import spray.routing.{ RequestContext, Route, HttpService, HttpServiceActor }
import spray.http.StatusCodes
import spray.httpx.SprayJsonSupport._
import domain.SimpleJob
import processor.ProcessingActor
class ApiActor(settings: Settings) extends HttpServiceActor with HttpService with ActorLogging {
import ApiActor._
import ProcessingActor._
private[http] val timeout = settings.Timeout
def receive = runRoute(route)
private[hashservice] def route: Route = {
path(Ping) {
get {
complete(StatusCodes.OK -> "pong")
}
} ~
pathPrefix(Api) {
path(Service) {
post {
entity(as[SimpleJob]) { job =>
requestContext =>
val processor = createProcessor(requestContext)
processor ! job
}
}
}
}
}
private[hashservice] def createProcessor(ctx: RequestContext): ActorRef =
context.actorOf(Props(new ProcessingActor(timeout, resultCallback = completeJobRequest(ctx))))
private[hashservice] def completeJobRequest(ctx: RequestContext)(result: JobResult): Unit = {
result match {
case Right(job) => ctx.complete(StatusCodes.Accepted -> job)
case Left(error) => ctx.complete(StatusCodes.ServiceUnavailable -> error)
}
}
}
object ApiActor {
private[hashservice] val Ping = "ping"
private[hashservice] val Api = "api"
private[hashservice] val Service = "service"
}
示例9: SSServer
//设置package包名称以及导入依赖的类
package com.server
import com.services.StorageService
import akka.actor.ActorSystem
import com.support.CORSSupport
import spray.http.MediaTypes
import spray.routing.{Route, SimpleRoutingApp}
object SSServer extends App with SimpleRoutingApp with CORSSupport{
implicit val actorSystem = ActorSystem()
//Custom directive to replace the inclcusion of the stated return type header
def getJson(route: Route) = get{
respondWithMediaType(MediaTypes.`application/json`){
route
}
}
//I have defined each route independently as lazy vals to keep the code clean
//Endpoint: List avalable endpoints
lazy val helloRoute = get {
cors{
path("hello") {
complete {
"Welcome to the MicroDG AWS-Stroage-Service" +
"\n Routes:" +
"\n Store output fro, Process A: storageServices/s3/processControllers/processA/withObject/{json_object}/andDestination/{url}"
}
}
}
}
//Endpoint: Write output from Process A to an S3 bucket
lazy val store_pcs_processA = get {
cors{
path("storageServices" / "s3" / "processControllers" / "processA" / "withObject" / Segment / "andDestination" / Segment ) { (data, fileName) =>
complete {
StorageService.writeObjectToS3(data,fileName)
}
}
}
}
startServer(interface = "localhost", port = 8084) {
helloRoute~
store_pcs_processA
}
}
示例10: SprayEndpoints
//设置package包名称以及导入依赖的类
package org.zachary.demo
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import spray.httpx.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._
import spray.json._
import spray.routing.{HttpServiceActor, Route}
class SprayEndpoints(actorSystem: ActorSystem, am: ActorMaterializer) extends HttpServiceActor {
implicit val printer = CompactPrinter
implicit val orderFormat = jsonFormat2(Order.apply)
implicit val actorMaterializer = am
implicit val ec = actorSystem.dispatcher
def receive = runRoute(routes)
lazy val routes: Route = blockingGet
val blockingGet: Route = path("blocking" / IntNumber)(i => {
get {
complete {
Order.source(i)
.runFold(Seq.empty[Order])(_ :+ _)
}
}
})
}