本文整理汇总了Scala中spray.routing.HttpService类的典型用法代码示例。如果您正苦于以下问题:Scala HttpService类的具体用法?Scala HttpService怎么用?Scala HttpService使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HttpService类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1:
//设置package包名称以及导入依赖的类
package org.packtpublishing.web
import spray.routing.HttpService
trait ApiDocsUi {
this: HttpService =>
import spray.http.StatusCodes
import spray.routing._
import Directives._
val swaggerUiPath = "META-INF/resources/webjars/swagger-ui/2.1.4"
val apiDocsUiRoutes = get {
pathEndOrSingleSlash {
requestUri { uri =>
parameters('url.?) {
case Some(url) => getFromResource(s"$swaggerUiPath/index.html")
case None => redirect(uri.copy(query = uri.query.+:("url", "/api-docs")), StatusCodes.PermanentRedirect)
}
}
} ~ getFromResourceDirectory(s"$swaggerUiPath/")
}
}
示例2: submitOrder
//设置package包名称以及导入依赖的类
package com.github.eventdrivenorders.api
import com.github.eventdrivenorders.api.dto.NewOrderRequest
import com.github.eventdrivenorders.api.json.OrderFormats._
import domain.Order
import spray.httpx.SprayJsonSupport
import spray.json._
import spray.routing.HttpService
trait ApiRoutes extends HttpService with SprayJsonSupport {
def submitOrder(order: Order): Unit
def getStatus(orderId: Long): Option[String]
val routes = path("orders") {
post {
entity(as[NewOrderRequest]) { order =>
complete {
val orderId = OrderIDGenerator.next
println(s"New order request: $orderId $order")
submitOrder(Order(orderId, order.products))
JsObject(("orderId", JsNumber(orderId)))
}
}
}
} ~ path("orders" / LongNumber) { orderId =>
get {
complete {
getStatus(orderId).map { status =>
JsObject(("orderId", JsNumber(orderId)), ("status", JsString(status)))
}
}
}
}
}
示例3: MyServiceActor
//设置package包名称以及导入依赖的类
package akka_in_action.MyServer
import akka.actor.{Props, ActorSystem, Actor}
import akka.io.IO
import spray.can.Http
import spray.routing.HttpService
import spray.http.MediaTypes._
trait MyService extends HttpService {
val myRoute = {
path("something") {
respondWithMediaType(`text/plain`) {
complete("okay")
}
}
path("hello") {
respondWithMediaType(`text/plain`) {
complete("kitty")
}
}
}
}
class MyServiceActor extends Actor with MyService {
def actorRefFactory = context
def receive = runRoute(myRoute)
}
object server extends App {
try {
implicit val system = ActorSystem("my-system")
val handler = system.actorOf(Props[MyServiceActor], name = "my-service")
IO(Http) ! Http.Bind(handler, interface = "localhost", port = 8080)
} catch {
case e: Throwable => println("error: ", e)
}
}
示例4: boxOffice
//设置package包名称以及导入依赖的类
package akka_in_action.GoTicks
import akka.actor.Actor.Receive
import akka.actor._
import com.typesafe.config.ConfigFactory
import spray.routing.{HttpService, HttpServiceActor}
object boxOffice {
class BoxOffice extends Actor {
def receive = {
case _ =>
}
}
trait BoxOfficeCreator {
this: Actor =>
def createBoxOffice: ActorRef = {
context.actorOf(Props[BoxOffice], "boxOffice")
}
}
trait RestApi extends HttpService with ActorLogging with BoxOfficeCreator {
actor: Actor =>
val boxOffice = createBoxOffice
}
class RestInterface extends HttpServiceActor with RestApi {
override def receive: Receive = ???
}
val config = ConfigFactory.load()
val system = ActorSystem("singlenode", config.getConfig("remote-single"))
val restInterface = system.actorOf(Props[RestInterface], "restInterface")
}
示例5: Person
//设置package包名称以及导入依赖的类
package com.sky.workshop.spray
import spray.routing.HttpService
import spray.http.MediaTypes._
import spray.json.DefaultJsonProtocol
import spray.httpx.unmarshalling._
import spray.httpx.marshalling._
case class Person(title: String, forename: String, surname: String)
object PersonJsonProtocol extends DefaultJsonProtocol {
implicit val PersonJF = jsonFormat3(Person)
}
import PersonJsonProtocol._
import spray.httpx.SprayJsonSupport._
trait PersonService extends HttpService {
val personRoutes =
path("person") {
get {
respondWithMediaType(`application/json`) {
complete {
Person("Mr", "Bobby", "Bobbyson")
}
}
}
}
}
示例6:
//设置package包名称以及导入依赖的类
package com.sky.workshop.spray
import spray.routing.HttpService
trait HelloService extends HttpService {
val helloRoutes =
path("hello") {
get {
complete {
<h1>Say hello to spray</h1>
}
}
}
}
示例7: PersonServiceSpec
//设置package包名称以及导入依赖的类
package com.sky.workshop.spray
import org.specs2.mutable.Specification
import spray.testkit.Specs2RouteTest
import spray.routing.HttpService
class PersonServiceSpec extends Specification with Specs2RouteTest with HttpService with PersonService {
def actorRefFactory = system
val personRespone = """{
| "title": "Mr",
| "forename": "Bobby",
| "surname": "Bobbyson"
|}""".stripMargin
"The Hello endpoint" should {
"return a greeting" in {
Get("/person") ~> personRoutes ~> check {
responseAs[String] must be equalTo(personRespone)
}
}
}
}
示例8: HelloServiceSpec
//设置package包名称以及导入依赖的类
package com.sky.workshop.spray
import org.specs2.mutable.Specification
import spray.testkit.Specs2RouteTest
import spray.routing.HttpService
class HelloServiceSpec extends Specification with Specs2RouteTest with HttpService with HelloService {
def actorRefFactory = system
"The Hello endpoint" should {
"return a greeting" in {
Get("/hello") ~> helloRoutes ~> check {
responseAs[String] must contain("Say hello")
}
}
}
}
示例9: 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 ) )
}
}
}
}
}
}
示例10: HttpServerActor
//设置package包名称以及导入依赖的类
package com.sretsnom.mangareader.server
import akka.actor._
import spray.routing.HttpService
class HttpServerActor extends Actor with ActorLogging with HttpServer {
def actorRefFactory = context
def receive = runRoute(serverRoute)
}
trait HttpServer extends HttpService {
val serverRoute = {
get {
path("health") {
complete("PONG!")
} ~ path("client_registration") {
getFromFile("client_registration.html")
}
}
}
}
示例11: handleErrors
//设置package包名称以及导入依赖的类
package com.github.mijicd.waes.api
import com.github.mijicd.waes.representations.{Error, JsonFormats}
import spray.http.StatusCodes
import spray.routing.{ExceptionHandler, HttpService, MalformedRequestContentRejection, RejectionHandler}
import spray.util.LoggingContext
trait FailureHandlers {
this: HttpService =>
import JsonFormats._
implicit def handleErrors(implicit log: LoggingContext) =
ExceptionHandler {
case e: IllegalArgumentException =>
log.warning(s"Failed to complete request. Cause: ${e.getMessage}")
complete(StatusCodes.BadRequest, Error(e.getMessage))
case t: Throwable =>
log.error(s"Failed to complete request. Cause: ${t.getMessage}")
complete(StatusCodes.InternalServerError, Error(t.getMessage))
}
implicit def handleRejections(implicit log: LoggingContext) =
RejectionHandler {
case MalformedRequestContentRejection(msg, cause) :: Nil =>
log.warning(s"Invalid content submitted. Cause: $msg")
complete(StatusCodes.BadRequest, Error(msg))
case _ =>
complete(StatusCodes.InternalServerError, Error("Server-side error occurred."))
}
}
示例12: RouterActor
//设置package包名称以及导入依赖的类
package com.example.routing
import akka.actor.{Actor, ActorLogging, Props}
import com.example.actors.TimetableActor
import com.example.ticketHub.TimetableQueryMessage
import spray.httpx.SprayJsonSupport
import spray.routing.HttpService
class RouterActor extends HttpService with Actor with ActorLogging with SprayJsonSupport{
implicit def actorRefFactory = context
def timetableActor = context.actorOf(Props[TimetableActor])
def receive = runRoute(route)
val route = {
get{
pathPrefix("akka"){
pathEndOrSingleSlash{
getFromResource("web/html/index.html")
}
} ~
path("akka" / "health") {
complete {
"ticket hub alive"
}
} ~
path("akka" / "timetable") {
parameter('trainRef.as[Int]){ trainRef =>
ctx => timetableActor ! TimetableQueryMessage(ctx,trainRef)
}
}
}
}
}
示例13: CreditServiceActor
//设置package包名称以及导入依赖的类
package org.mireynol.credit.service
import akka.actor.Actor
import org.mireynol.credit.model.Approval
import org.mireynol.rules.api.RulesService
import org.mireynol.rules.drools.ClasspathDroolsRulesService
import spray.httpx.SprayJsonSupport
import spray.routing.HttpService
class CreditServiceActor extends Actor with CreditService {
def actorRefFactory = context
def receive = {
runRoute( applicationRoute )
}
}
trait CreditService extends HttpService with SprayJsonSupport {
import spray.http.MediaTypes._
import org.mireynol.credit.model.Application
import org.mireynol.credit.model.ApplicationJSONFormat.applicationFormat
import org.mireynol.credit.model.Approval
import org.mireynol.credit.model.ApprovalJSONFormat.approvalFormat
val rulesService : RulesService = new ClasspathDroolsRulesService( )
val applicationRoute = path( "applications" ) {
post {
respondWithMediaType( `application/json` )
entity( as[ Application ] ) { application =>
detach() {
val results = rulesService.execute( "credit-approval-ksession", None, List( application ),classOf[ Approval ] ).asInstanceOf[ List[ Approval ] ]
complete( results(0) )
}
}
}
}
}
示例14: sendStreamingResponse
//设置package包名称以及导入依赖的类
package spark.jobserver
import akka.actor.Props
import spray.routing.{HttpService, RequestContext}
trait ChunkEncodedStreamingSupport {
this: HttpService =>
protected def sendStreamingResponse(ctx: RequestContext,
chunkSize: Int,
byteIterator: Iterator[_]): Unit = {
actorRefFactory.actorOf {
Props {
new ChunkEncodingActor(ctx, chunkSize, byteIterator)
}
}
}
}
示例15: cors
//设置package包名称以及导入依赖的类
package com.biosimilarity.evaluator.spray.directives
import spray.http.HttpHeaders.{
`Access-Control-Allow-Headers`,
`Access-Control-Allow-Methods`,
`Access-Control-Allow-Origin`,
`Access-Control-Max-Age`
}
import spray.http._
import spray.routing.{HttpService, MethodRejection, Rejected, _}
// see also https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
trait CORSSupport { this: HttpService =>
private val allowOriginHeader = `Access-Control-Allow-Origin`(AllOrigins)
private val optionsCorsHeaders = List(
//`Access-Control-Allow-Methods`(HttpMethods.POST, HttpMethods.GET,HttpMethods.PUT, HttpMethods.DELETE , HttpMethods.OPTIONS),
`Access-Control-Allow-Headers`(
"Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Host, Referer, User-Agent"),
`Access-Control-Max-Age`(1728000)
)
def cors[T]: Directive0 = mapRequestContext { ctx =>
ctx.withRouteResponseHandling {
// OPTION request for a resource that responds to other methods
case Rejected(x) if ctx.request.method.equals(HttpMethods.OPTIONS) && x.exists(_.isInstanceOf[MethodRejection]) => {
val allowedMethods: List[HttpMethod] = x.collect { case rejection: MethodRejection => rejection.supported }
ctx.complete {
HttpResponse().withHeaders(
`Access-Control-Allow-Methods`(HttpMethods.OPTIONS, allowedMethods: _*) :: allowOriginHeader ::
optionsCorsHeaders
)
}
}
}.withHttpResponseHeadersMapped { headers =>
allowOriginHeader :: headers
}
}
override def timeoutRoute = complete {
HttpResponse(
StatusCodes.InternalServerError,
HttpEntity(ContentTypes.`text/plain(UTF-8)`, "The server was not able to produce a timely response to your request."),
List(allowOriginHeader)
)
}
}