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

Scala Directives类代码示例

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

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



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

示例1: extractBearerToken

//设置package包名称以及导入依赖的类
package com.github.cupenya.microservices.sdk.authentication

import akka.http.scaladsl.model.headers.{Authorization, OAuth2BearerToken}
import akka.http.scaladsl.server.{AuthorizationFailedRejection, Directive1, Directives}
import com.github.cupenya.microservices.sdk.logging.Logging

import scala.concurrent.ExecutionContext

trait AuthorizationDirectives extends Logging {
  self: Directives =>

  implicit val ec: ExecutionContext

  // TODO: dep injection
  private val tokenVerifier = new JwtTokenVerifier

  private def extractBearerToken(authHeader: Option[Authorization]): Option[String] =
    authHeader.collect {
      case Authorization(OAuth2BearerToken(token)) => token
    }

  def authorized: Directive1[AuthInfo] = {
    optionalHeaderValueByType(classOf[Authorization]).map(extractBearerToken).flatMap {
      case Some(token) =>
        onComplete(tokenVerifier.verifyToken(token)).flatMap { x =>
          x.map(authInfo => provide(authInfo))
            .recover {
              case ex =>
                log.error("Couldn't log in using provided authorization token", ex)
                reject(AuthorizationFailedRejection).toDirective[Tuple1[AuthInfo]]
            }
            .get
        }
      case None =>
        reject(AuthorizationFailedRejection)
    }
  }
} 
开发者ID:cupenya,项目名称:microservices-sdk,代码行数:39,代码来源:AuthorizationDirectives.scala


示例2: UsersRoute

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

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.{Directives, Route}
import core.db.users.UsersDao
import core.entities.UserInformationEntityConverters._
import restapi.http.JsonSupport
import restapi.http.routes.support.SecuredAccessSupport

import scala.concurrent.ExecutionContext
import scala.util.Try

class UsersRoute(usersDao: UsersDao)(implicit ec: ExecutionContext, ac: ApiContext)
    extends Directives with SecuredAccessSupport with JsonSupport {

  val route: Route =
    pathPrefix("users") {
      securedAccess { ctx =>
        pathEndOrSingleSlash {
          get {
            complete(usersDao.findUsers().map(toUserInformationEntity))
          }
        } ~
          path("name" / Segment) { name =>
            get {
              complete {
                val maybeUser = usersDao.findUserByName(name)
                maybeUser match {
                  case Some(user) => toUserInformationEntity(user)
                  case None       => StatusCodes.NotFound
                }
              }
            } ~
              delete {
                privateResourceAccess(ctx, name) {
                  complete {
                    Try(usersDao.deleteUser(ctx.userId))
                    StatusCodes.OK
                  }
                }
              }
          }
      }
    }

} 
开发者ID:lymr,项目名称:fun-chat,代码行数:47,代码来源:UsersRoute.scala


示例3: executionContext

//设置package包名称以及导入依赖的类
package onextent.oemap.server.http

import akka.http.scaladsl.marshalling.{ToResponseMarshallable, ToResponseMarshaller}
import akka.http.scaladsl.model.headers.Location
import akka.http.scaladsl.server.{Directives, Route}

import scala.concurrent.{ExecutionContext, Future}

trait JsonResource extends Directives with JsonSupport {

  val notFoundCode = 404
  val successCode = 204

  implicit def executionContext: ExecutionContext

  def completeWithLocationHeader[T](resourceId: Future[Option[T]], ifDefinedStatus: Int, ifEmptyStatus: Int): Route =
    onSuccess(resourceId) {
      case Some(t) => completeWithLocationHeader(ifDefinedStatus, t)
      case None => complete(ifEmptyStatus, None)
    }

  def completeWithLocationHeader[T](status: Int, resourceId: T): Route =
    extractRequestContext { requestContext =>
      val request = requestContext.request
      val location = request.uri.copy(path = request.uri.path / resourceId.toString)
      respondWithHeader(Location(location)) {
        complete(status, None)
      }
    }

  def complete[T: ToResponseMarshaller](resource: Future[Option[T]]): Route =
    onSuccess(resource) {
      case Some(t) => complete(ToResponseMarshallable(t))
      case None => complete(notFoundCode, None)
    }

