• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala StatusCodes类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

} 
开发者ID:poguez,项目名称:class_orchestration_api,代码行数:42,代码来源:AuthServiceRoute.scala


示例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)
        }
      }
    }
  }
} 
开发者ID:psycho-ir,项目名称:elbts,代码行数:27,代码来源:RestAPI.scala


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

} 
开发者ID:durooma,项目名称:api,代码行数:25,代码来源:UserResource.scala


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

} 
开发者ID:durooma,项目名称:api,代码行数:30,代码来源:SessionResource.scala


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

} 
开发者ID:durooma,项目名称:api,代码行数:29,代码来源:Api.scala


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


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

} 
开发者ID:xoyo24,项目名称:akka-http-line-bot,代码行数:56,代码来源:BaseLineBotSpec.scala


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


示例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))
  }
} 
开发者ID:DalenWBrauner,项目名称:Alkes-Prototype,代码行数:22,代码来源:NoAuthority.scala


示例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()
  }
} 
开发者ID:TopSpoofer,项目名称:minio-scala,代码行数:33,代码来源:BucketListTest.scala


示例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> 
开发者ID:shashankgowdal,项目名称:introduction-to-akkahttp,代码行数:51,代码来源:FileUploadStream.scala


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

  }

} 
开发者ID:shashankgowdal,项目名称:introduction-to-akkahttp,代码行数:51,代码来源:Rejection.scala


示例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
  }
} 
开发者ID:zhranklin,项目名称:Private_Blog,代码行数:40,代码来源:RouteService.scala


示例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)
} 
开发者ID:tpalanga,项目名称:akka-http-microservice,代码行数:52,代码来源:NewsletterService.scala


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

} 
开发者ID:tpalanga,项目名称:akka-http-microservice,代码行数:27,代码来源:PingRouteSpec.scala


示例16: CreateCheckingsAccountResponse

//设置package包名称以及导入依赖的类
package com.franklevering.ports.adapters.http.request.handlers

import java.util.UUID

import akka.actor.SupervisorStrategy._
import akka.actor.{OneForOneStrategy, Props}
import akka.http.scaladsl.model.StatusCodes
import com.franklevering.banking.domain.model.account.Account
import com.franklevering.banking.domain.model.account.CreateCheckingsAccount
import com.franklevering.ports.adapters.http.ImperativeRequestContext
import com.franklevering.ports.adapters.http.request.Request

import scala.concurrent.duration._

case class CreateCheckingsAccountResponse(id: String)

class AccountRequestHandler(ctx: ImperativeRequestContext) extends Request(ctx) {

  override val supervisorStrategy =
    OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) {
      case _: ArithmeticException      => Resume
      case _: NullPointerException     => Restart
      case _: IllegalArgumentException => Stop
      case _: Exception                => Escalate
    }

  def receive: Receive = {
    case createCheckingsAccount: CreateCheckingsAccount =>
      val account = context.actorOf(Props(classOf[Account], UUID.randomUUID()))
      account ! createCheckingsAccount
    case createCheckingsAccountResponse: CreateCheckingsAccountResponse =>
      ctx.complete(StatusCodes.Created, createCheckingsAccountResponse)
      context.stop(self)
  }
} 
开发者ID:frankieleef,项目名称:banking,代码行数:36,代码来源:AccountRequestHandler.scala


示例17: JsonRoutes

//设置package包名称以及导入依赖的类
package routes

import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import scala.concurrent.Future
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import models.Item
import repositories.ItemRepository
import spray.json.DefaultJsonProtocol._

import scala.concurrent.ExecutionContext

class JsonRoutes()(implicit ec: ExecutionContext) {

  val itemRepository: ItemRepository = new ItemRepository()
  implicit val itemFormat = jsonFormat2(models.Item)

  def routes = get {
    path(LongNumber) { id =>
      val maybeItem: Future[Option[Item]] = itemRepository.fetchItem(id)

      onSuccess(maybeItem) {
        case Some(item) => complete(item)
        case None => complete(StatusCodes.NotFound)
      }
    }
  }

} 
开发者ID:Giovannini,项目名称:hackday-akka-vue,代码行数:31,代码来源:Json.scala


示例18: AkkaService

//设置package包名称以及导入依赖的类
package uk.me.arseni

import akka.actor.{ActorSystem}
import akka.http.scaladsl.model.{StatusCodes}
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import uk.me.arseni.search.SearchIndex
import spray.json._
import DefaultJsonProtocol._
import scala.io.StdIn


object AkkaService extends App {
  implicit val actorSystem = ActorSystem("akka-system")
  implicit val flowMaterializer = ActorMaterializer()

