akka.http.scaladsl.marshalling.ToResponseMarshallable Scala Examples
The following examples show how to use akka.http.scaladsl.marshalling.ToResponseMarshallable.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: ModelService.scala From reactive-machine-learning-systems with MIT License | 6 votes |
package com.reactivemachinelearning import akka.actor.ActorSystem import akka.event.{Logging, LoggingAdapter} import akka.http.scaladsl.Http import akka.http.scaladsl.marshalling.ToResponseMarshallable import akka.http.scaladsl.model.StatusCodes._ import akka.http.scaladsl.server.Directives._ import akka.stream.{ActorMaterializer, Materializer} //import spray.json._ import spray.json.DefaultJsonProtocol import scala.concurrent.{ExecutionContextExecutor, Future} case class Prediction(id: Long, timestamp: Long, value: Double) trait Protocols extends DefaultJsonProtocol { implicit val ipInfoFormat = jsonFormat3(Prediction.apply) } trait Service extends Protocols { implicit val system: ActorSystem implicit def executor: ExecutionContextExecutor implicit val materializer: Materializer val logger: LoggingAdapter // private def parseFeatures(features: String): Map[Long, Double] = { // features.parseJson.convertTo[Map[Long, Double]] // } def predict(features: String): Future[Prediction] = { Future(Prediction(123, 456, 0.5)) } val routes = { logRequestResult("predictive-service") { pathPrefix("ip") { (get & path(Segment)) { features => complete { predict(features).map[ToResponseMarshallable] { // case prediction: Prediction => prediction case _ => BadRequest } } } } } } } object PredictiveService extends App with Service { override implicit val system = ActorSystem() override implicit val executor = system.dispatcher override implicit val materializer = ActorMaterializer() override val logger = Logging(system, getClass) Http().bindAndHandle(routes, "0.0.0.0", 9000) }
Example 2
Source File: AuthRoute.scala From matcher with MIT License | 5 votes |
package com.wavesplatform.dex.api.routes import akka.http.scaladsl.marshalling.{ToResponseMarshallable, ToResponseMarshaller} import akka.http.scaladsl.model.{StatusCode, StatusCodes} import akka.http.scaladsl.server.{Directive0, Directive1} import com.wavesplatform.dex.api.http.entities.{MatcherResponse, SimpleErrorResponse} import com.wavesplatform.dex.api.http.headers.{`X-Api-Key`, `X-User-Public-Key`, api_key} import com.wavesplatform.dex.api.ws.routes.MatcherWebSocketRoute import com.wavesplatform.dex.domain.account.PublicKey import com.wavesplatform.dex.domain.crypto import com.wavesplatform.dex.error.{ApiKeyIsNotProvided, ApiKeyIsNotValid, MatcherError, UserPublicKeyIsNotValid} trait AuthRoute { this: ApiRoute => protected val apiKeyHash: Option[Array[Byte]] def withAuth(implicit matcherResponseTrm: ToResponseMarshaller[MatcherResponse]): Directive0 = { def correctResponse(statusCode: StatusCode, matcherError: MatcherError): ToResponseMarshallable = this match { case _: MatcherWebSocketRoute => matcherError.toWsHttpResponse(statusCode) case _ => SimpleErrorResponse(statusCode, matcherError) } apiKeyHash.fold[Directive0] { complete(SimpleErrorResponse(StatusCodes.InternalServerError, ApiKeyIsNotProvided)) } { hashFromSettings => optionalHeaderValueByType[`X-Api-Key`](()).flatMap { case Some(key) if java.util.Arrays.equals(crypto secureHash key.value, hashFromSettings) => pass case _ => optionalHeaderValueByType[api_key](()).flatMap { case Some(key) if java.util.Arrays.equals(crypto secureHash key.value, hashFromSettings) => pass case _ => complete { correctResponse(StatusCodes.Forbidden, ApiKeyIsNotValid) } } } } } def withUserPublicKeyOpt(implicit matcherResponseTrm: ToResponseMarshaller[MatcherResponse]): Directive1[Option[PublicKey]] = optionalHeaderValueByType[`X-User-Public-Key`](()).flatMap { case None => provide(None) case Some(rawPublicKey) => PublicKey.fromBase58String(rawPublicKey.value) match { case Left(_) => complete(SimpleErrorResponse(StatusCodes.BadRequest, UserPublicKeyIsNotValid)) case Right(x) => provide[Option[PublicKey]](Some(PublicKey(x))) } } }
Example 3
Source File: MatcherApiRouteV1.scala From matcher with MIT License | 5 votes |
package com.wavesplatform.dex.api.http.routes import akka.http.scaladsl.marshalling.ToResponseMarshallable import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.server.directives.FutureDirectives import akka.http.scaladsl.server.{Directive1, Route} import com.wavesplatform.dex.Matcher import com.wavesplatform.dex.api.http.entities.{HttpV1OrderBook, InfoNotFound} import com.wavesplatform.dex.api.http.{HasStatusBarrier, OrderBookHttpInfo} import com.wavesplatform.dex.api.routes.{ApiRoute, AuthRoute, PathMatchers} import com.wavesplatform.dex.domain.asset.AssetPair import com.wavesplatform.dex.domain.utils.ScorexLogging import com.wavesplatform.dex.error.{ErrorFormatterContext, MatcherError} import com.wavesplatform.dex.model.{AssetPairBuilder, MatcherModel} import io.swagger.annotations.{Api, ApiImplicitParam, ApiImplicitParams, ApiOperation} import javax.ws.rs.Path @Path("/api/v1") @Api(value = "/api v1/") case class MatcherApiRouteV1(assetPairBuilder: AssetPairBuilder, orderBookHttpInfo: OrderBookHttpInfo, matcherStatus: () => Matcher.Status, apiKeyHash: Option[Array[Byte]])(implicit val errorContext: ErrorFormatterContext) extends ApiRoute with AuthRoute with HasStatusBarrier with ScorexLogging { import PathMatchers._ override lazy val route: Route = pathPrefix("api" / "v1") { matcherStatusBarrier { getOrderBook } } private def withAssetPair(p: AssetPair, redirectToInverse: Boolean, suffix: String = "", formatError: MatcherError => ToResponseMarshallable = InfoNotFound.apply): Directive1[AssetPair] = { FutureDirectives.onSuccess { assetPairBuilder.validateAssetPair(p).value } flatMap { case Right(_) => provide(p) case Left(e) if redirectToInverse => FutureDirectives.onSuccess { assetPairBuilder.validateAssetPair(p.reverse).value } flatMap { case Right(_) => redirect(s"/api/v1/${p.priceAssetStr}/${p.amountAssetStr}$suffix", StatusCodes.MovedPermanently) case Left(_) => complete(formatError(e)) } case Left(e) => complete { formatError(e) } } } @Path("/orderbook/{amountAsset}/{priceAsset}") @ApiOperation( value = "Get Order Book for a given Asset Pair", notes = "Get Order Book for a given Asset Pair", httpMethod = "GET", response = classOf[HttpV1OrderBook] ) @ApiImplicitParams( Array( new ApiImplicitParam(name = "amountAsset", value = "Amount Asset Id in Pair, or 'WAVES'", dataType = "string", paramType = "path"), new ApiImplicitParam(name = "priceAsset", value = "Price Asset Id in Pair, or 'WAVES'", dataType = "string", paramType = "path"), new ApiImplicitParam(name = "depth", value = "Limit the number of bid/ask records returned", required = false, dataType = "integer", paramType = "query") ) ) def getOrderBook: Route = (path("orderbook" / AssetPairPM) & get) { p => parameters('depth.as[Int].?) { depth => withAssetPair(p, redirectToInverse = true) { pair => complete { orderBookHttpInfo.getHttpView(pair, MatcherModel.Denormalized, depth) } } } } }
Example 4
Source File: HydraDirectives.scala From hydra with Apache License 2.0 | 5 votes |
package hydra.core.http import akka.http.scaladsl.marshalling.ToResponseMarshallable import akka.http.scaladsl.model.StatusCode import akka.http.scaladsl.model.Uri.Path import akka.http.scaladsl.model.headers.Location import akka.http.scaladsl.server._ import hydra.common.config.ConfigSupport import scala.concurrent.Promise trait HydraDirectives extends Directives with ConfigSupport { def imperativelyComplete(inner: ImperativeRequestContext => Unit): Route = { ctx: RequestContext => val p = Promise[RouteResult]() inner(new ImperativeRequestContextImpl(ctx, p)) p.future } def completeWithLocationHeader[T](status: StatusCode, resourceId: T): Route = extractRequestContext { requestContext => val request = requestContext.request val location = request.uri.withPath(Path("/" + resourceId.toString)) respondWithHeader(Location(location)) { complete(status) } } } trait ImperativeRequestContext { def complete(obj: ToResponseMarshallable): Unit def failWith(error: Throwable): Unit } // an imperative wrapper for request context final class ImperativeRequestContextImpl( val ctx: RequestContext, promise: Promise[RouteResult] ) extends ImperativeRequestContext { private implicit val ec = ctx.executionContext def complete(obj: ToResponseMarshallable): Unit = ctx.complete(obj).onComplete(promise.complete) def failWith(error: Throwable): Unit = ctx.fail(error).onComplete(promise.complete) }
Example 5
Source File: HttpRouter.scala From JustinDB with Apache License 2.0 | 5 votes |
package justin.httpapi import java.util.UUID import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ import akka.http.scaladsl.marshalling.ToResponseMarshallable import akka.http.scaladsl.model.StatusCodes._ import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.Route import justin.db.Data import justin.db.client.{ActorRefStorageNodeClient, GetValueResponse, WriteValueResponse} import justin.db.replica.{R, W} import justin.db.storage.Base64 import justin.db.versioning.NodeIdVectorClockBase64 import justin.httpapi.JustinDirectives._ import justin.httpapi.Unmarshallers.UUIDUnmarshaller import spray.json.DefaultJsonProtocol._ import spray.json.RootJsonFormat import scala.concurrent.ExecutionContext import scala.util.{Failure, Success} object HttpRouter { import Unmarshallers.UuidFormat case class Result(value: String) implicit val valueFormat: RootJsonFormat[Result] = jsonFormat1(Result) case class ConflictedData(id: String, value: String, vclock: Base64) implicit val conflictedDataFormat: RootJsonFormat[ConflictedData] = jsonFormat3(ConflictedData) case class PutValue(id: UUID, value: String, w: Int) implicit val putValueFormat: RootJsonFormat[PutValue] = jsonFormat3(PutValue) } class HttpRouter(client: ActorRefStorageNodeClient)(implicit ec: ExecutionContext) { import HttpRouter._ private[this] def transformConflictedData(data: Data) = { val vcBase64 = new NodeIdVectorClockBase64().encode(data.vclock).get ConflictedData(data.id.toString, data.value, vcBase64) } def routes: Route = withVectorClockHeader { vClockHeader => { (get & path("get") & pathEndOrSingleSlash & parameters(('id.as(UUIDUnmarshaller), 'r.as[Int]))) { (uuid, r) => onComplete(client.get(uuid, R(r))) { case Success(GetValueResponse.Found(data)) => respondWithHeader(VectorClockHeader(data.vclock)) { complete(OK -> Result(data.value)) } case Success(GetValueResponse.Conflicts(data)) => complete(MultipleChoices -> data.map(transformConflictedData)) case Success(GetValueResponse.NotFound(id)) => complete(NotFound -> Result(s"Couldn't found value with id ${id.toString}")) case Success(GetValueResponse.Failure(err)) => complete(BadRequest -> Result(err)) case Failure(ex) => complete(InternalServerError -> Result(ex.getMessage)) } } } ~ (post & path("put") & pathEndOrSingleSlash & entity(as[PutValue])) { putValue => complete { client.write(Data(putValue.id, putValue.value, vClockHeader.vectorClock), W(putValue.w)).map[ToResponseMarshallable] { case WriteValueResponse.Success(id) => NoContent case WriteValueResponse.Conflict => MultipleChoices -> Result("Multiple Choices") case WriteValueResponse.Failure(err) => BadRequest -> Result(err) } } } } }
Example 6
Source File: StaticService.scala From incubator-retired-gearpump with Apache License 2.0 | 5 votes |
package org.apache.gearpump.services import akka.actor.ActorSystem import akka.http.scaladsl.marshalling.ToResponseMarshallable import akka.http.scaladsl.model._ import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.marshalling.ToResponseMarshallable._ import akka.stream.Materializer import org.apache.gearpump.util.Util // NOTE: This cannot be removed!!! import org.apache.gearpump.services.util.UpickleUtil._ class StaticService(override val system: ActorSystem, supervisorPath: String) extends BasicService { private val version = Util.version protected override def prefix = Neutral override def cache: Boolean = true protected override def doRoute(implicit mat: Materializer) = { path("version") { get { ctx => ctx.complete(version) } } ~ // For YARN usage, we need to make sure supervisor-path // can be accessed without authentication. path("supervisor-actor-path") { get { complete(supervisorPath) } } ~ pathEndOrSingleSlash { getFromResource("index.html") } ~ path("favicon.ico") { complete(ToResponseMarshallable(StatusCodes.NotFound)) } ~ pathPrefix("webjars") { get { getFromResourceDirectory("META-INF/resources/webjars") } } ~ path(Remaining) { path => getFromResource("%s" format path) } } }
Example 7
Source File: MyResource.scala From quiz-management-service with Apache License 2.0 | 5 votes |
package com.danielasfregola.quiz.management.routing import akka.http.scaladsl.marshalling.{ToResponseMarshaller, ToResponseMarshallable} import scala.concurrent.{ExecutionContext, Future} import akka.http.scaladsl.model.headers.Location import akka.http.scaladsl.server.{Directives, Route} import com.danielasfregola.quiz.management.serializers.JsonSupport trait MyResource extends Directives with JsonSupport { 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(404, None) } def complete(resource: Future[Unit]): Route = onSuccess(resource) { complete(204, None) } }
Example 8
Source File: AuthCodeCard.scala From reactive-microservices with MIT License | 5 votes |
import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ import akka.http.scaladsl.marshalling.ToResponseMarshallable import akka.http.scaladsl.model.StatusCodes._ import akka.http.scaladsl.server.Directives._ import akka.stream.ActorFlowMaterializer case class CodeCard(id: Long, codes: Seq[String], userIdentifier: String) case class RegisterResponse(identity: Identity, codesCard: CodeCard) case class LoginRequest(userIdentifier: String, cardIndex: Long, codeIndex: Long, code: String) case class ActivateCodeRequest(userIdentifier: String) case class ActivateCodeResponse(cardIndex: Long, codeIndex: Long) case class GetCodeCardRequest(userIdentifier: String) case class GetCodeCardResponse(userIdentifier: String, codesCard: CodeCard) case class Identity(id: Long) case class Token(value: String, validTo: Long, identityId: Long, authMethods: Set[String]) object AuthCodeCardCard extends App with JsonProtocols with Config { implicit val actorSystem = ActorSystem() implicit val materializer = ActorFlowMaterializer() implicit val dispatcher = actorSystem.dispatcher val repository = new Repository val gateway = new Gateway val service = new Service(gateway, repository) Http().bindAndHandle(interface = interface, port = port, handler = { logRequestResult("auth-codecard") { (path("register" / "codecard" ) & pathEndOrSingleSlash & post & optionalHeaderValueByName("Auth-Token")) { (tokenValue) => complete { service.register(tokenValue).map[ToResponseMarshallable] { case Right(response) => Created -> response case Left(errorMessage) => BadRequest -> errorMessage } } } ~ (path("login" / "codecard" / "activate") & pathEndOrSingleSlash & post & entity(as[ActivateCodeRequest])) { (request) => complete { service.activateCode(request).map[ToResponseMarshallable] { case Right(response) => OK -> response case Left(errorMessage) => BadRequest -> errorMessage } } } ~ (path("login" / "codecard") & pathEndOrSingleSlash & post & optionalHeaderValueByName("Auth-Token") & entity(as[LoginRequest])) { (tokenValue, request) => complete { service.login(request, tokenValue).map[ToResponseMarshallable] { case Right(response) => Created -> response case Left(errorMessage) => BadRequest -> errorMessage } } } ~ (path("generate" / "codecard") & pathEndOrSingleSlash & post & optionalHeaderValueByName("Auth-Token") & entity(as[GetCodeCardRequest])) { (tokenValue, request) => complete { service.getCodeCard(request, tokenValue).map[ToResponseMarshallable] { case Right(response) => OK -> response case Left(errorMessage) => BadRequest -> errorMessage } } } } }) }
Example 9
Source File: AuthPassword.scala From reactive-microservices with MIT License | 5 votes |
import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ import akka.http.scaladsl.marshalling.ToResponseMarshallable import akka.http.scaladsl.model.StatusCodes._ import akka.http.scaladsl.server.Directives._ import akka.stream.ActorFlowMaterializer case class PasswordRegisterRequest(email: EmailAddress, password: String) case class PasswordLoginRequest(email: EmailAddress, password: String) case class PasswordResetRequest(email: EmailAddress, newPassword: String) case class Identity(id: Long) case class Token(value: String, validTo: Long, identityId: Long, authMethods: Set[String]) object AuthPassword extends App with JsonProtocols with Config { implicit val actorSystem = ActorSystem() implicit val materializer = ActorFlowMaterializer() implicit val dispatcher = actorSystem.dispatcher val repository = new Repository val gateway = new Gateway val service = new Service(repository, gateway) Http().bindAndHandle(interface = interface, port = port, handler = { logRequestResult("auth-password") { path("register" / "password") { (pathEndOrSingleSlash & post & entity(as[PasswordRegisterRequest]) & optionalHeaderValueByName("Auth-Token")) { (request, tokenValue) => complete { service.register(request, tokenValue).map[ToResponseMarshallable] { case Right(identity) => Created -> identity case Left(errorMessage) => BadRequest -> errorMessage } } } } ~ path("login" / "password") { (pathEndOrSingleSlash & post & entity(as[PasswordLoginRequest]) & optionalHeaderValueByName("Auth-Token")) { (request, tokenValue) => complete { service.login(request, tokenValue).map[ToResponseMarshallable] { case Right(token) => Created -> token case Left(errorMessage) => BadRequest -> errorMessage } } } } ~ path("reset" / "password") { (pathEndOrSingleSlash & post & entity(as[PasswordResetRequest]) & headerValueByName("Auth-Token")) { (request, tokenValue) => complete { service.reset(request, tokenValue).map[ToResponseMarshallable] { case Right(identity) => OK -> identity case Left(errorMessage) => BadRequest -> errorMessage } } } } } }) }
Example 10
Source File: AuthFb.scala From reactive-microservices with MIT License | 5 votes |
import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ import akka.http.scaladsl.marshalling.ToResponseMarshallable import akka.http.scaladsl.model.StatusCodes._ import akka.http.scaladsl.server.Directives._ import akka.stream.ActorFlowMaterializer import com.restfb.exception.FacebookException import scala.util.{Failure => FailureT, Success => SuccessT} case class AuthResponse(accessToken: String) case class Identity(id: Long) case class Token(value: String, validTo: Long, identityId: Long, authMethods: Set[String]) object AuthFb extends App with JsonProtocols with Config { implicit val actorSystem = ActorSystem() implicit val materializer = ActorFlowMaterializer() implicit val dispatcher = actorSystem.dispatcher val gateway = new Gateway val service = new Service(gateway) Http().bindAndHandle(interface = interface, port = port, handler = { logRequestResult("auth-fb") { (path("register" / "fb") & pathEndOrSingleSlash & post & entity(as[AuthResponse]) & optionalHeaderValueByName("Auth-Token")) { (authResponse, tokenValue) => complete { service.register(authResponse, tokenValue) match { case SuccessT(f) => f.map[ToResponseMarshallable] { case Right(identity) => Created -> identity case Left(errorMessage) => BadRequest -> errorMessage } case FailureT(e: FacebookException) => Unauthorized -> e.getMessage case _ => InternalServerError } } } ~ (path("login" / "fb") & pathEndOrSingleSlash & post & entity(as[AuthResponse]) & optionalHeaderValueByName("Auth-Token")) { (authResponse, tokenValue) => complete { service.login(authResponse, tokenValue) match { case SuccessT(f) => f.map[ToResponseMarshallable] { case Right(token) => Created -> token case Left(errorMessage) => BadRequest -> errorMessage } case FailureT(e: FacebookException) => Unauthorized -> e.getMessage case _ => InternalServerError } } } } }) }
Example 11
Source File: TokenManager.scala From reactive-microservices with MIT License | 5 votes |
import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ import akka.http.scaladsl.marshalling.ToResponseMarshallable import akka.http.scaladsl.model.StatusCodes._ import akka.http.scaladsl.server.Directives._ import akka.stream.ActorFlowMaterializer import metrics.common.{Value, RequestResponseStats, Counter, Metrics} import metrics.common.MetricsDirectives._ case class LoginRequest(identityId: Long, authMethod: String) case class ReloginRequest(tokenValue: String, authMethod: String) case class Token(value: String, validTo: Long, identityId: Long, authMethods: Set[String]) object TokenManager extends App with JsonProtocols with Config with Metrics { implicit val actorSystem = ActorSystem() implicit val materializer = ActorFlowMaterializer() implicit val dispatcher = actorSystem.dispatcher val repository = new Repository val service = new Service(repository) def putMetricForRequestResponse(requestStats: RequestResponseStats): Unit = { val method = requestStats.request.method.name.toLowerCase putMetric(Value(s"token-manager.$method.time", requestStats.time)) } Http().bindAndHandle(interface = interface, port = port, handler = { (measureRequestResponse(putMetricForRequestResponse) & logRequestResult("token-manager")) { pathPrefix("tokens") { (post & pathEndOrSingleSlash & entity(as[LoginRequest])) { loginRequest => complete { putMetric(Counter("token-manager.post", 1)) service.login(loginRequest).map(token => Created -> token) } } ~ (patch & pathEndOrSingleSlash & entity(as[ReloginRequest])) { reloginRequest => complete { service.relogin(reloginRequest).map[ToResponseMarshallable] { case Some(token) => putMetric(Counter("token-manager.patch", 1)) OK -> token case None => putMetric(Counter("token-manager.patch", -1)) NotFound -> "Token expired or not found" } } } ~ (path(Segment) & pathEndOrSingleSlash) { tokenValue => get { complete { service.findAndRefreshToken(tokenValue).map[ToResponseMarshallable] { case Some(token) => putMetric(Counter("token-manager.get", 1)) OK -> token case None => putMetric(Counter("token-manager.get", -1)) NotFound -> "Token expired or not found" } } } ~ delete { complete { service.logout(tokenValue) putMetric(Counter("token-manager.delete", 1)) OK } } } } } }) }
Example 12
Source File: ResponseFactory.scala From akka-http-circe-json-template with Apache License 2.0 | 5 votes |
package com.vitorsvieira.http.routes import akka.http.scaladsl.marshalling.ToResponseMarshallable import akka.http.scaladsl.model.StatusCodes._ import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server._ import com.vitorsvieira.http.config.ServerSettingsTemplate import com.vitorsvieira.http.model.{ ApiMessage, ApiStatusMessages } import de.heikoseeberger.akkahttpcirce.CirceSupport._ import scala.concurrent.Future import scala.util.{ Failure, Success } trait ResponseFactory { import ServerSettingsTemplate._ import io.circe.generic.auto._ def sendResponse[T](eventualResult: Future[T])(implicit marshaller: T ⇒ ToResponseMarshallable): Route = { onComplete(eventualResult) { case Success(result) ⇒ complete(result) case Failure(e) ⇒ log.error(s"Error: ${e.toString}") complete(ToResponseMarshallable(InternalServerError → ApiMessage(ApiStatusMessages.unknownException))) } } }
Example 13
Source File: TimeLimitedRoute.scala From Waves with MIT License | 5 votes |
package com.wavesplatform.api.http import akka.http.scaladsl.marshalling.ToResponseMarshallable import akka.http.scaladsl.server.{Directive1, ExceptionHandler, Route} import com.google.common.util.concurrent.{ExecutionError, UncheckedExecutionException} import com.wavesplatform.utils.Schedulers import monix.execution.Scheduler import scala.concurrent.ExecutionException trait TimeLimitedRoute { self: ApiRoute => def limitedScheduler: Scheduler def executeLimited[T](f: => T): Directive1[T] = { val handler = ExceptionHandler { case _: InterruptedException | _: ExecutionException | _: ExecutionError | _: UncheckedExecutionException => complete(ApiError.CustomValidationError("The request took too long to complete")) } handleExceptions(handler) & onSuccess(Schedulers.executeCatchingInterruptedException(limitedScheduler)(f)) } def completeLimited(f: => ToResponseMarshallable): Route = executeLimited(f)(complete(_)) }
Example 14
Source File: BroadcastRoute.scala From Waves with MIT License | 5 votes |
package com.wavesplatform.http import akka.http.scaladsl.marshalling.ToResponseMarshallable import akka.http.scaladsl.server.Route import cats.syntax.either._ import com.wavesplatform.api.http.{ApiError, ApiRoute, jsonParammedPost} import com.wavesplatform.lang.ValidationError import com.wavesplatform.network._ import com.wavesplatform.transaction.Transaction import play.api.libs.json._ trait BroadcastRoute { _: ApiRoute => def utxPoolSynchronizer: UtxPoolSynchronizer def broadcast[A: Reads](f: A => Either[ValidationError, Transaction]): Route = jsonParammedPost[A] { (a, params) => f(a).fold[ToResponseMarshallable]( ApiError.fromValidationError, tx => { val p = utxPoolSynchronizer.publish(tx) p.transformE(r => r.bimap(ApiError.fromValidationError, t => tx.json() ++ params.get("trace").fold(Json.obj())(_ => Json.obj("trace" -> p.trace.map(_.loggedJson))))) } ) } }
Example 15
Source File: AuthenticationRouter.scala From akka-http-rest-api with MIT License | 5 votes |
package authentication import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ import akka.http.scaladsl.marshalling.ToResponseMarshallable import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.Route import core.{StatusWrapper, ErrorWrapper, BaseRoute} import akka.http.scaladsl.model.StatusCodes trait AuthenticationRouter extends BaseRoute { import UserAuthJsonProtocol._ import core.CommonJsonProtocol._ def userAuthService: UserAuthService val authenticationRoutes: Route = { pathPrefix("auth") { (path("register") & pathEnd & post & entity(as[UserRegistrationRequest])) { request => complete { userAuthService.register(request).map[ToResponseMarshallable] { case UserAuthResult.InvalidData(msg) => StatusCodes.BadRequest -> ErrorWrapper("invalidData", msg) case UserAuthResult.UserExists(msg) => StatusCodes.Conflict -> ErrorWrapper("userExists", msg) case UserAuthResult.Success(token) => StatusCodes.Created -> StatusWrapper("OK", Some(token)) } } } ~ (path("login") & pathEnd & post & entity(as[UserLoginRequest])) { request => complete { userAuthService.login(request).map[ToResponseMarshallable] { case UserAuthResult.InvalidData(msg) => StatusCodes.BadRequest -> ErrorWrapper("invalidData", msg) case UserAuthResult.UserNotExists(msg) => StatusCodes.BadRequest -> ErrorWrapper("userNotExists", msg) case UserAuthResult.Success(token) => StatusCodes.OK -> StatusWrapper("OK", Some(token)) } } } } } }
Example 16
Source File: UserRouter.scala From akka-http-rest-api with MIT License | 5 votes |
package user import akka.http.scaladsl.marshalling.ToResponseMarshallable import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.Route import core.authorization.{WithPermissionRejections, Permission} import core.{ErrorWrapper, StatusWrapper, BaseRoute} import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ import core.authentication.{Identity, TokenAuthenticator} trait UserRouter extends TokenAuthenticator with Permission with WithPermissionRejections with BaseRoute { import UserJsonProtocol._ import core.CommonJsonProtocol._ def userService: UserService val userRoutes: Route = { pathPrefix("users") { authenticate(executor, redis) { identity => (path("me") & pathEnd & get) { complete { userService.getUser(identity.user.id).map[ToResponseMarshallable] { case Left(msg) => StatusCodes.NotFound -> ErrorWrapper("invalidData", msg) case Right(user) => StatusCodes.OK -> user } } } ~ (path("me") & pathEnd & put & entity(as[UserUpdateRequest])) { request => complete { userService.updateLoggedUser(identity, request).map[ToResponseMarshallable] { _ => StatusCodes.OK -> StatusWrapper() } } } ~ (pathEnd & get & parameters('offset.as[Long], 'limit.as[Int] ? 20)) { (offset, limit) => complete { userService.getUsers(offset, limit).map[ToResponseMarshallable] { usersResponse => StatusCodes.OK -> usersResponse } } } ~ (path(LongNumber) & pathEnd & get) { id => complete { userService.getUser(id).map[ToResponseMarshallable] { case Left(msg) => StatusCodes.NotFound -> ErrorWrapper("invalidData", msg) case Right(user) => StatusCodes.OK -> user } } } ~ (path(LongNumber) & pathEnd & delete & handleRejections(permissionRejectionHandlers) & authorize(hasPermission(identity))) { id => complete { userService.deleteUser(id).map[ToResponseMarshallable] { case Left(msg) => StatusCodes.NotFound -> ErrorWrapper("invalidData", msg) case Right(_) => StatusCodes.OK -> StatusWrapper() } } } ~ (path(LongNumber / "role") & pathEnd & patch & handleRejections(permissionRejectionHandlers) & authorize(hasPermission(identity)) & entity(as[UserRoleUpdateRequest])) { (id, request) => complete { userService.updateRole(id, identity, request).map[ToResponseMarshallable] { case Left(msg) => StatusCodes.NotFound -> ErrorWrapper("invalidData", msg) case Right(_) => StatusCodes.OK -> StatusWrapper() } } } } } } def hasPermission(identity: Identity): () => Boolean = () => identity.user.role == 1 }