  def complete(resource: Future[Unit]): Route = onSuccess(resource) { complete(successCode, None) }

} 
开发者ID:navicore,项目名称:oemap-server,代码行数:40,代码来源:JsonResource.scala


示例4: Hello

//设置package包名称以及导入依赖的类
package com.github.cupenya.hello

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.server.{ AuthorizationFailedRejection, Directives, RejectionHandler }
import akka.http.scaladsl.model.StatusCodes._
import com.github.cupenya.hello.authentication.AuthorizationDirectives
import spray.json._

import scala.concurrent.ExecutionContext

case class Hello(message: String)

case class AuthError(error: String)

trait Protocols extends DefaultJsonProtocol {
  implicit val helloFormat = jsonFormat1(Hello)
}

trait HelloHttpService extends Directives with AuthorizationDirectives with SprayJsonSupport with Protocols with Logging {
  implicit val ec: ExecutionContext

  implicit val authErrorFormat = jsonFormat1(AuthError)

  private val rh = RejectionHandler.newBuilder().handle {
    case AuthorizationFailedRejection =>
      complete(Forbidden -> AuthError("The supplied authentication is not authorized to access this resource"))
  }.result()

  val helloRoute = handleRejections(rh) {
    authorized { authInfo =>
      pathPrefix("hello") {
        get {
          complete(Hello(s"hello ${authInfo.userId}"))
        }
      }
    }
  }
} 
开发者ID:cupenya,项目名称:hello-world-microservice,代码行数:39,代码来源:HelloHttpService.scala


示例5: HealthCheckModel

//设置package包名称以及导入依赖的类
package com.github.cupenya.hello

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.model.StatusCodes._
import spray.json.DefaultJsonProtocol

sealed trait HealthCheckModel

object HealthCheckModel extends DefaultJsonProtocol {
  implicit val healthCheckResultFormat = jsonFormat2(HealthCheckResult)
}

case class HealthCheckResult(name: String, status: String) extends HealthCheckModel

trait HealthHttpService extends Directives with SprayJsonSupport with Protocols with Logging {
  val healthRoute =
    pathPrefix("health") {
      get {
        complete(OK -> Map(
          "services" -> List(
            HealthCheckResult("service1", "ok")
          )
        ))
      }
    }
} 
开发者ID:cupenya,项目名称:hello-world-microservice,代码行数:28,代码来源:HealthHttpService.scala


示例6: AuthError

//设置package包名称以及导入依赖的类
package com.github.cupenya.microservices.sdk

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.{AuthorizationFailedRejection, Directives, RejectionHandler}
import com.github.cupenya.microservices.sdk.authentication.AuthorizationDirectives
import com.github.cupenya.microservices.sdk.logging.Logging
import spray.json._

import scala.concurrent.ExecutionContext

case class AuthError(error: String)

trait SampleHttpService extends Directives with AuthorizationDirectives with SprayJsonSupport with DefaultJsonProtocol with Logging {
  implicit val ec: ExecutionContext

  implicit val authErrorFormat = jsonFormat1(AuthError)

  private val rh = RejectionHandler.newBuilder().handle {
    case AuthorizationFailedRejection =>
      complete(Forbidden -> AuthError("The supplied authentication is not authorized to access this resource"))
  }.result()

  val routes = handleRejections(rh) {
    authorized { authInfo =>
      pathPrefix("test") {
        get {
          complete(OK, None)
        }
      }
    }
  }
} 
开发者ID:cupenya,项目名称:microservices-sdk,代码行数:34,代码来源:SampleHttpService.scala


示例7: ReservationRoute

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

import akka.http.scaladsl.server.{ Directives, Route }
import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport
import handlers.OAuth2DataHandler
import http.auth.OAuth2RouteProvider
import io.circe.generic.auto._
import io.circe.syntax._
import models.{ Account, ReservationCreate }
import services.{ CachingService, ReservationService }
import akka.http.scaladsl.model.StatusCodes._

import scala.concurrent.ExecutionContext
import scalaoauth2.provider.AuthInfo