  val interface = "localhost"
  val port = 8080

  val index = new SearchIndex(args(0))

  import Directives._

  val routes =
    logRequestResult("akka-http-microservice") {
      pathEndOrSingleSlash {
        get {
          // complete(HttpResponse(
          //  = io.Source.fromInputStream(getClass.getResourceAsStream("/static/search_form.html")).mkString))
          getFromResource("static/search_form.html")
        } ~
        head {
          complete(StatusCodes.OK)
        }
      } ~
      path("search") {
        post {
          formFields('query) { query =>
            complete(s"${index.processQuery(query).map(_._1).toJson}")
          }
        }
      }
    }
  val binding = Http().bindAndHandle(routes, interface, port)
  println(s"Server is now online at http://$interface:$port\nPress RETURN to stop...")
  StdIn.readLine()

  import actorSystem.dispatcher

  binding.flatMap(_.unbind()).onComplete(_ => actorSystem.shutdown())
  println("Server is down...")
} 
开发者ID:yarrseni,项目名称:scala_search_engine,代码行数:54,代码来源:AkkaService.scala


示例19: TopicsAPIRoute

//设置package包名称以及导入依赖的类
package net.kemuridama.kafcon.route

import akka.http.scaladsl.model.StatusCodes

import net.kemuridama.kafcon.model.{APIResponse, CreateTopicRequest}
import net.kemuridama.kafcon.protocol.{TopicJsonProtocol, CreateTopicRequestJsonProtocol}
import net.kemuridama.kafcon.service.{UsesTopicService, MixinTopicService}

trait TopicsAPIRoute
  extends APIRoute
  with UsesTopicService
  with TopicJsonProtocol
  with CreateTopicRequestJsonProtocol {

  val route = pathPrefix("clusters" / IntNumber / "topics") { clusterId =>
    pathEnd {
      get {
        onSuccess(topicService.findAll(clusterId)) { response =>
          complete(APIResponse(Some(response)))
        }
      } ~
      post {
        entity(as[CreateTopicRequest]) { request =>
          onSuccess(topicService.create(clusterId, request.name, request.replicationFactor, request.partitionCount)) { response =>
            complete(StatusCodes.Created, APIResponse(Some(response)))
          }
        }
      }
    } ~
    pathPrefix(Segment) { name =>
      pathEnd {
        get {
          onSuccess(topicService.find(clusterId, name)) {
            case Some(response) => complete(APIResponse(Some(response)))
            case _ => complete(StatusCodes.NotFound, errorMessage("Not found"))
          }
        }
      }
    }
  }

}

private[route] object TopicsAPIRoute
  extends TopicsAPIRoute
  with MixinTopicService

trait UsesTopicsAPIRoute {
  val topicsAPIRoute: TopicsAPIRoute
}

trait MixinTopicsAPIRoute {
  val topicsAPIRoute = TopicsAPIRoute
} 
开发者ID:kemuridama,项目名称:kafcon,代码行数:55,代码来源:TopicsAPIRoute.scala


示例20: BrokersAPIRoute

//设置package包名称以及导入依赖的类
package net.kemuridama.kafcon.route

import akka.http.scaladsl.model.StatusCodes

import net.kemuridama.kafcon.model.APIResponse
import net.kemuridama.kafcon.service.{UsesBrokerService, MixinBrokerService}
import net.kemuridama.kafcon.protocol.BrokerJsonProtocol

trait BrokersAPIRoute
  extends APIRoute
  with UsesBrokerService
  with BrokerJsonProtocol {

  val route = pathPrefix("clusters" / IntNumber / "brokers") { clusterId =>
    pathEnd {
      get {
        onSuccess(brokerService.findAll(clusterId)) { response =>
          complete(APIResponse(Some(response)))
        }
      }
    } ~
    pathPrefix(IntNumber) { id =>
      pathEnd {
        get {
          onSuccess(brokerService.find(clusterId, id)) {
            case Some(response) => complete(APIResponse(Some(response)))
            case _ => complete(StatusCodes.NotFound, errorMessage("Not found"))
          }
        }
      }
    }
  }

}

private[route] object BrokersAPIRoute
  extends BrokersAPIRoute
  with MixinBrokerService

trait UsesBrokersAPIRoute {
  val brokersAPIRoute: BrokersAPIRoute
}

trait MixinBrokersAPIRoute {
  val brokersAPIRoute = BrokersAPIRoute
} 
开发者ID:kemuridama,项目名称:kafcon,代码行数:47,代码来源:BrokersAPIRoute.scala



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Vector类代码示例发布时间:2022-05-23
下一篇:
Scala Elem类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap