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


Scala Directives类代码示例

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


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


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