class ReservationRoute(
  override val oauth2DataHandler: OAuth2DataHandler,
  reservationService: ReservationService,
  cachingService: CachingService
)(implicit executionContext: ExecutionContext)
    extends Directives
    with OAuth2RouteProvider[Account]
    with FailFastCirceSupport {

  import reservationService._

  val route: Route = pathPrefix("reservation") {
    pathEndOrSingleSlash {
      post {
        authenticateOAuth2Async[AuthInfo[Account]]("realm", oauth2Authenticator) {
          _ =>
            entity(as[ReservationCreate]) { reservation =>
              onSuccess(makeReservation(reservation)) {
                result =>
                  {
                    if (result.success) {
                      complete(result.message)
                    } else {
                      complete(BadRequest, result.message)
                    }
                  }
              }
            }
        }
      } ~ parameters('imdbId.as[String], 'screenId.as[String]) { (imdbId, screenId) =>
        {
          authenticateOAuth2Async[AuthInfo[Account]]("realm", oauth2Authenticator) {
            _ =>
              onSuccess(getReservationDetail(imdbId, screenId)) {
                case Some(detail) => complete(detail.asJson)
                case None => complete(BadRequest)
              }

          }
        }
      }
    }
  }
} 
开发者ID:ziyasal,项目名称:Reserveon,代码行数:60,代码来源:ReservationRoute.scala


示例8: System

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

import akka.actor.ActorSystem
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import akka.http.scaladsl.server.Directives

object System {
  implicit val system = ActorSystem()
  implicit val materializer = ActorMaterializer()

  trait LoggerExecutor extends BaseComponent {
    protected implicit val executor = system.dispatcher
    protected implicit val log = Logging(system, "app")
  }
}

object Main extends App with Config with System.LoggerExecutor with StatusService {
  import System._
  import Directives._

  Http().bindAndHandle(statusRoutes, httpConfig.interface, httpConfig.port)
} 
开发者ID:beritou,项目名称:mfp-akka,代码行数:25,代码来源:Main.scala


示例9: ec

//设置package包名称以及导入依赖的类
package scaladays.akka.http

import akka.http.scaladsl.marshallers.sprayjson.ExtendedSprayJsonSupport
import akka.http.scaladsl.model.ws
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.server.directives.FramedEntityStreamingDirectives
import akka.stream.Materializer
import akka.stream.scaladsl.{Flow, Sink}

import scala.concurrent.ExecutionContext
import scaladays.akka.kafka.KafkaTopics

trait Step3WebsocketRoutes extends Directives with FramedEntityStreamingDirectives
  with ExtendedSprayJsonSupport with MyJsonProtocol {
  implicit def ec: ExecutionContext
  implicit def materializer: Materializer
  def kafkaTopics: KafkaTopics

  lazy val namesFromKafka = 
      kafkaTopics.namesSource.map { comittable =>
        comittable.committableOffset.commitScaladsl()
        comittable.value
      }

  lazy val namesAsWebSocketMessages =
    namesFromKafka.map(ws.TextMessage(_))
  
  def step3WsRoutes =
    path("step3" / "ws") {
      val source = Flow.fromSinkAndSource(Sink.ignore, namesAsWebSocketMessages)
      handleWebSocketMessages(source)
    }
  
} 
开发者ID:ktoso,项目名称:scaladays-berlin-akka-streams,代码行数:35,代码来源:Step3WebsocketRoutes.scala


示例10: AppReturningChunking

//设置package包名称以及导入依赖的类
package com.github.michalbogacz.http.streaming

import akka.NotUsed
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.Directives
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source
import akka.util.ByteString
import com.mongodb.reactivestreams.client.{MongoClients, MongoCollection}
import org.bson.Document

import scala.concurrent.ExecutionContextExecutor
import scala.io.StdIn

object AppReturningChunking extends Directives {
  
  implicit val system = ActorSystem()
  implicit val dispatcher: ExecutionContextExecutor = system.dispatcher
  implicit val mat = ActorMaterializer()

  def main(args: Array[String]): Unit = {
    val mongoClient = MongoClients.create()
    val coll = mongoClient.getDatabase("test").getCollection("resources")

    val route =
      path("resources") {
        get {
          complete(HttpEntity(ContentTypes.`application/json`, getData(coll)))
        }
      }

    val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)

