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


Scala complete类代码示例

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


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

示例1: handler

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

import akka.http.scaladsl.server.Directives.complete
import akka.http.scaladsl.server.{MalformedQueryParamRejection, MalformedRequestContentRejection, RejectionHandler}
import com.queirozf.utils.ResponseUtils.JsonBadRequest


  def handler = {
    RejectionHandler
      .newBuilder()
      .handle {
        case MalformedRequestContentRejection(msg, e) => complete(JsonBadRequest("GLOBAL", msg, Some(e)))
        case MalformedQueryParamRejection(parameterName, errorMsg, maybeThrowable) =>
          maybeThrowable match {
            case Some(e) => complete(JsonBadRequest(parameterName,errorMsg, Some(e)))
            case None    => complete(JsonBadRequest(parameterName, errorMsg))
          }
      }
      .result()
      .withFallback(RejectionHandler.default)
  }
} 
开发者ID:queirozfcom,项目名称:akka-http-docker-aws-code-pipeline-beanstalk,代码行数:23,代码来源:CustomRejectionHandling.scala

示例2: ImperativeRequestContext

//设置package包名称以及导入依赖的类
package org.cristal.api.helper

import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.Directives.complete
import akka.http.scaladsl.server.{RequestContext, Route, RouteResult, StandardRoute}
import scala.concurrent.Promise


final class ImperativeRequestContext(ctx: RequestContext, promise: Promise[RouteResult]) {
  private implicit val ec = ctx.executionContext
  def complete(obj: ToResponseMarshallable): Unit = ctx.complete(obj).onComplete(promise.complete)
  def fail(error: Throwable): Unit = ctx.fail(error).onComplete(promise.complete)
}

trait ApiHelper {

  def notImplementedResponse(msg: String = ""): StandardRoute =
    complete(HttpEntity(ContentTypes.`text/html(UTF-8)`,
      s"<h1>We plan to support this resource soon.</h1>"))

  def imperativelyComplete(inner: ImperativeRequestContext => Unit): Route = { ctx: RequestContext =>
    val p = Promise[RouteResult]()
    inner(new ImperativeRequestContext(ctx, p))
    p.future
  }

} 
开发者ID:frecano,项目名称:cristal,代码行数:29,代码来源:ApiHelper.scala

示例3: WebServer

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

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.Directives.{complete, get, path}
import akka.stream.ActorMaterializer

import scala.io.StdIn

object WebServer extends App {
  implicit val system = ActorSystem("my-system")
  implicit val materializer = ActorMaterializer()
  // needed for the future flatMap/onComplete in the end
  implicit val executionContext = system.dispatcher

  val route =
    path("hello") {
      get {
        complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Say hello to akka-http</h1>"))
      }
    }

  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
} 
开发者ID:hiroinamine,项目名称:akka-labs,代码行数:32,代码来源:WebServer.scala

示例4: ResponseBuilder

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

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.{StatusCode, StatusCodes}
import akka.http.scaladsl.server.Directives.complete
import akka.http.scaladsl.server.StandardRoute
import homeworkzen.model._
import spray.json.{DefaultJsonProtocol, JsonFormat, RootJsonFormat}

object ResponseBuilder extends DefaultJsonProtocol with SprayJsonSupport {

  private case class ResponseTemplateWithoutResult(statusCode: Int, message: String)

  private case class ResponseTemplateWithResult[T](statusCode: Int, message: String, result: T)

  private implicit val responseTemplateWithoutResultFormat: RootJsonFormat[ResponseTemplateWithoutResult] =
    jsonFormat2(ResponseTemplateWithoutResult)

  // same as akka http default
  def internalServerError(): StandardRoute =
    complete(StatusCodes.InternalServerError -> "There was an internal server error.")

  def success(statusCode: StatusCode): StandardRoute =
    complete(statusCode -> ResponseTemplateWithoutResult(statusCode.intValue, "success"))

  def success[T](statusCode: StatusCode, result: T)(implicit jsonFormat: JsonFormat[T]): StandardRoute = {
    implicit val format: RootJsonFormat[ResponseTemplateWithResult[T]] = jsonFormat3(ResponseTemplateWithResult[T])
    complete(statusCode -> ResponseTemplateWithResult(statusCode.intValue, "success", result))
  }

  def failure(statusCode: StatusCode, message: String): StandardRoute =
    complete(statusCode -> ResponseTemplateWithoutResult(statusCode.intValue, message))

  def notFound(unitId: UnitId): StandardRoute = {
    val body = ResponseTemplateWithoutResult(StatusCodes.NotFound.intValue, s"Could not find station with id ${unitId.id.toString}")
    complete(StatusCodes.NotFound -> body)
  }
} 
开发者ID:anopse,项目名称:HomeworkZen,代码行数:39,代码来源:ResponseBuilder.scala

示例5: CovarianceInput

//设置package包名称以及导入依赖的类
package org.openalgo.analytics

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.StatusCodes.OK
import akka.http.scaladsl.server.Directives.{as, complete, decodeRequest, entity, path, post}
import akka.stream.ActorMaterializer
import argonaut.Argonaut.casecodec2
import com.typesafe.config.ConfigFactory
import de.heikoseeberger.akkahttpargonaut.ArgonautSupport

import scala.collection.JavaConverters._
import scala.collection.mutable

case class CovarianceInput(series1: mutable.Buffer[java.lang.Double], series2: mutable.Buffer[java.lang.Double])

object AppMain extends App with ArgonautSupport {
  val config = ConfigFactory.load()

  implicit def PersonCodecJson =
    casecodec2(CovarianceInput.apply, CovarianceInput.unapply)("series1", "series2")

  implicit val system = ActorSystem("my-system")
  implicit val materializer = ActorMaterializer()
  implicit val ec = system.dispatcher

  val route =
    path("covariance") {
      post {
        decodeRequest {
          entity(as[CovarianceInput]) { json: CovarianceInput =>
            complete(OK, CovarianceCall.getCovariance(json.series1.asJava, json.series2.asJava))
          }
        }
      }
    }

  val bindingFuture = Http().bindAndHandle(route, config.getString("http.interface"), config.getInt("http.port"))

  println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
  Console.readLine() // for the future transformations
  bindingFuture
    .flatMap(_.unbind()) // trigger unbinding from the port
    .onComplete(_ ? system.terminate()) // and shutdown when done
} 
开发者ID:openalgo,项目名称:analytics,代码行数:46,代码来源:AppMain.scala

示例6: WebServer2

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

import scala.io.StdIn
import scala.util.Random

import akka.actor.ActorSystem
import akka.http.scaladsl.marshalling.ToResponseMarshallable.apply
import akka.http.scaladsl.model.ContentTypes
import akka.http.scaladsl.model.HttpEntity
import akka.http.scaladsl.server.Directive.addByNameNullaryApply
import akka.http.scaladsl.server.Directives._segmentStringToPathMatcher
import akka.http.scaladsl.server.Directives.complete
import akka.http.scaladsl.server.Directives.get
import akka.http.scaladsl.server.Directives.path
import akka.http.scaladsl.server.RouteResult.route2HandlerFlow
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source
import akka.util.ByteString
import akka.http.scaladsl.Http

object WebServer2 {
  def main(args: Array[String]) {
    implicit val system = ActorSystem()
    implicit val materializer = ActorMaterializer()
    implicit val executionContext = system.dispatcher

    val numbers = Source.fromIterator(() =>
      Iterator.continually(Random.nextInt()))

    val route =
      path("random") {
        get {
          complete(
            HttpEntity(
              ContentTypes.`text/plain(UTF-8)`,
              numbers.map(n => ByteString(s"$n\n"))))
        }
      }

    val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
    println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
    StdIn.readLine()
    bindingFuture
      .flatMap(_.unbind())
      .onComplete(_ => system.terminate())
  }
} 
开发者ID:xtwxy,项目名称:akka-tests,代码行数:48,代码来源:WebServer2.scala

示例7: WebServer

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

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshalling.ToResponseMarshallable.apply
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.Directive.addByNameNullaryApply
import akka.http.scaladsl.server.Directives.{_segmentStringToPathMatcher, complete, get, path}
import akka.http.scaladsl.server.RouteResult.route2HandlerFlow
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory

import scala.io.StdIn

object WebServer {
  def main_(args: Array[String]) {

    implicit val seedConfig = ConfigFactory.load("dcim-cluster")
    implicit val seedSystem = ActorSystem("dcim", seedConfig)
    implicit val materializer = ActorMaterializer()
    implicit val executionContext = seedSystem.dispatcher

    val route =
      path("hello") {
        get {
          complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Say hello to akka-http</h1>"))
        }
      }

    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(_ => seedSystem.terminate()) // and shutdown when done
  }
} 
开发者ID:xtwxy,项目名称:akka-tests,代码行数:39,代码来源:WebServer.scala

示例8: UserController

//设置package包名称以及导入依赖的类
package com.softwaremill.sandbox.api.http

import java.util.UUID

import akka.http.scaladsl.server.Directives.{complete, onSuccess, pathEnd, pathPrefix, post, _}
import akka.http.scaladsl.server.Route
import com.softwaremill.sandbox.application.UserService
import com.typesafe.scalalogging.LazyLogging
import kamon.akka.http.KamonTraceDirectives
import kamon.trace.Tracer

import scala.concurrent.ExecutionContext

class UserController(userService: UserService)(implicit executionContext: ExecutionContext) extends KamonTraceDirectives with LazyLogging {

  def routes: Route = pathPrefix("user") {
    pathEnd {
      post {
        traceName("user-creation") {
          val uuid = UUID.randomUUID()
          logger.debug(s"processing user $uuid creation request [token ${Tracer.currentContext.token}]")

          onSuccess(userService.createUser(uuid)) {
            case name: String =>
              logger.debug(s"creating user $uuid finished [token ${Tracer.currentContext.token}]")
              complete(201, s"user $uuid created")
          }
        }
      }
    } ~
      pathPrefix(JavaUUID) { uuid =>
        pathEnd {
          get {
            traceName("get-user") {
              onSuccess(userService.getUser(uuid)) {
                case Some(userName) =>
                  logger.debug(s"getting user $uuid finished [token ${Tracer.currentContext.token}]")
                  complete(200, s"user $uuid found, name is: $userName")
                case None =>
                  logger.debug(s"user $uuid not found [token ${Tracer.currentContext.token}]")
                  complete(404, s"user $uuid not found")
              }
            }
          }
        }
      }
  }
} 
开发者ID:softwaremill,项目名称:akka-sandbox,代码行数:49,代码来源:UserController.scala

示例9:

//设置package包名称以及导入依赖的类
package au.edu.utscic.athanorserver.server

import akka.http.scaladsl.server.Directives.{as, complete, entity, extractUnmatchedPath, pathPrefix, post}
import akka.http.scaladsl.server.Route
import akka.util.ByteString
import au.edu.utscic.athanorserver.message.Json


trait AthanorApi extends GenericApi {

  val textRoutes: Route = pathPrefix("text") {
    extractUnmatchedPath { param =>
      if (!param.isEmpty) {
        post {
          import akka.http.scaladsl.unmarshalling.PredefinedFromEntityUnmarshallers.byteStringUnmarshaller
          entity(as[ByteString]) { str =>
            if (str.isEmpty) complete("Text required for analysis")
            else {
              val analysisType = param.dropChars(1).head.toString
              //println("analysisType - {}",analysisType)
              val analysisMsg = Json.ByteStringAnalysis(str,analysisType)
              complete(TextAnalysisHandler.analyse(analysisMsg))
            }
          }
        }
      }
      else nothingHere
    }
  }

  override val customRoutes: Route = pathPrefix("analyse") {
    textRoutes
  }

} 
开发者ID:uts-cic,项目名称:athanor-server,代码行数:36,代码来源:AthanorApi.scala

示例10: searchClient

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

import akka.actor.ActorSystem
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshalling.ToResponseMarshallable.apply
import akka.http.scaladsl.server.Directive.addByNameNullaryApply
import akka.http.scaladsl.server.Directives.complete
import akka.http.scaladsl.server.Directives.get
import akka.http.scaladsl.server.Directives.path
import akka.http.scaladsl.server.Directives.segmentStringToPathMatcher
import akka.http.scaladsl.server.RouteResult.route2HandlerFlow
import akka.stream.ActorMaterializer
import houseprices.search.model._
import houseprices.search.model.SearchResultJsonProtocol._
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import scala.concurrent.ExecutionContext
import spray.json.DefaultJsonProtocol
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport

trait SearchJsonProtocol extends SprayJsonSupport with DefaultJsonProtocol {
  implicit val format2 = jsonFormat3(PricePaidData)
  implicit val format1 = jsonFormat2(SearchResult)
}

trait HousePriceSearchService extends SearchJsonProtocol {
  def searchClient: SearchClient
  implicit val ec: ExecutionContext

  val routes =
    path("search" / ".*".r) { text =>
      get {
        complete {
          searchClient.search(Query(text))
        }
      }
    }
}

class HousePriceSearchServer(val searchClient: SearchClient)(implicit val system: ActorSystem, implicit val materializer: ActorMaterializer) extends HousePriceSearchService {

  val log = Logging(system, getClass)
  implicit val ec = system.dispatcher
  def startServer(interface: String, port: Int) = {
    Http().bindAndHandle(routes, interface, port)
    log.info("Search server ready at {}:{}", interface, port)
    this
  }
}

object DevHousePriceSearchServer extends App {
  implicit val system = ActorSystem("housePriceSearchServer")
  implicit val materializer = ActorMaterializer()
  val searchClient = HttpSearchClient(system)
  new HousePriceSearchServer(searchClient).startServer("localhost", 8080)
} 
开发者ID:ayubmalik,项目名称:houseprices,代码行数:57,代码来源:HousePriceSearchServer.scala

示例11: Pong

//设置package包名称以及导入依赖的类
package net.petitviolet.domain.pong

import akka.http.scaladsl.server.Directives.complete
import akka.http.scaladsl.server.StandardRoute

case class Pong(msg: String) {
  lazy val out: String = s"Pong!!! $msg"
}

object Pong {
  def apply(): Pong = {
    Pong("")
  }
}

trait PongService {
  def response(pong: Pong = Pong()): StandardRoute = {
    complete(pong.out)
  }
}
trait UsesPongService {
  val pongService: PongService
}

trait MixInPongService {
  val pongService: PongService = new PongServiceImpl
}

class PongServiceImpl extends PongService 
开发者ID:petitviolet,项目名称:akka-http-slick-ddd,代码行数:30,代码来源:Pong.scala

示例12: QuizRoute

//设置package包名称以及导入依赖的类
package app.flashcard.route

import akka.NotUsed
import akka.http.scaladsl.common.{EntityStreamingSupport, JsonEntityStreamingSupport}
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.server.Directives.{complete, _}
import akka.stream.scaladsl.Source
import app.flashcard.repository.FlashcardRepository
import app.flashcard.route.QuizRoute._
import spray.json.DefaultJsonProtocol

class QuizRoute(flashcardRepository: FlashcardRepository) extends DefaultJsonProtocol with SprayJsonSupport {
  implicit val questionJson = jsonFormat1(Question)
  implicit val answerJson = jsonFormat1(Answer)
  implicit val jsonStreamingSupport: JsonEntityStreamingSupport = EntityStreamingSupport.json()

  
  def answer = path("answer") {
    get {
      parameter('word) { word =>
        parameter('translation) { translation =>
          val response: Source[Answer, NotUsed] = flashcardRepository
            .get(word)
            .map(flashcard => Answer(flashcard.translation.equalsIgnoreCase(translation)))

          complete(response)
        }
      }
    }
  }

  def routes = pathPrefix("quiz")(question ~ answer)
}

object QuizRoute {

  case class Question(word: String)

  case class Answer(correct: Boolean)

  def apply(flashcardRepository: FlashcardRepository): QuizRoute = new QuizRoute(flashcardRepository)
} 
开发者ID:mateuszjancy,项目名称:intro-to-akka-stream,代码行数:43,代码来源:QuizRoute.scala


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