本文整理汇总了Scala中akka.http.scaladsl.server.Route类的典型用法代码示例。如果您正苦于以下问题:Scala Route类的具体用法?Scala Route怎么用?Scala Route使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Route类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Demo1
//设置package包名称以及导入依赖的类
package lew.bing.akka.http
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.{Directive, RequestContext, Route, RouteResult}
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Flow
import scala.io.StdIn
object Demo1 {
def main(args: Array[String]): Unit = {
implicit val system = ActorSystem("my-http")
implicit val materializer = ActorMaterializer()
// needed for the future flatMap/onComplete in the end
implicit val executionContext = system.dispatcher
val route:Route =
path("hello"){
get {
complete(HttpEntity(ContentTypes.`text/html(UTF-8)`,"<h1>Say hello to akka-http</h1>"))
}
}
val map = Flow[RequestContext].map(route)
//???????????
val bindingFuture = Http().bindAndHandle(route,"localhost",9898)
println(s"Server online at http://localhost:9898/\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
}
}
示例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
}
}
}
}
}
}
}
示例3: executor
//设置package包名称以及导入依赖的类
package com.ferhtaydn.server
import akka.actor.ActorSystem
import akka.event.LoggingAdapter
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.server.Directives._
import akka.stream.Materializer
import com.ferhtaydn.models.{ JsonFormats, PatientInfo, PatientResult }
import com.ferhtaydn.rater.RatePredictor
import akka.http.scaladsl.model.StatusCodes._
import scala.concurrent.ExecutionContextExecutor
trait Server extends JsonFormats {
implicit val system: ActorSystem
implicit def executor: ExecutionContextExecutor
implicit val materializer: Materializer
val logger: LoggingAdapter
def predictor: RatePredictor
protected val routes: Route =
pathPrefix("cancerater") {
get {
pathSingleSlash {
complete("Welcome to CanceRater")
}
} ~
get {
path("cm") {
complete {
predictor.confusionMatrixString.map[ToResponseMarshallable] {
case cm ? cm
}
}
}
} ~
post {
path("check") {
entity(as[PatientInfo]) { patientInfo ?
complete {
predictor.predict(patientInfo).map[ToResponseMarshallable] {
case Right(score) ? PatientResult(score)
case Left(error) ? BadRequest ? error
}
}
}
}
}
}
}
示例4: UsersProtonModule
//设置package包名称以及导入依赖的类
package proton.users
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ExceptionHandler, Route, RouteResult}
import akka.stream.ActorMaterializer
import com.typesafe.config.Config
import com.typesafe.scalalogging.LazyLogging
import scaldi.{Injectable, Module, TypesafeConfigInjector}
import spray.json.{CompactPrinter, JsonPrinter}
import scala.concurrent.ExecutionContext
class UsersProtonModule(config: Config) extends Module {
bind[ExecutionContext] to scala.concurrent.ExecutionContext.Implicits.global
bind[ActorSystem] to ActorSystem("ProtonUsers", config) destroyWith (_.terminate())
bind[JsonPrinter] to CompactPrinter
}
object UsersProtonApp extends App with Injectable with LazyLogging with SprayJsonSupport with UsersProtocol {
ProtonConfig.parse("users-dev.conf", args).foreach(c => {
val config = c.config
implicit val injector = TypesafeConfigInjector(config) :: new UsersProtonModule(config)
implicit val executionContext = inject[ExecutionContext]
implicit val system = inject[ActorSystem]
implicit val materializer = ActorMaterializer()
implicit val printer = inject[JsonPrinter]
implicit val exceptionHandler = ExceptionHandler {
case e: Exception =>
logger.error("HTTP unhandled exception.", e)
var message = "HTTP unhandled exception."
if (e != null) {
message = e.getMessage
}
complete(InternalServerError -> Message(message, UsersEvents.Unhandled))
}
def route: Route =
pathSingleSlash {
get {
complete("test")
}
}
Http().bindAndHandle(route, config.getString("proton.ip"), config.getInt("proton.users.http.port"))
})
}
示例5: MainRoute
//设置package包名称以及导入依赖的类
package com.ubirch.auth.server.route
import com.ubirch.auth.util.server.RouteConstants
import com.ubirch.util.mongo.connection.MongoUtil
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
class MainRoute(implicit mongo: MongoUtil) {
val welcome = new WelcomeRoute {}
val deepCheck = new DeepCheckRoute {}
val provider = new ProviderRoute {}
val token = new TokenRoute {}
val logout = new LogoutRoute {}
val register = new RegisterRoute {}
val userInfo = new UserInfoRoute() {}
val myRoute: Route = {
pathPrefix(RouteConstants.apiPrefix) {
pathPrefix(RouteConstants.serviceName) {
pathPrefix(RouteConstants.currentVersion) {
provider.route ~
token.route ~
logout.route ~
register.route ~
userInfo.route ~
deepCheck.route ~
path(RouteConstants.check) {
welcome.route
} ~ pathEndOrSingleSlash {
welcome.route
}
}
}
} ~
pathSingleSlash {
welcome.route
}
}
}
示例6: TestWasatAuth
//设置package包名称以及导入依赖的类
package co.horn.alkes.auth
import akka.http.scaladsl.model.HttpMethods.{DELETE, GET, POST}
import akka.http.scaladsl.model.StatusCodes.ServerError
import akka.http.scaladsl.model.headers.OAuth2BearerToken
import akka.http.scaladsl.server.Route
class TestWasatAuth extends AuthTest {
val auth: Authority = new WasatAuthority(config)
describe("Alkes is able to communicate with Wasat") {
ignore("WasatAuthority is responding to Alkes' PING calls") {
Get(s"$BASE_PATH/auth") ~> Route.seal(routes) ~> check {
status should not be a[ServerError]
}
}
}
describe("WasatAuthority should allow") {
ignore("anyone to ping") {
canAccessRoute(OAuth2BearerToken("a"), s"$BASE_PATH/ping", GET) shouldBe true
}
ignore("anyone to check the database is alive") {
canAccessRoute(OAuth2BearerToken("b"), s"$BASE_PATH/database", GET) shouldBe true
}
ignore("anyone to accidentally use POST") {
canAccessRoute(OAuth2BearerToken("c"), s"$BASE_PATH", POST) shouldBe true
}
ignore("anyone to stumble upon the wrong route") {
canAccessRoute(OAuth2BearerToken("d"), s"$BASE_PATH/whoops/wrong/path", GET) shouldBe true
}
}
describe("DummyAuthority should NOT allow") {
ignore("anonymous users to Get server file lists") {
canAccessRoute(OAuth2BearerToken("j"), s"$LIST_PATH", GET) shouldBe false
}
ignore("anonymous users to Delete server file lists") {
canAccessRoute(OAuth2BearerToken("k"), s"$LIST_PATH", DELETE) shouldBe false
}
}
}
示例7: canAccessRoute
//设置package包名称以及导入依赖的类
package co.horn.alkes.auth
import akka.http.scaladsl.model.HttpMethod
import akka.http.scaladsl.model.HttpMethods.{DELETE, GET, POST, PUT}
import akka.http.scaladsl.model.StatusCodes.{Forbidden, ServerError}
import akka.http.scaladsl.model.headers.{Authorization, OAuth2BearerToken}
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.testkit.ScalatestRouteTest
import co.horn.alkes.config.Configuration
import co.horn.alkes.dao.DataHandler
import co.horn.alkes.dao.implementations.riak.RiakDataHandler
import co.horn.alkes.log.Logger
import co.horn.alkes.rest.Routes
import org.scalatest.{FunSpec, Matchers}
import org.scalatest.concurrent.Eventually
trait AuthTest extends FunSpec with Matchers with Eventually with ScalatestRouteTest with Routes {
val config: Configuration = Configuration.get
val dao: DataHandler = new RiakDataHandler(config)
val log: Logger = config.log.tests
// TODO: Define these all in just ONE spot. Need to keep DRY!
val BASE_PATH: String = "/" + config.app.name
val FILE_PATH: String = BASE_PATH + "/share/file"
val LIST_PATH: String = BASE_PATH + "/share/filelist"
val META_PATH: String = BASE_PATH + "/share/metadata"
val THUMB_PATH: String = BASE_PATH + "/share/thumbnail"
def canAccessRoute(token: OAuth2BearerToken, route: String, method: HttpMethod): Boolean = {
method match {
case GET =>
Get(route).withHeaders(Authorization(token)) ~> Route.seal(routes) ~> check {
status should not be a[ServerError]
status != Forbidden
}
case PUT =>
Put(route).withHeaders(Authorization(token)) ~> Route.seal(routes) ~> check {
status should not be a[ServerError]
status != Forbidden
}
case DELETE =>
Get(route).withHeaders(Authorization(token)) ~> Route.seal(routes) ~> check {
status should not be a[ServerError]
status != Forbidden
}
case POST =>
Post(route).withHeaders(Authorization(token)) ~> Route.seal(routes) ~> check {
status should not be a[ServerError]
status != Forbidden
}
case m => throw new IllegalArgumentException(s"$m is not an HttpMethod accepted by Alkes.")
}
}
}
示例8: corsAllowOrigins
//设置package包名称以及导入依赖的类
package com.signalswarm
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.{HttpHeader, HttpResponse}
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{Route, Directive0, MethodRejection, RejectionHandler}
trait CorsSupport {
protected def corsAllowOrigins: List[String]
protected def corsAllowedHeaders: List[String]
protected def corsAllowCredentials: Boolean
protected def optionsCorsHeaders: List[HttpHeader]
protected def corsRejectionHandler(allowOrigin: `Access-Control-Allow-Origin`) = RejectionHandler
.newBuilder().handle {
case MethodRejection(supported) =>
complete(HttpResponse().withHeaders(
`Access-Control-Allow-Methods`(OPTIONS, supported) ::
allowOrigin ::
optionsCorsHeaders
))
}
.result()
private def originToAllowOrigin(origin: Origin): Option[`Access-Control-Allow-Origin`] =
if (corsAllowOrigins.contains("*") || corsAllowOrigins.contains(origin.value))
origin.origins.headOption.map(`Access-Control-Allow-Origin`.apply)
else
None
def cors[T]: Directive0 = mapInnerRoute { route => context =>
((context.request.method, context.request.header[Origin].flatMap(originToAllowOrigin)) match {
case (OPTIONS, Some(allowOrigin)) =>
handleRejections(corsRejectionHandler(allowOrigin)) {
respondWithHeaders(allowOrigin,
`Access-Control-Allow-Credentials`(corsAllowCredentials)) {
preflightRequestHandler ~ route
}
}
case (_, Some(allowOrigin)) =>
respondWithHeaders(allowOrigin, `Access-Control-Allow-Credentials`(corsAllowCredentials)) {
route ~ preflightRequestHandler
}
case (_, _) =>
route
})(context)
}
private def preflightRequestHandler: Route = options {
complete(HttpResponse(200).withHeaders(
`Access-Control-Allow-Methods`(OPTIONS, POST, PUT, GET, DELETE),
`Access-Control-Allow-Headers`(corsAllowedHeaders)
)
)
}
}
示例9: 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)
}
}
}
}
}
}
}
示例10: addAccessControlHeaders
//设置package包名称以及导入依赖的类
package utils
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ Directive0, Route }
import com.typesafe.config.ConfigFactory
trait CorsSupport {
lazy val allowedOriginHeader = {
val config = ConfigFactory.load()
val sAllowedOrigin = config.getString("cors.allowed-origin")
if (sAllowedOrigin == "*")
`Access-Control-Allow-Origin`.*
else
`Access-Control-Allow-Origin`(HttpOrigin(sAllowedOrigin))
}
private def addAccessControlHeaders: Directive0 = {
mapResponseHeaders { headers =>
allowedOriginHeader +:
`Access-Control-Allow-Credentials`(true) +:
`Access-Control-Allow-Headers`("Token", "Content-Type", "X-Requested-With") +:
headers
}
}
private def preflightRequestHandler: Route = options {
complete(HttpResponse(200).withHeaders(
`Access-Control-Allow-Methods`(OPTIONS, POST, PUT, GET, DELETE)
))
}
def corsHandler(r: Route) = addAccessControlHeaders {
preflightRequestHandler ~ r
}
}
示例11: WebJarsSupport
//设置package包名称以及导入依赖的类
package task.airport
package util
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import org.webjars.WebJarAssetLocator
import scala.util.{Failure, Success, Try}
// See: https://github.com/ThoughtWorksInc/akka-http-webjars/blob/master/src/main/scala/com/thoughtworks/akka/http/WebJarsSupport.scala
trait WebJarsSupport {
private val webJarAssetLocator = new WebJarAssetLocator
val webJars: Route =
path(Segment / Remaining) { (webJar, partialPath) =>
Try {
webJarAssetLocator.getFullPath(webJar, partialPath)
} match {
case Success(fullPath) => getFromResource(fullPath)
case Failure(_: IllegalArgumentException) => reject
case Failure(exception) => failWith(exception)
}
}
}
object WebJarsSupport extends WebJarsSupport
示例12: WebhooksHttpHandler
//设置package包名称以及导入依赖的类
package im.actor.server.webhooks.http.routes
import akka.actor.ActorSystem
import akka.event.Logging
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.stream.{ ActorMaterializer, Materializer }
import akka.util.Timeout
import im.actor.server.api.http.HttpHandler
import im.actor.server.group.IntegrationTokensReadCompat
import scala.concurrent.ExecutionContext
import scala.concurrent.duration._
final class WebhooksHttpHandler()(implicit val system: ActorSystem)
extends HttpHandler
with OutgoingHooks
with IngoingHooks
with TokenStatus {
protected implicit val ec: ExecutionContext = system.dispatcher
implicit val materializer: Materializer = ActorMaterializer()
implicit val timeout: Timeout = Timeout(5.seconds)
protected val log = Logging(system, getClass)
protected val integrationTokensKV = new IntegrationTokensReadCompat
override def routes: Route =
defaultVersion {
pathPrefix("webhooks") {
outgoing ~ ingoing ~ status
}
}
}
示例13: AboutHttpHandler
//设置package包名称以及导入依赖的类
package im.actor.server.api.http.info
import akka.actor.ActorSystem
import akka.http.scaladsl.model.StatusCodes.OK
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import de.heikoseeberger.akkahttpcirce.CirceSupport
import im.actor.config.ActorConfig
import im.actor.server.api.http.HttpHandler
import im.actor.server.api.http.json.{ JsonEncoders, ServerInfo }
import scala.collection.JavaConversions._
private[http] final class AboutHttpHandler()(implicit system: ActorSystem) extends HttpHandler
with CirceSupport
with JsonEncoders {
private lazy val about = getServerInfo
def routes: Route = path("about") {
get {
complete(OK ? about)
}
}
private def getServerInfo: ServerInfo =
ServerInfo(
projectName = ActorConfig.projectName,
endpoints = ActorConfig.load().getStringList("public-endpoints").toList
)
}
示例14: DiscussionGroupsHttpHandler
//设置package包名称以及导入依赖的类
package im.actor.server.api.http.rest.groups
import akka.actor.ActorSystem
import akka.http.scaladsl.model.StatusCodes.OK
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import im.actor.server.db.DbExtension
import de.heikoseeberger.akkahttpplayjson.PlayJsonSupport
import im.actor.server.api.http.HttpHandler
import im.actor.server.api.http.json.{ JsonFormatters, DiscussionGroupInfo }
import im.actor.server.persist.DiscussionGroupRepo
import im.actor.server.api.http.rest.util.SecurityManager
/**
* Created by User on 2016/10/8.
*/
private[http] final class DiscussionGroupsHttpHandler()(implicit system: ActorSystem) extends HttpHandler with PlayJsonSupport {
import JsonFormatters._
private lazy val db = DbExtension(system).db
private lazy val config = system.settings.config
override def routes: Route =
defaultVersion {
pathPrefix("dangchat-discussionGroups") {
pathEnd {
post {
complete("The post http request is not processed!")
}
} ~
get {
//??request?? request =>
path(Segment) { discussionGroupId ?
//???????ctx.uri.query.get("apiPwd")
parameters('apiPassword) { apiPassword ?
if (SecurityManager.checkApiPassword(apiPassword, config)) {
//?????Id?????
val optDiscussionGroup = scala.concurrent.Await.result(
db.run(DiscussionGroupRepo.findById(discussionGroupId)), scala.concurrent.duration.Duration.Inf
)
optDiscussionGroup match {
case Some(discussionGroup) ? complete(OK ? DiscussionGroupInfo(discussionGroup.id, discussionGroup.groupId))
case None ? complete(OK ? DiscussionGroupInfo("", 0))
}
} else {
complete("Api password???")
}
}
}
} ~
put {
complete("The put http request is not processed!")
} ~
delete {
complete("The delete http request is not processed!")
}
}
}
}
示例15: WebServer
//设置package包名称以及导入依赖的类
package com.jjabuk.bookstore.web
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory.load
import scala.io.StdIn
import scala.language.postfixOps
import scala.util.Try
object WebServer extends App with Routes {
implicit val system = ActorSystem("bookstore")
implicit val materializer = ActorMaterializer()
implicit val executionContext = system.dispatcher
lazy val config = load("web.conf")
lazy val apiHost = Try(config getString "http.host") getOrElse "localhost"
lazy val apiPort = Try(config getInt "http.port") getOrElse 9000
val binding = Http().bindAndHandle(routes, apiHost, apiPort)
println(s"Server online at http://$apiHost:$apiPort/\nPress RETURN to stop...")
StdIn.readLine() // let it run until user presses return
binding flatMap (_.unbind()) onComplete (_ => system.terminate())
}