当前位置: 首页>>代码示例>>Scala>>正文


Scala HttpService类代码示例

本文整理汇总了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/")
  }
} 
开发者ID:allansene,项目名称:spray-scala-akka-book-catalog,代码行数:25,代码来源:ApiDocsUi.scala

示例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)))
        }
      }
    }
  }


} 
开发者ID:simonko91,项目名称:event-driven-orders,代码行数:41,代码来源:ApiRoutes.scala

示例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)
  }
} 
开发者ID:rockdragon,项目名称:fourthgala,代码行数:39,代码来源:MyServer.scala

示例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")

} 
开发者ID:rockdragon,项目名称:fourthgala,代码行数:38,代码来源:boxOffice.scala

示例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")
          }
        }
      }
    }
} 
开发者ID:peteslater-sky,项目名称:SprayWorkshop,代码行数:31,代码来源:PersonService.scala

示例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>
        }
      }
    }
} 
开发者ID:peteslater-sky,项目名称:SprayWorkshop,代码行数:15,代码来源:HelloService.scala

示例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)
      }
    }
  }
} 
开发者ID:peteslater-sky,项目名称:SprayWorkshop,代码行数:24,代码来源:PersonServiceSpec.scala

示例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")
      }
    }
  }
} 
开发者ID:peteslater-sky,项目名称:SprayWorkshop,代码行数:18,代码来源:HelloServiceSpec.scala

示例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 ) )
            }
          }
        }
      }
    }
} 
开发者ID:knowledgedataaction,项目名称:credit-approvals,代码行数:48,代码来源:CreditService.scala

示例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")
            }
        }
    }
} 
开发者ID:sretsnom,项目名称:mangareader,代码行数:23,代码来源:HttpServer.scala

示例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."))
    }
} 
开发者ID:mijicd,项目名称:spray-akka-demo,代码行数:32,代码来源:FailureHandlers.scala

示例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)
          }
        }
      }
    }
} 
开发者ID:ChengGit,项目名称:ticketHub,代码行数:37,代码来源:RouterActor.scala

示例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) )
        }

      }
    }
  }

} 
开发者ID:reynoldsm88,项目名称:scala-drools,代码行数:43,代码来源:CreditService.scala

示例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)
      }
    }
  }
} 
开发者ID:TruenoDB,项目名称:trueno-compute-server,代码行数:19,代码来源:ChunkEncodedStreamingSupport.scala

示例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)
    )
  }
} 
开发者ID:synereo,项目名称:synereo,代码行数:48,代码来源:CORSSupport.scala


注:本文中的spray.routing.HttpService类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。