    println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
    StdIn.readLine() // let it run until user presses return
    bindingFuture
      .flatMap(_.unbind()) // trigger unbinding from the port
      .onComplete(_ => system.terminate()) // and shutdown when done

  }

  def getData(coll: MongoCollection[Document]): Source[ByteString, NotUsed] =
    Source.fromPublisher(coll.find())
      .map(_.toJson)
      .map(ByteString(_))
      .intersperse(ByteString("["), ByteString(","), ByteString("]"))

} 
开发者ID:michalbogacz,项目名称:http-streaming,代码行数:51,代码来源:AppReturningChunking.scala


示例11: 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


示例12: StoriesResource

//设置package包名称以及导入依赖的类
package com.benoj.janus.resources

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.{Directives, Route}
import akka.stream.Materializer

import scala.concurrent.ExecutionContext

object StoriesResource extends Directives {
  def route(projectId: String)(implicit mat: Materializer, ec: ExecutionContext): Route = pathPrefix("stories") {
    pathEnd {
      complete(StatusCodes.NotImplemented)
    } ~
      pathPrefix(Segment) { storyId =>
        pathEnd {
          complete(StatusCodes.NotImplemented)
        } ~ TaskResource.route(projectId, storyId)
      }
  }
} 
开发者ID:benoj,项目名称:janus,代码行数:21,代码来源:StoriesResource.scala


示例13: TaskResource

//设置package包名称以及导入依赖的类
package com.benoj.janus.resources

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.{Directives, Route}
import akka.stream.Materializer

import scala.concurrent.ExecutionContext

object TaskResource extends Directives {
  def route(projectId: String, storyId: String)(implicit mat: Materializer, ec: ExecutionContext): Route = pathPrefix("tasks") {
    pathEnd {
      complete(StatusCodes.NotImplemented)
    } ~
      pathPrefix(Segment) { taskId =>
        pathEnd {
          complete(StatusCodes.NotImplemented)
        }
      }
  }
} 
开发者ID:benoj,项目名称:janus,代码行数:21,代码来源:TaskResource.scala


示例14: aultCORSHeaders

//设置package包名称以及导入依赖的类
package com.github.cupenya.authorization.server

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.server.Directives

import scala.concurrent.duration._

trait CorsRoute extends Directives with CorsDirectives with SprayJsonSupport {
  val corsRoute =
    defaultCORSHeaders {
      options {
        complete(StatusCodes.OK -> None)
      }
    }
}

trait CorsDirectives { this: Directives =>
  private def ALLOWED_HEADERS = Seq(
    "Origin",
    "X-Requested-With",
    "Content-Type",
    "Accept",
    "Accept-Encoding",
    "Accept-Language",
    "Host",
    "Referer",
    "User-Agent",
    "Overwrite",
    "Destination",
    "Depth",
    "X-Token",
    "X-File-Size",
    "If-Modified-Since",
    "X-File-Name",
    "Cache-Control",
    "x-api-key",
    "x-auth-cupenya",
    "x-api-version",
    "x-cpy-trace-token"
  )

  def defaultCORSHeaders = respondWithHeaders(
    `Access-Control-Allow-Origin`.*,
    `Access-Control-Allow-Methods`(GET, POST, OPTIONS, DELETE,
      CONNECT, DELETE, HEAD, PATCH, PUT, TRACE),
    `Access-Control-Allow-Headers`(ALLOWED_HEADERS.mkString(", ")),
    `Access-Control-Allow-Credentials`(allow = true),
    `Access-Control-Max-Age`(1.hour.toSeconds)
  )
} 
开发者ID:cupenya,项目名称:authorization,代码行数:54,代码来源:CorsDirectives.scala


示例15: AdminExceptionHandler

//设置package包名称以及导入依赖的类
package csw.apps.clusterseed.admin.http

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.{Directives, ExceptionHandler}
import csw.apps.clusterseed.admin.exceptions.UnresolvedAkkaLocationException
import csw.apps.clusterseed.commons.ClusterSeedLogger

import scala.util.control.NonFatal


class AdminExceptionHandler extends Directives with ClusterSeedLogger.Simple {

  val exceptionHandler: ExceptionHandler = ExceptionHandler {
    case ex: UnresolvedAkkaLocationException ?
      log.error(ex.getMessage, ex = ex)
      complete(StatusCodes.NotFound ? ex.getMessage)
    case NonFatal(ex) ?
      log.error(ex.getMessage, ex = ex)
      complete(StatusCodes.InternalServerError ? ex.getMessage)
  }
} 
开发者ID:tmtsoftware,项目名称:csw-prod,代码行数:22,代码来源:AdminExceptionHandler.scala


