本文整理汇总了Scala中akka.http.scaladsl.model.StatusCode类的典型用法代码示例。如果您正苦于以下问题:Scala StatusCode类的具体用法?Scala StatusCode怎么用?Scala StatusCode使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了StatusCode类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: route
//设置package包名称以及导入依赖的类
package com.ulasakdeniz.hakker
import akka.http.scaladsl.marshalling.{Marshal, ToEntityMarshaller}
import akka.http.scaladsl.model.{HttpHeader, HttpResponse, ResponseEntity, StatusCode}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import com.typesafe.config.ConfigFactory
import com.ulasakdeniz.hakker.template.Render
import de.heikoseeberger.akkahttpcirce.CirceSupport._
import io.circe.{Encoder, Json}
import io.circe.syntax._
import scala.collection.immutable
import scala.concurrent.ExecutionContext
trait Controller extends Render {
override lazy val config = ConfigFactory.load()
val StatusCodes = akka.http.scaladsl.model.StatusCodes
def route: Route
def apply(): Route = {
get {
// render frontend files
pathPrefix("js") {
renderDir("js")
}
} ~ route
}
def send(statusCode: StatusCode): Route = complete(statusCode)
def send[T](statusCode: StatusCode, content: T, headers: immutable.Seq[HttpHeader] = Nil)(
implicit marshaller: ToEntityMarshaller[T],
ec: ExecutionContext): Route = {
val response = Marshal(content)
.to[ResponseEntity](marshaller, ec)
.map(entity => {
HttpResponse(statusCode, headers = headers).withEntity(entity)
})
complete(response)
}
def sendJson[T](statusCode: StatusCode, content: T)(implicit encoder: Encoder[T],
ec: ExecutionContext): Route = {
sendJson(statusCode, content.asJson)
}
def sendJson[T](content: T)(implicit encoder: Encoder[T], ec: ExecutionContext): Route = {
sendJson(StatusCodes.OK, content)
}
def sendJson(statusCode: StatusCode, json: Json)(implicit ec: ExecutionContext): Route = {
send(statusCode, Option(json.noSpaces))
}
}
示例2: asThrowable
//设置package包名称以及导入依赖的类
package ca.schwitzer.scaladon
import akka.http.scaladsl.model.StatusCode
import play.api.libs.json.{JsPath, JsonValidationError}
sealed trait MastodonResponse[+A]
sealed trait MastodonError extends MastodonResponse[Nothing] {
def asThrowable: Throwable
}
object MastodonResponses {
case class Success[+A](elem: A) extends MastodonResponse[A]
}
object MastodonErrors {
case class JSONParseError(e: Throwable) extends MastodonError {
def asThrowable: Throwable = new Exception(toString)
override def toString: String = s"$e"
}
case class JSONValidationError(jsErrors: Seq[(JsPath, Seq[JsonValidationError])], e: Throwable) extends MastodonError {
def asThrowable: Throwable = new Exception(toString)
override def toString: String = s"$e\n$jsErrors"
}
case class ResponseError(statusCode: StatusCode, e: Throwable) extends MastodonError {
def asThrowable: Throwable = new Exception(toString)
override def toString: String = s"$statusCode\n$e"
}
}
示例3: WindTurbineSimulatorException
//设置package包名称以及导入依赖的类
package sample
import akka.actor.{Actor, ActorLogging, Props}
import akka.http.scaladsl.model.StatusCode
import akka.stream.ActorMaterializer
import sample.WindTurbineSimulator._
import sample.stream_actor.WebSocketClient
case class WindTurbineSimulatorException(id: String) extends RuntimeException
object WindTurbineSimulator {
def props(id: String, endpoint: String)(implicit materializer: ActorMaterializer) =
Props(classOf[WindTurbineSimulator], id, endpoint, materializer)
final case object Upgraded
final case object Connected
final case object Terminated
final case class ConnectionFailure(ex: Throwable)
final case class FailedUpgrade(statusCode: StatusCode)
}
class WindTurbineSimulator(id: String, endpoint: String)
(implicit materializer: ActorMaterializer)
extends Actor with ActorLogging {
implicit private val system = context.system
implicit private val executionContext = system.dispatcher
val webSocket = WebSocketClient(id, endpoint, self)
override def receive: Receive = startup //initial state
private def startup: Receive = {
case Upgraded =>
log.info(s"$id : WebSocket upgraded")
case FailedUpgrade(statusCode) =>
log.error(s"$id : Failed to upgrade WebSocket connection: $statusCode")
throw WindTurbineSimulatorException(id)
case ConnectionFailure(ex) =>
log.error(s"$id : Failed to establish WebSocket connection: $ex")
throw WindTurbineSimulatorException(id)
case Connected =>
log.info(s"$id : WebSocket connected")
context.become(running)
}
private def running: Receive = {
case Terminated =>
log.error(s"$id : WebSocket connection terminated")
throw WindTurbineSimulatorException(id)
case ConnectionFailure(ex) =>
log.error(s"$id : ConnectionFailure occurred: $ex")
throw WindTurbineSimulatorException(id)
}
}
示例4: SuccessfulOut
//设置package包名称以及导入依赖的类
package akka.http.documenteddsl.directives
import akka.http.documenteddsl.documentation.RouteDocumentation
import akka.http.scaladsl.model.{ContentType, StatusCode, StatusCodes}
import akka.http.scaladsl.server.Directive
import org.coursera.autoschema.AutoSchema
import play.api.libs.json.{JsValue, Writes}
import scala.reflect.runtime.{universe => ru}
trait UnmarshallingDDirectives {
final class SuccessfulOut[T : ru.TypeTag](status: StatusCode, example: Option[JsValue]) extends DDirective0 {
def describe(w: RouteDocumentation)(implicit as: AutoSchema): RouteDocumentation = w.outSuccess[T](status.intValue, example)
def delegate = Directive.Empty
}
final class ErrorOut(status: StatusCode, contentType: Option[String], description: Option[String]) extends DDirective0 {
def describe(w: RouteDocumentation)(implicit as: AutoSchema): RouteDocumentation = w.outError(status, contentType, description)
def delegate = Directive.Empty
}
object Out {
def apply[T : ru.TypeTag]: SuccessfulOut[T] = new SuccessfulOut(StatusCodes.OK, None)
def apply[T : ru.TypeTag](status: StatusCode): SuccessfulOut[T] = new SuccessfulOut(status, None)
def apply[T : ru.TypeTag](example: T)(implicit writes: Writes[T]): SuccessfulOut[T] = new SuccessfulOut(StatusCodes.OK, Some(writes writes example))
def apply[T : ru.TypeTag](status: StatusCode, example: T)(implicit writes: Writes[T]): SuccessfulOut[T] = new SuccessfulOut(status, Some(writes writes example))
def success(status: StatusCode): SuccessfulOut[Nothing] = new SuccessfulOut(status, None)
def error(status: StatusCode): ErrorOut = new ErrorOut(status, None, None)
def apply(status: StatusCode, description: String): ErrorOut = new ErrorOut(status, None, Some(description))
def apply(status: StatusCode, contentType: ContentType, description: String): ErrorOut = new ErrorOut(status, Some(contentType.toString()), Some(description))
}
}
object UnmarshallingDDirectives extends UnmarshallingDDirectives
示例5: OutDocumentation
//设置package包名称以及导入依赖的类
package akka.http.documenteddsl.documentation
import akka.http.documenteddsl.documentation.OutDocumentation.Payload._
import akka.http.documenteddsl.documentation.OutDocumentation._
import akka.http.scaladsl.model.StatusCode
import play.api.libs.json.{JsObject, JsValue}
case class OutDocumentation(
success: List[Success] = Nil,
failure: List[Failure] = Nil) {
def :+(r: Payload): OutDocumentation = r match {
case r: Success => copy(success = success :+ r)
case r: Failure => copy(failure = failure :+ r)
}
}
object OutDocumentation {
case class Status(code: Int, detail: String)
object Status {
def apply(statusCode: StatusCode): Status = Status(
statusCode.intValue,
statusCode.reason)
}
sealed trait Payload
object Payload {
case class Success(status: Status, contentType: String, schema: JsObject, example: Option[JsValue]) extends Payload
case class Failure(status: Status, contentType: Option[String], description: Option[String]) extends Payload
}
}
示例6: CustomDirectives
//设置package包名称以及导入依赖的类
package com.durooma.api.route
import akka.http.scaladsl.model.{StatusCode, StatusCodes}
import akka.http.scaladsl.server.RouteResult.{Complete, Rejected}
import akka.http.scaladsl.server.directives.BasicDirectives.mapRouteResult
import akka.http.scaladsl.server.directives.{AuthenticationDirective, Credentials}
import akka.http.scaladsl.server.{Directive0, Directives}
import com.durooma.api.route.RouteSystem._
import com.durooma.api.model.Session
import scala.concurrent.Future
class CustomDirectives extends Directives {
val authenticateToken: AuthenticationDirective[Session] = authenticateOAuth2Async("durooma", {
case Credentials.Provided(token) => Session.get(token)
case _ => Future.successful(None)
})
def completeDbMutation(result: Future[Int], statusCode: StatusCode = StatusCodes.OK) = complete(result.map({
case x if x > 0 => statusCode
case _ => StatusCodes.NotFound
}))
}
示例7: PageToDownload
//设置package包名称以及导入依赖的类
package ru.fediq.scrapingkit.platform
import akka.http.scaladsl.model.{HttpEntity, StatusCode}
import org.joda.time.DateTime
import ru.fediq.scrapingkit.model.PageRef
import ru.fediq.scrapingkit.scraper.Scraped
case class PageToDownload(
ref: PageRef
)
case class PageToEnqueue(
ref: PageRef
)
case class DownloadedPage(
ref: PageRef,
time: DateTime,
status: StatusCode,
body: HttpEntity.Strict
)
case class ScrapedPage(
page: DownloadedPage,
entities: Seq[Scraped]
)
case class ProcessedPage(
ref: PageRef
)
case class FailedPage(
ref: PageRef,
time: DateTime,
reason: Option[String] = None,
cause: Option[Throwable] = None
)
示例8: ops
//设置package包名称以及导入依赖的类
package com.github.btesila.weather.monitor.routes
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.model.{StatusCode, StatusCodes}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import com.github.btesila.weather.monitor.WeatherMonitorOps
import com.github.btesila.weather.monitor.model.WeatherMonitorProtocol
import spray.json.RootJsonWriter
import scala.concurrent.Future
trait WeatherMonitorRoutes extends WeatherMonitorProtocol {
def ops: WeatherMonitorOps
val routes = pathPrefix("weather") {
(get & path("current" / "conditions")) {
parameters('city.as[String], 'country.as[String]) { (city, country) =>
completeWith(StatusCodes.OK, ops.getLocationCrtRecord(city, country))
}
} ~
(get & path("today")) {
parameters('city.as[String], 'country.as[String]) { (city, country) =>
completeWith(StatusCodes.OK, ops.getDailyForecast(city, country))
}
} ~
(get & path("forecast")) {
parameters('city.as[String], 'country.as[String]) { (city, country) =>
completeWith(StatusCodes.OK, ops.getExtendedForecast(city, country))
}
}
}
private def completeWith[A: RootJsonWriter](statusCode: StatusCode, op: Future[A]): Route =
extractExecutionContext { implicit ec =>
complete {
op map { (statusCode, _) }
}
}
}
object WeatherMonitorRoutes {
def apply(wmo: WeatherMonitorOps): WeatherMonitorRoutes = new WeatherMonitorRoutes {
override def ops: WeatherMonitorOps = wmo
}
}
示例9: Register
//设置package包名称以及导入依赖的类
package io.orkestra.cluster
import akka.actor.ActorRef
import akka.http.scaladsl.model.{StatusCodes, StatusCode}
import play.api.libs.json.{JsString, Format, Json, JsValue}
package object protocol {
case class Register(member: ActorRef, role: String)
case class RegisterInternal(member: ActorRef, role: String)
sealed trait Response {
def asJson: JsValue
def httpStatusCode: StatusCode
}
object Response {
trait Success extends Response {
override val httpStatusCode: StatusCode = StatusCodes.OK
}
object Success {
case class Router(name: String, routees: List[String]) extends Success {
override val asJson = Json.toJson(this)
}
object Router {
implicit val fmt: Format[Router] = Json.format[Router]
}
case class Routers(routers: Iterable[JsValue]) extends Success {
override val asJson = Json.toJson(routers)
}
case class RouteeDeleted(role: String, path: String) extends Success {
override val asJson = JsString(s"routee: $path with role: $role successfully deleted")
}
}
trait Failure extends Response
object Failure {
case class RouterNotFound(role: String) extends Failure {
override val httpStatusCode: StatusCode = StatusCodes.NotFound
override val asJson: JsValue = Json.obj("error" -> s"router with role: $role not found")
}
}
}
}
示例10: 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)
}
}
示例11: PlayJsonException
//设置package包名称以及导入依赖的类
package com.wavesplatform.http
import scala.util.control.Exception.nonFatalCatch
import scala.util.control.NoStackTrace
import akka.http.scaladsl.marshalling.{Marshaller, PredefinedToEntityMarshallers, ToEntityMarshaller, ToResponseMarshaller}
import akka.http.scaladsl.model.MediaTypes.{`application/json`, `text/plain`}
import akka.http.scaladsl.model.StatusCode
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, PredefinedFromEntityUnmarshallers, Unmarshaller}
import akka.util.ByteString
import play.api.libs.json._
import scorex.api.http.ApiError
import scorex.transaction.{Transaction, ValidationError}
case class PlayJsonException(
cause: Option[Throwable] = None,
errors: Seq[(JsPath, Seq[JsonValidationError])] = Seq.empty) extends IllegalArgumentException with NoStackTrace
trait ApiMarshallers {
type TRM[A] = ToResponseMarshaller[A]
import akka.http.scaladsl.marshalling.PredefinedToResponseMarshallers._
implicit val aem: TRM[ApiError] = fromStatusCodeAndValue[StatusCode, JsValue].compose { ae => ae.code -> ae.json }
implicit val vem: TRM[ValidationError] = aem.compose(ve => ApiError.fromValidationError(ve))
implicit val tw: Writes[Transaction] = Writes(_.json)
private val jsonStringUnmarshaller =
Unmarshaller.byteStringUnmarshaller
.forContentTypes(`application/json`)
.mapWithCharset {
case (ByteString.empty, _) => throw Unmarshaller.NoContentException
case (data, charset) => data.decodeString(charset.nioCharset.name)
}
private lazy val jsonStringMarshaller =
Marshaller.stringMarshaller(`application/json`)
implicit def playJsonUnmarshaller[A](implicit reads: Reads[A]): FromEntityUnmarshaller[A] =
jsonStringUnmarshaller map { data =>
val json = nonFatalCatch.withApply(t => throw PlayJsonException(cause = Some(t)))(Json.parse(data))
json.validate[A] match {
case JsSuccess(value, _) => value
case JsError(errors) => throw PlayJsonException(errors = errors)
}
}
// preserve support for extracting plain strings from requests
implicit val stringUnmarshaller: FromEntityUnmarshaller[String] = PredefinedFromEntityUnmarshallers.stringUnmarshaller
implicit val intUnmarshaller: FromEntityUnmarshaller[Int] = stringUnmarshaller.map(_.toInt)
implicit def playJsonMarshaller[A](
implicit writes: Writes[A],
printer: JsValue => String = Json.prettyPrint): ToEntityMarshaller[A] =
jsonStringMarshaller.compose(printer).compose(writes.writes)
// preserve support for using plain strings as request entities
implicit val stringMarshaller = PredefinedToEntityMarshallers.stringMarshaller(`text/plain`)
}
object ApiMarshallers extends ApiMarshallers
示例12: json
//设置package包名称以及导入依赖的类
package com.wavesplatform.matcher.api
import akka.http.scaladsl.model.{StatusCode, StatusCodes}
import play.api.libs.json.{JsNull, JsValue, Json}
trait MatcherResponse {
def json: JsValue
def code: StatusCode
}
trait GenericMatcherResponse extends MatcherResponse {
def success: Boolean
def message: String
def result: JsValue = JsNull
def json: JsValue = Json.obj(
"success" -> success,
"message" -> message,
"result" -> result
)
def code: StatusCode = if (success) StatusCodes.OK else StatusCodes.BadRequest
}
case class StatusCodeMatcherResponse(override val code: StatusCode, message: String) extends GenericMatcherResponse {
override def success: Boolean = code == StatusCodes.OK
}
case class BadMatcherResponse(override val code: StatusCode, message: String) extends GenericMatcherResponse {
override def success: Boolean = code == StatusCodes.OK
}
示例13: serviceSuccess
//设置package包名称以及导入依赖的类
package com.github.cupenya.auth
import akka.http.scaladsl.model.{ HttpHeader, StatusCode, StatusCodes }
import spray.json.JsonFormat
import scala.concurrent.{ ExecutionContext, Future }
package object service {
def serviceSuccess[T: JsonFormat](t: T): ServiceResponse[T] =
ServiceResponse(success = true, Some(t), None)
def serviceNoSuccess[T: JsonFormat](message: String): ServiceResponse[T] =
ServiceResponse(success = false, None, Some(ServiceResponseError(message, None)))
def serviceUnauthorized[T: JsonFormat](message: String = "No authorization information supplied."): ServiceResponse[T] =
ServiceResponse(success = false, None, Some(ServiceResponseError(message, None)))
implicit def toServiceSuccess[T: JsonFormat](t: T): ServiceResponse[T] = serviceSuccess(t)
def apiComplete[T: JsonFormat](response: Future[ServiceResponse[T]], statusCode: StatusCode)(implicit ec: ExecutionContext): Future[(StatusCode, List[HttpHeader], ServiceResponse[T])] = {
response.map(apiComplete(_, statusCode = statusCode))
}
def apiComplete[T: JsonFormat](apiResponse: ServiceResponse[T], responseHeaders: List[HttpHeader] = Nil, statusCode: StatusCode = StatusCodes.OK): (StatusCode, List[HttpHeader], ServiceResponse[T]) = {
(statusCode.intValue, responseHeaders, apiResponse)
}
}
示例14: getMessage
//设置package包名称以及导入依赖的类
package com.github.chaabaj.openid.exceptions
import akka.http.scaladsl.model.StatusCode
trait GenericWebServiceException[A] extends RuntimeException {
val statusCode: StatusCode
val message: A
override def getMessage: String = s"WebService exception status code: $statusCode message: ${message.toString}"
}
case class WebServiceException[A](statusCode: StatusCode, message: A) extends GenericWebServiceException[A]
case class MalformedResponseException(statusCode: StatusCode, message: String)
extends GenericWebServiceException[String] {
override def getMessage: String = s"WebService exception status code: $statusCode message: ${message.toString}"
}
示例15: AuthenticationException
//设置package包名称以及导入依赖的类
package allawala.chassis.auth.exception
import akka.http.scaladsl.model.{StatusCode, StatusCodes}
import allawala.chassis.core.exception.{DomainException, ErrorType}
case class AuthenticationException (
override val errorCode: String = "authentication.error",
override val message: String = "authentication exception",
override val cause: Throwable = None.orNull,
override val errorMap: Map[String, String] = Map.empty[String, String],
override val logMap: Map[String, AnyRef] = Map.empty[String, AnyRef]
) extends DomainException {
override val errorType: ErrorType = ErrorType.AccessDeniedError
override val statusCode: StatusCode = StatusCodes.Unauthorized
}