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


Scala StandardRoute类代码示例

本文整理汇总了Scala中akka.http.scaladsl.server.StandardRoute的典型用法代码示例。如果您正苦于以下问题:Scala StandardRoute类的具体用法?Scala StandardRoute怎么用?Scala StandardRoute使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了StandardRoute类的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: ImperativeRequestContext

//设置package包名称以及导入依赖的类
package org.cristal.api.helper

import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.Directives.complete
import akka.http.scaladsl.server.{RequestContext, Route, RouteResult, StandardRoute}
import scala.concurrent.Promise


final class ImperativeRequestContext(ctx: RequestContext, promise: Promise[RouteResult]) {
  private implicit val ec = ctx.executionContext
  def complete(obj: ToResponseMarshallable): Unit = ctx.complete(obj).onComplete(promise.complete)
  def fail(error: Throwable): Unit = ctx.fail(error).onComplete(promise.complete)
}

trait ApiHelper {

  def notImplementedResponse(msg: String = ""): StandardRoute =
    complete(HttpEntity(ContentTypes.`text/html(UTF-8)`,
      s"<h1>We plan to support this resource soon.</h1>"))

  def imperativelyComplete(inner: ImperativeRequestContext => Unit): Route = { ctx: RequestContext =>
    val p = Promise[RouteResult]()
    inner(new ImperativeRequestContext(ctx, p))
    p.future
  }

} 
开发者ID:frecano,项目名称:cristal,代码行数:29,代码来源:ApiHelper.scala

示例2: ResponseBuilder

//设置package包名称以及导入依赖的类
package homeworkzen.rest

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.{StatusCode, StatusCodes}
import akka.http.scaladsl.server.Directives.complete
import akka.http.scaladsl.server.StandardRoute
import homeworkzen.model._
import spray.json.{DefaultJsonProtocol, JsonFormat, RootJsonFormat}

object ResponseBuilder extends DefaultJsonProtocol with SprayJsonSupport {

  private case class ResponseTemplateWithoutResult(statusCode: Int, message: String)

  private case class ResponseTemplateWithResult[T](statusCode: Int, message: String, result: T)

  private implicit val responseTemplateWithoutResultFormat: RootJsonFormat[ResponseTemplateWithoutResult] =
    jsonFormat2(ResponseTemplateWithoutResult)

  // same as akka http default
  def internalServerError(): StandardRoute =
    complete(StatusCodes.InternalServerError -> "There was an internal server error.")

  def success(statusCode: StatusCode): StandardRoute =
    complete(statusCode -> ResponseTemplateWithoutResult(statusCode.intValue, "success"))

  def success[T](statusCode: StatusCode, result: T)(implicit jsonFormat: JsonFormat[T]): StandardRoute = {
    implicit val format: RootJsonFormat[ResponseTemplateWithResult[T]] = jsonFormat3(ResponseTemplateWithResult[T])
    complete(statusCode -> ResponseTemplateWithResult(statusCode.intValue, "success", result))
  }

  def failure(statusCode: StatusCode, message: String): StandardRoute =
    complete(statusCode -> ResponseTemplateWithoutResult(statusCode.intValue, message))

  def notFound(unitId: UnitId): StandardRoute = {
    val body = ResponseTemplateWithoutResult(StatusCodes.NotFound.intValue, s"Could not find station with id ${unitId.id.toString}")
    complete(StatusCodes.NotFound -> body)
  }
} 
开发者ID:anopse,项目名称:HomeworkZen,代码行数:39,代码来源:ResponseBuilder.scala

示例3: routes

//设置package包名称以及导入依赖的类
package io.github.tpartyka.testapp

import akka.actor.Props
import akka.http.scaladsl.server.{Directives, Route, StandardRoute}
import akka.pattern.ask
import akka.util.Timeout
import io.github.tpartyka.testapp.AkkaEnv._
import io.github.tpartyka.testapp.api.CalculationRequest

import scala.concurrent.duration._

trait CalculationService extends BaseService {

  import Directives._
  import io.circe.generic.auto._

  implicit val timeout: Timeout = 3.seconds

  override protected def routes: Route =
    path("evaluate") {
      post {
        entity(as[CalculationRequest]) { request: CalculationRequest =>
          onComplete(
            system.actorOf(Props[CalculationActor]).ask(request).mapTo[StandardRoute]
          ) {
            response => response.fold(failWith, route => route)
          }
        }
      }
    }
} 
开发者ID:tpartyka,项目名称:test-app,代码行数:32,代码来源:CalculationService.scala

示例4: nothingHere

//设置package包名称以及导入依赖的类
package au.edu.utscic.athanorserver.server

import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ExceptionHandler, Route, StandardRoute}
import au.edu.utscic.athanorserver.message.Exception.UnknownAnalysisType
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s._


//noinspection ForwardReference
trait GenericApi extends Json4sSupport {

  import au.edu.utscic.athanorserver.StreamsContext._

  val version = "v2"
  val details:String = "no details yet" // ApiInfo(Config.name,Config.description,Config.version,Config.colour)
  val healthEndPoint = "health"

  val athanorExceptionHandler = ExceptionHandler {
    case _: UnknownAnalysisType =>
      extractUri { uri =>
        log.error(s"Request to $uri did not include a valid analysis type")
        complete(HttpResponse(InternalServerError, entity = "The request did not include a valid analysis type"))
      }
  }

  implicit val formats: Formats = DefaultFormats
  implicit val jacksonSerialization: Serialization = jackson.Serialization

  def nothingHere: StandardRoute =  complete(ResponseMessage("There is nothing at this URL"))

  val routes: Route = handleExceptions(athanorExceptionHandler) {
    pathSingleSlash {
      get(complete(ResponseMessage("The current version of this API can be found at /"+version)))
    } ~
      pathPrefix(version) {
        customRoutes ~
          path(healthEndPoint) {
            get(complete(ResponseMessage("ok")))
          } ~
          apiDetails ~
          adminRoutes
      }
  }

  val customRoutes: Route = path("custom") { get(complete("")) }
  val adminRoutes: Route = path("admin") { get(complete(""))}
  val apiDetails: Route = pathEnd(complete(ResponseMessage(details)))
} 
开发者ID:uts-cic,项目名称:athanor-server,代码行数:52,代码来源:GenericApi.scala

示例5: StatusService

//设置package包名称以及导入依赖的类
package g8.akkahttp.eventsvc

import java.lang.management.ManagementFactory

import akka.actor.ActorSystem
import akka.event.Logging
import akka.http.scaladsl.server.{Directives, StandardRoute}
import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport._

import scala.concurrent.duration._

class StatusService(system: ActorSystem) extends StatusServiceTrait {

  override protected def log      = Logging(system, "service")
  override protected def executor = system.dispatcher
}

trait StatusServiceTrait extends BaseComponent {
  import Directives._
  import g8.akkahttp.eventsvc.data._
  import io.circe.generic.auto._

  def getStatus: StandardRoute = {
    log.info("/status executed")
    complete(Status(Duration(ManagementFactory.getRuntimeMXBean.getUptime, MILLISECONDS).toString()))
  }
} 
开发者ID:stephmajor,项目名称:eventsvc,代码行数:28,代码来源:StatusService.scala

示例6: Pong

//设置package包名称以及导入依赖的类
package net.petitviolet.domain.pong

import akka.http.scaladsl.server.Directives.complete
import akka.http.scaladsl.server.StandardRoute

case class Pong(msg: String) {
  lazy val out: String = s"Pong!!! $msg"
}

object Pong {
  def apply(): Pong = {
    Pong("")
  }
}

trait PongService {
  def response(pong: Pong = Pong()): StandardRoute = {
    complete(pong.out)
  }
}
trait UsesPongService {
  val pongService: PongService
}

trait MixInPongService {
  val pongService: PongService = new PongServiceImpl
}

class PongServiceImpl extends PongService 
开发者ID:petitviolet,项目名称:akka-http-slick-ddd,代码行数:30,代码来源:Pong.scala

示例7: asJsonArray

//设置package包名称以及导入依赖的类
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 
开发者ID:blstream,项目名称:akka-viz,代码行数:32,代码来源:AkkaHttpHelpers.scala


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