示例16: ConfigExceptionHandler

//设置package包名称以及导入依赖的类
package csw.services.config.server.http

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.{Directives, ExceptionHandler}
import csw.services.config.api.exceptions.{FileAlreadyExists, FileNotFound, InvalidInput}
import csw.services.config.server.commons.ConfigServerLogger

import scala.util.control.NonFatal


class ConfigExceptionHandler extends Directives with ConfigServerLogger.Simple {

  val exceptionHandler: ExceptionHandler = ExceptionHandler {
    case ex: FileAlreadyExists ?
      log.error(ex.getMessage, ex = ex)
      complete(StatusCodes.Conflict ? ex.getMessage)
    case ex: FileNotFound ?
      log.error(ex.getMessage, ex = ex)
      complete(StatusCodes.NotFound ? ex.getMessage)
    case ex: InvalidInput ?
      log.error(ex.getMessage, ex = ex)
      complete(StatusCodes.BadRequest ? ex.getMessage)
    case NonFatal(ex) ?
      log.error(ex.getMessage, ex = ex)
      complete(StatusCodes.InternalServerError ? ex.getMessage)
  }
} 
开发者ID:tmtsoftware,项目名称:csw-prod,代码行数:28,代码来源:ConfigExceptionHandler.scala


示例17: HttpRouter

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

import akka.actor.ActorRef
import akka.http.scaladsl.server.{Directives, Route}
import core.authentication.AuthenticationService
import core.db.DatabaseContext
import core.entities.{AuthToken, AuthTokenContext, User}
import restapi.http.JsonSupport
import restapi.http.routes.support.CorsSupport
import utils.Configuration
import websocket.WebSocketHandler

import scala.concurrent.ExecutionContext

class HttpRouter(dbc: DatabaseContext,
                 authService: AuthenticationService,
                 webSocketHandler: WebSocketHandler,
                 processingRouter: ActorRef,
                 configuration: Configuration)(implicit apiDispatcher: ExecutionContext)
    extends Directives with JsonSupport with CorsSupport {

  private implicit val ac = new ApiContext(authService.authorize, dbc.usersDao.findUserByName)

  private val userRoute = new UsersRoute(dbc.usersDao)
  private val authRoute = new AuthenticationRoute(authService)
  private val messagesRoute = new MessagesRoute(processingRouter, webSocketHandler, configuration.messageTimeout)

  val routes: Route = pathPrefix("v1") {
    AccessControlCheck {
      authRoute.route ~
        userRoute.route ~
        messagesRoute.route
    }
  }
}

class ApiContext(val authenticate: AuthToken => Option[AuthTokenContext],
                 val findUserByName: String => Option[User]) 
开发者ID:lymr,项目名称:fun-chat,代码行数:39,代码来源:HttpRouter.scala


示例18: AuthenticationRoute

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

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.headers.BasicHttpCredentials
import akka.http.scaladsl.server.{Directives, Route}
import core.authentication.AuthenticationService
import core.entities.UserSecret
import restapi.http.JsonSupport
import restapi.http.routes.support._

import scala.concurrent.{ExecutionContext, Future}

class AuthenticationRoute(authService: AuthenticationService)(implicit ec: ExecutionContext, ac: ApiContext)
    extends Directives with SecuredAccessSupport with ContentExtractionSupport with JsonSupport {

  val route: Route =
    pathPrefix("auth") {
      path("signIn") {
        post {
          extractClientInfo { clientInfo =>
            extractCredentials {
              case Some(BasicHttpCredentials(username, password)) =>
                complete(Future(authService.signIn(username, UserSecret(password))))
              case _ => complete(StatusCodes.Unauthorized)
            }
          }
        }
      } ~
        path("signUp") {
          post {
            extractClientInfo { clientInfo =>
              extractCredentials {
                case Some(BasicHttpCredentials(username, password)) =>
                  complete(Future(authService.signUp(username, UserSecret(password))))
                case _ => complete(StatusCodes.Unauthorized)
              }
            }
          }
        } ~
        path("signOut") {
          securedAccess { ctx =>
            post {
              Future(authService.signOut(ctx.userId))
              complete(StatusCodes.Accepted)
            }
          }
        }
    } ~
      path("credentials") {
        securedAccess { ctx =>
          patch {
            entity(as[String]) { password =>
              complete(Future(authService.updateCredentials(ctx.userId, UserSecret(password))))
            }
          }
        }
      }
} 
开发者ID:lymr,项目名称:fun-chat,代码行数:59,代码来源:AuthenticationRoute.scala


