本文整理汇总了Scala中akka.http.scaladsl.model.StatusCodes类的典型用法代码示例。如果您正苦于以下问题:Scala StatusCodes类的具体用法?Scala StatusCodes怎么用?Scala StatusCodes使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了StatusCodes类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: AuthServiceRoute
//设置package包名称以及导入依赖的类
package com.noedominguez.class_orchestration.restapi.http.routes
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import com.noedominguez.class_orchestration.restapi.models.UserEntity
import com.noedominguez.class_orchestration.restapi.services.AuthService
import com.noedominguez.class_orchestration.restapi.http.SecurityDirectives
import de.heikoseeberger.akkahttpcirce.CirceSupport
import io.circe.generic.auto._
import io.circe.syntax._
import scala.concurrent.ExecutionContext
class AuthServiceRoute(val authService: AuthService)(implicit executionContext: ExecutionContext) extends CirceSupport with SecurityDirectives {
import StatusCodes._
import authService._
val route = pathPrefix("auth") {
path("signIn") {
pathEndOrSingleSlash {
post {
entity(as[LoginPassword]) { loginPassword =>
complete(signIn(loginPassword.login, loginPassword.password).map(_.asJson))
}
}
}
} ~
path("signUp") {
pathEndOrSingleSlash {
post {
entity(as[UserEntity]) { userEntity =>
complete(Created -> signUp(userEntity).map(_.asJson))
}
}
}
}
}
private case class LoginPassword(login: String, password: String)
}
示例2: healthcheck
//设置package包名称以及导入依赖的类
package de.zalando.elbts
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import scala.concurrent.Future
trait RestAPI {
def healthcheck(): Future[String] = Future.successful("ELBTS is alive")
}
class RestRoutes extends RestAPI {
import StatusCodes._
val healthcheckRoute = pathPrefix("healthcheck") {
pathEndOrSingleSlash {
get {
onSuccess(healthcheck()) { msg =>
complete(OK, msg)
}
}
}
}
}
示例3: UserResource
//设置package包名称以及导入依赖的类
package com.durooma.api.route
import akka.http.scaladsl.model.StatusCodes
import com.durooma.api.route.RouteSystem._
import com.durooma.api.model.{User, UserRegistration}
object UserResource extends CustomDirectives with JsonSupport {
val route = pathPrefix("user") {
pathEnd {
post {
entity(as[UserRegistration]) { user =>
complete(User.create(user).map(_ => StatusCodes.Created))
}
}
} ~
path(LongNumber) { id =>
get {
complete(User.get(id))
}
}
}
}
示例4: SessionResource
//设置package包名称以及导入依赖的类
package com.durooma.api.route
import akka.http.scaladsl.model.StatusCodes
import com.durooma.api.route.RouteSystem._
import com.durooma.api.model.{CustomCredentials, Session}
object SessionResource extends CustomDirectives with JsonSupport {
val route = pathPrefix("session") {
pathEnd {
post {
entity(as[CustomCredentials]) { credentials =>
complete(Session.login(credentials))
}
} ~
get {
authenticateToken { implicit session =>
complete(session)
}
} ~
delete {
authenticateToken { implicit session =>
complete(Session.logout.map(_ => StatusCodes.NoContent))
}
}
}
}
}
示例5: Api
//设置package包名称以及导入依赖的类
package com.durooma.api.route
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.ExceptionHandler
import com.durooma.api.error.AuthenticationError
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException
object Api extends CustomDirectives with JsonSupport {
val genericExceptionHandler = ExceptionHandler {
case AuthenticationError(message) => complete((StatusCodes.Unauthorized, message))
case e: MySQLIntegrityConstraintViolationException => e.getErrorCode match {
case 1062 => complete((StatusCodes.BadRequest, e.getMessage))
}
case e =>
e.printStackTrace()
complete((StatusCodes.InternalServerError, e.getLocalizedMessage))
}
val route = handleExceptions(genericExceptionHandler) {
AccountResource.route ~
TransactionResource.route ~
UserResource.route ~
SessionResource.route
}
}
示例6: SearchApi
//设置package包名称以及导入依赖的类
package au.csiro.data61.magda.api
import akka.event.LoggingAdapter
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.model.{ StatusCodes }
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import au.csiro.data61.magda.model.misc
import au.csiro.data61.magda.model.misc._
import au.csiro.data61.magda.api.{ model => apimodel }
import au.csiro.data61.magda.search.SearchQueryer
import com.typesafe.config.Config
class SearchApi(val searchQueryer: SearchQueryer)(implicit val config: Config, implicit val logger: LoggingAdapter) extends misc.Protocols with BaseMagdaApi with apimodel.Protocols {
override def getLogger = logger
val queryCompiler = new QueryCompiler()
val routes =
magdaRoute {
pathPrefix("v0") {
pathPrefix("facets") {
path(Segment / "options") { facetId ?
(get & parameters("facetQuery" ? "*", "start" ? 0, "limit" ? 10, "generalQuery" ? "*")) { (facetQuery, start, limit, generalQuery) ?
FacetType.fromId(facetId) match {
case Some(facetType) ? complete(searchQueryer.searchFacets(facetType, facetQuery, queryCompiler.apply(generalQuery), start, limit))
case None ? complete(NotFound)
}
}
}
} ~
pathPrefix("datasets") {
(get & parameters("query" ? "*", "start" ? 0, "limit" ? 10, "facetSize" ? 10)) { (rawQuery, start, limit, facetSize) ?
val query = if (rawQuery.equals("")) "*" else rawQuery
onSuccess(searchQueryer.search(queryCompiler.apply(query), start, limit, facetSize)) { result =>
val status = if (result.errorMessage.isDefined) StatusCodes.InternalServerError else StatusCodes.OK
pathPrefix("datasets") {
complete(status, result.copy(facets = None))
} ~ pathPrefix("facets") {
complete(status, result.facets)
} ~ pathEnd {
complete(status, result)
}
}
}
} ~
path("region-types") { get { getFromResource("regionMapping.json") } } ~
path("regions") {
(get & parameters("query" ? "*", "start" ? 0, "limit" ? 10)) { (query, start, limit) ?
complete(searchQueryer.searchRegions(query, start, limit))
}
}
}
}
}
示例7: BaseLineBotSpec
//设置package包名称以及导入依赖的类
package bot.application
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.testkit.ScalatestRouteTest
import bot.line.client.SignatureVerifier
import bot.line.json.EventsJsonSupport
import bot.line.model.event._
import org.scalamock.scalatest.MockFactory
import org.scalatest.{Matchers, _}
class BaseLineBotSpec
extends FlatSpec
with Matchers
with ScalatestRouteTest
with EventsJsonSupport
with MockFactory {
def createBot(
sv: SignatureVerifier = mock[SignatureVerifier],
rv:List[Event] => Unit
): BaseLineBot[Unit] = new BaseLineBot[Unit] {
override val channelSecret: String = "channelSecret"
override val signatureVerifier: SignatureVerifier = sv
override def receive(events: List[Event]): Unit = rv(events)
}
it should "Verify signature" in {
val signatureVerifier = stub[SignatureVerifier]
(signatureVerifier.isValid _).when(*, *, *) returns true
val receive = stubFunction[List[Event], Unit]
receive.when(*).returns(Unit)
val bot = createBot(
signatureVerifier,
receive
)
val event = MessageEvent(
replyToken = "replyToken",
timestamp = 0,
source = UserSource(id = "1"),
message = TextMessage(id = "2", text = "test message")
)
val body = Events(List(event))
val header = RawHeader("X-Line-Signature", "signature")
Post("/line/callback", body).withHeaders(header) ~> bot.routes ~> check {
status shouldBe StatusCodes.OK
responseAs[String] shouldBe "OK"
}
(signatureVerifier.isValid _).verify("channelSecret", *, "signature").once
receive.verify(body.events).once
}
}
示例8: WebServerTest
//设置package包名称以及导入依赖的类
package wow.api
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.{Ignore, Matchers, WordSpec}
import spray.json.DefaultJsonProtocol._
import spray.json.RootJsonFormat
import wow.auth.data.AccountAPI.AccountReq
import wow.utils.Reflection
@Ignore
class WebServerTest extends WordSpec with Matchers with ScalatestRouteTest {
Reflection.eagerLoadClasses()
implicit val userFormat: RootJsonFormat[AccountReq] = jsonFormat2(AccountReq.apply)
"The service" should {
"return a creation success code when an account is create" in {
Post("/account/create", AccountReq("myName", "myPass")) ~> WebServer.route ~> check {
status shouldEqual StatusCodes.Created
}
}
"return a success code when an account is deleted" in {
Post("/account/delete", "myName") ~> WebServer.route ~> check {
status shouldEqual StatusCodes.OK
}
}
"return a success code when a password is reinitialized" in {
Put("/account/reinitialize", AccountReq("myName", "myPass")) ~> WebServer.route ~> check {
status shouldEqual StatusCodes.OK
}
}
}
}
示例9: NoAuthority
//设置package包名称以及导入依赖的类
package co.horn.alkes.auth
import akka.http.scaladsl.model.{HttpResponse, StatusCodes}
import akka.http.scaladsl.server.directives.Credentials
import scala.concurrent.Future
import scala.util.Random
class NoAuthority extends Authority {
lazy val anonymous = new Random(1337L)
def ping: Future[HttpResponse] = Future.successful(HttpResponse(StatusCodes.OK))
def channelAccess(credentials: Credentials, channel_uuid: String): Future[Option[Long]] = {
Future.successful(Some(anonymous.nextLong))
}
def overlordAccess(credentials: Credentials): Future[Option[Long]] = {
Future.successful(Some(anonymous.nextLong))
}
}
示例10: BucketListTest
//设置package包名称以及导入依赖的类
package examples
import akka.http.scaladsl.model.StatusCodes
import edu.goldlok.minio_scala.s3v4.BucketStatus
import org.scalatest.{FlatSpec, Matchers}
import scala.concurrent.Await
class BucketListTest extends FlatSpec with Matchers {
import examples.MioSystem._
private def listBucketTest() = {
val response = mc.listBuckets()
val result = Await.result(response, timeout)
result.status should be (StatusCodes.OK)
}
private def bucketExistsTest() = {
val foundRes = Await.result(mc.bucketExists(bucket), timeout)
foundRes should be (BucketStatus.Existed)
val notfoundRes = Await.result(mc.bucketExists(notfoundBucket), timeout)
notfoundRes should be (BucketStatus.NotFound)
}
"list bucket " should "return" in {
listBucketTest()
bucketExistsTest()
}
}
示例11: FileUploadStream
//设置package包名称以及导入依赖的类
package com.shashank.akkahttp.basic.routing
import akka.http.scaladsl.model.{ContentTypes, HttpEntity, Multipart, StatusCodes}
import akka.http.scaladsl.server.Directives._
import akka.stream.scaladsl.Framing
import akka.util.ByteString
import scala.concurrent.Future
object FileUploadStream extends BaseSpec{
def main(args: Array[String]) {
val route =
extractRequestContext { ctx =>
implicit val materializer = ctx.materializer
implicit val ec = ctx.executionContext
fileUpload("csv") {
case (metadata, byteSource) =>
val sumF: Future[Int] =
// sum the numbers as they arrive so that we can
byteSource.via(Framing.delimiter(ByteString("\n"), 1024))
.mapConcat(_.utf8String.split(",").toVector)
.map(_.toInt)
.runFold(0) { (acc, n) => acc + n }
onSuccess(sumF) { sum => complete(s"Sum: $sum") }
}
}
//Test file upload stream
val multipartForm =
Multipart.FormData(Multipart.FormData.BodyPart.Strict(
"csv",
HttpEntity(ContentTypes.`text/plain(UTF-8)`, "2,3,5\n7,11,13,17,23\n29,31,37\n"),
Map("filename" -> "primes.csv")))
Post("/", multipartForm) ~> route ~> check {
status shouldEqual StatusCodes.OK
responseAs[String] shouldEqual "Sum: 178"
}
system.terminate()
}
}
//File upload direct
//curl --form "[email protected]" http://<host>:<port>
示例12: Rejection
//设置package包名称以及导入依赖的类
package com.shashank.akkahttp.basic.routing
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpResponse, StatusCodes}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import akka.stream.{ActorMaterializer, Materializer}
object Rejection {
def main(args: Array[String]) {
implicit val sys = ActorSystem("IntroductionToAkkaHttp")
implicit val mat:Materializer = ActorMaterializer()
implicit def myRejectionHandler = RejectionHandler.newBuilder().handle{
case MissingCookieRejection(cookieName) =>
complete(HttpResponse(StatusCodes.BadRequest, entity = "No cookies, no service!!!"))
}.handleNotFound {
complete((StatusCodes.NotFound, "Not here!"))
}.result()
val route =
path("welcome"){
get{
complete {
"welcome to rest service"
}
}
} ~
path("demo"){
get{
complete {
"welcome to demonstration"
}
}
} ~
path("wrong"){
reject{
ValidationRejection("Invalid path", None)
}
}
Http().bindAndHandle(route, "localhost", 8090)
}
}
示例13: myRoute
//设置package包名称以及导入依赖的类
package com.zhranklin.homepage
import akka.actor.ActorSystem
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server._
import akka.stream.ActorMaterializer
trait RouteService extends MyHttpService {
def myRoute: Route
}
trait BaseRoute extends RouteService {
def myRoute = getFromResourceDirectory("")
}
object ActorImplicits {
implicit val system = ActorSystem("on-spray-can")
implicit val materializer = ActorMaterializer()
implicit val executionContext = system.dispatcher
}
trait MyRouteService extends BaseRoute with react.ReactRoute
with blog.BlogRoute with solr.SolrRoute with notice.NoticeRoute
with imhere.IMhereRoute with im.ImRoute
with ExceptionHandlerRoute
trait ExceptionHandlerRoute extends RouteService {
abstract override def myRoute = handleExceptions {
ExceptionHandler {
case e: Exception ?
e.printStackTrace()
complete((StatusCodes.InternalServerError, "Unhandled server error."))
}
} {
super.myRoute
}
}
示例14: NewsletterService
//设置package包名称以及导入依赖的类
package com.tpalanga.account.service
import akka.actor.{Actor, ActorLogging, Props, Status}
import akka.http.scaladsl.model.StatusCodes
import com.tpalanga.account.model.{User, UserId}
import com.tpalanga.testlib.test.client.impl.NewsletterServiceRestClient.NewsletterServiceRestClientFactory
import com.tpalanga.testlib.test.client.impl.{NewsletterServiceRestClient, Subscriber}
import com.tpalanga.testlib.test.client.{NoEntity, Response}
import com.tpalanga.testlib.test.config.RestServiceConfig
object NewsletterService {
case class Subscribe(user: User)
case class Unsubscribe(id: UserId)
case class CreateResponse(response: Response[Subscriber])
case class DeleteResponse(response: Response[NoEntity])
def props(restServiceConfig: RestServiceConfig, clientFactory: NewsletterServiceRestClientFactory = NewsletterServiceRestClient.defaultFactory): Props =
Props(new NewsletterService(restServiceConfig, clientFactory))
}
class NewsletterService(restServiceConfig: RestServiceConfig, clientFactory: NewsletterServiceRestClientFactory) extends Actor with ActorLogging {
import NewsletterService._
import akka.pattern.pipe
import context.dispatcher
override def receive: Receive = {
case Subscribe(user) =>
newClient().subscriberCreate(Subscriber(user.id, user.name, user.email)).map(CreateResponse) pipeTo self
case Unsubscribe(userId) =>
newClient().subscriberDelete(userId).map(DeleteResponse) pipeTo self
case CreateResponse(response) if response.status == StatusCodes.Created =>
log.info("Subscribed to newsletter")
case CreateResponse(response) =>
log.info(s"Unexpected response while subscribing to newsletter $response")
case DeleteResponse(response) if response.status == StatusCodes.OK =>
log.info("Unsubscribed from newsletter")
case DeleteResponse(response) =>
log.info("Unsubscribed from newsletter")
case Status.Failure(th) =>
log.error(th, "Error on newsletter request")
}
private def newClient() = clientFactory(restServiceConfig, context.system)
}
示例15: PingRouteSpec
//设置package包名称以及导入依赖的类
package com.tpalanga.account.route
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.concurrent.Eventually
import org.scalatest.{FlatSpec, Matchers}
object PingRouteSpec {
trait Test {
val pingRoute = new PingRoute
}
}
class PingRouteSpec extends FlatSpec with ScalatestRouteTest with Matchers with Eventually {
import PingRouteSpec._
"PingRoute" should "respond to GET" in new Test {
Get("/ping") ~> pingRoute.route ~> check {
eventually {
status shouldBe StatusCodes.OK
}
responseAs[String] shouldBe "<h1>pong</h1>"
}
}
}