示例19: DeviceUpdateBulkRoute

//设置package包名称以及导入依赖的类
package com.ubirch.avatar.backend.route

import akka.actor.{ActorSystem, Props}
import akka.http.scaladsl.HttpExt
import akka.http.scaladsl.server.{Directives, Route}
import akka.routing.RoundRobinPool
import akka.stream.Materializer
import akka.util.Timeout
import com.typesafe.scalalogging.slf4j.StrictLogging
import com.ubirch.avatar.config.Config
import com.ubirch.avatar.core.actor.MessageValidatorActor
import com.ubirch.avatar.model.rest.device.DeviceDataRaw
import com.ubirch.avatar.util.actor.ActorNames
import com.ubirch.avatar.util.server.RouteConstants._
import com.ubirch.util.http.response.ResponseUtil
import com.ubirch.util.model.JsonResponse
import com.ubirch.util.mongo.connection.MongoUtil

import scala.concurrent.ExecutionContextExecutor
import scala.concurrent.duration._
import scala.language.postfixOps
import de.heikoseeberger.akkahttpjson4s.Json4sSupport._


class DeviceUpdateBulkRoute(implicit mongo: MongoUtil, httpClient: HttpExt, materializer: Materializer)
  extends ResponseUtil
    with Directives
    with StrictLogging {

  implicit val system = ActorSystem()
  implicit val executionContext: ExecutionContextExecutor = system.dispatcher
  implicit val timeout = Timeout(Config.actorTimeout seconds)

  private val validatorActor = system.actorOf(new RoundRobinPool(Config.akkaNumberOfWorkers).props(Props(new MessageValidatorActor())), ActorNames.MSG_VALIDATOR)

  val route: Route = {

    path(update / bulk) {

      pathEnd {

        post {

          post {
            entity(as[DeviceDataRaw]) { sdm =>

              validatorActor ! sdm

              complete(JsonResponse(message = "processing started"))
            }
          }
        }
      }
    }
  }
} 
开发者ID:ubirch,项目名称:ubirch-avatar-service,代码行数:57,代码来源:DeviceUpdateBulkRoute.scala


示例20: Subscription

//设置package包名称以及导入依赖的类
package com.mooneyserver.akkapubsub

import akka.actor.ActorRef
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Route
import spray.json.DefaultJsonProtocol
import akka.http.scaladsl.server.Directives

// domain model
final case class Subscription(id: Long, publisherId: Long)
final case class UpdateableEvent(id: Long, value: Double)

// collect your json format instances into a support trait:
trait PubSubApiJsonProtocl extends SprayJsonSupport with DefaultJsonProtocol {
  implicit val subscriptionFormat = jsonFormat2(Subscription)
  implicit val updateFormat = jsonFormat2(UpdateableEvent)
}

class RestService(subscriberShard: ActorRef, publisherShard: ActorRef)
  extends Directives with PubSubApiJsonProtocl {

  val routes: Route = path("subscriber") {
    post {
      entity(as[Subscription]) { subscription =>
        subscriberShard ! NewSubscriber(subscription)
        complete((StatusCodes.Accepted, "subscription created"))
      }
    }
  } ~ path("publisher") {
    post {
      entity(as[UpdateableEvent]) { event =>
        publisherShard ! PublisherUpdate(event)
        complete((StatusCodes.Accepted, "event updated"))
      }
    }
  } ~ path("health") {
    get {
      complete("All's good in the hood!")
    }
  }
} 
开发者ID:irishshagua,项目名称:akka-distributed-pub-sub-testing,代码行数:43,代码来源:RestService.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala CacheBuilder类代码示例发布时间:2022-05-23
下一篇:
Scala SparkEnv类代码示例发布时间: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