akka.http.scaladsl.model.StatusCode Scala Examples
The following examples show how to use akka.http.scaladsl.model.StatusCode.
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: AuditLogProvider.scala From rokku with Apache License 2.0 | 5 votes |
package com.ing.wbaa.rokku.proxy.provider import akka.Done import akka.http.scaladsl.model.{ HttpRequest, StatusCode } import com.ing.wbaa.rokku.proxy.data.{ AWSMessageEventJsonSupport, RequestId, S3Request } import com.ing.wbaa.rokku.proxy.handler.parsers.RequestParser.AWSRequestType import com.ing.wbaa.rokku.proxy.provider.aws.s3ObjectAudit import com.ing.wbaa.rokku.proxy.provider.kafka.EventProducer import com.typesafe.config.ConfigFactory import scala.concurrent.Future trait AuditLogProvider extends EventProducer with AWSMessageEventJsonSupport { protected[this] def auditEnabled: Boolean = ConfigFactory.load().getBoolean("rokku.auditEnable") def auditLog(s3Request: S3Request, httpRequest: HttpRequest, user: String, awsRequest: AWSRequestType, responseStatus: StatusCode)(implicit id: RequestId): Future[Done] = { if (auditEnabled) { prepareAWSMessage(s3Request, httpRequest.method, user, s3Request.userIps, s3ObjectAudit(httpRequest.method.value), id, responseStatus, awsRequest) .map(jse => sendSingleMessage(jse.toString(), kafkaSettings.auditEventsTopic)) .getOrElse(Future(Done)) } else { Future(Done) } } }
Example 2
Source File: package.scala From akka-cluster-manager with MIT License | 5 votes |
package io.orkestra.cluster import akka.actor.ActorRef import akka.http.scaladsl.model.{StatusCodes, StatusCode} import play.api.libs.json.{JsString, Format, Json, JsValue} package object protocol { case class Register(member: ActorRef, role: String) case class RegisterInternal(member: ActorRef, role: String) sealed trait Response { def asJson: JsValue def httpStatusCode: StatusCode } object Response { trait Success extends Response { override val httpStatusCode: StatusCode = StatusCodes.OK } object Success { case class Router(name: String, routees: List[String]) extends Success { override val asJson = Json.toJson(this) } object Router { implicit val fmt: Format[Router] = Json.format[Router] } case class Routers(routers: Iterable[JsValue]) extends Success { override val asJson = Json.toJson(routers) } case class RouteeDeleted(role: String, path: String) extends Success { override val asJson = JsString(s"routee: $path with role: $role successfully deleted") } } trait Failure extends Response object Failure { case class RouterNotFound(role: String) extends Failure { override val httpStatusCode: StatusCode = StatusCodes.NotFound override val asJson: JsValue = Json.obj("error" -> s"router with role: $role not found") } } } }
Example 3
Source File: TwitterException.scala From twitter4s with Apache License 2.0 | 5 votes |
package com.danielasfregola.twitter4s.exceptions import akka.http.scaladsl.model.StatusCode final case class TwitterError(message: String, code: Int) { override def toString = s"$message ($code)" } final case class Errors(errors: TwitterError*) { override def toString = errors.mkString(", ") } object Errors { def apply(throwable: Throwable): Errors = { val error = TwitterError(throwable.getMessage, code = -1) apply(error) } def apply(msg: String): Errors = { val error = TwitterError(msg, code = -1) apply(error) } } final case class TwitterException(code: StatusCode, errors: Errors) extends Exception(s"[$code] $errors") object TwitterException { def apply(code: StatusCode, msg: String): TwitterException = { val error = TwitterError(msg, code.intValue) TwitterException(code, Errors(error)) } }
Example 4
Source File: PropertiesApiSuite.scala From iep-apps with Apache License 2.0 | 5 votes |
package com.netflix.iep.archaius import java.io.StringReader import java.util.Properties import akka.http.scaladsl.model.HttpResponse import akka.http.scaladsl.model.MediaTypes import akka.http.scaladsl.model.StatusCode import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.model.headers._ import akka.http.scaladsl.testkit.RouteTestTimeout import akka.http.scaladsl.testkit.ScalatestRouteTest import com.netflix.atlas.akka.RequestHandler import com.netflix.atlas.json.Json import com.netflix.spectator.api.DefaultRegistry import com.netflix.spectator.api.ManualClock import org.scalatest.funsuite.AnyFunSuite class PropertiesApiSuite extends AnyFunSuite with ScalatestRouteTest { import scala.concurrent.duration._ implicit val routeTestTimeout = RouteTestTimeout(5.second) val clock = new ManualClock() val registry = new DefaultRegistry(clock) val propContext = new PropertiesContext(registry) val endpoint = new PropertiesApi(propContext, system) val routes = RequestHandler.standardOptions(endpoint.routes) private def assertJsonContentType(response: HttpResponse): Unit = { assert(response.entity.contentType.mediaType === MediaTypes.`application/json`) } private def assertResponse(response: HttpResponse, expected: StatusCode): Unit = { assert(response.status === expected) assertJsonContentType(response) } test("no asg") { Get("/api/v1/property") ~> routes ~> check { assert(response.status === StatusCodes.BadRequest) } } test("empty") { propContext.update(Nil) Get("/api/v1/property?asg=foo-main-v001") ~> addHeader(Accept(MediaTypes.`application/json`)) ~> routes ~> check { assertResponse(response, StatusCodes.OK) assert(responseAs[String] === "[]") } } test("properties response") { propContext.update( List( PropertiesApi.Property("foo-main::a", "foo-main", "a", "b", 12345L), PropertiesApi.Property("foo-main::1", "foo-main", "1", "2", 12345L), PropertiesApi.Property("bar-main::c", "bar-main", "c", "d", 12345L) ) ) Get("/api/v1/property?asg=foo-main-v001") ~> routes ~> check { assert(response.status === StatusCodes.OK) val props = new Properties props.load(new StringReader(responseAs[String])) assert(props.size === 2) assert(props.getProperty("a") === "b") assert(props.getProperty("1") === "2") } } test("json response") { propContext.update( List( PropertiesApi.Property("foo-main::a", "foo-main", "a", "b", 12345L) ) ) Get("/api/v1/property?asg=foo-main-v001") ~> addHeader(Accept(MediaTypes.`application/json`)) ~> routes ~> check { assertResponse(response, StatusCodes.OK) val props = Json.decode[List[PropertiesApi.Property]](responseAs[String]) assert(props === List(PropertiesApi.Property("foo-main::a", "foo-main", "a", "b", 12345L))) } } }
Example 5
Source File: StatsApiSuite.scala From iep-apps with Apache License 2.0 | 5 votes |
package com.netflix.iep.lwc import akka.http.scaladsl.model.HttpResponse import akka.http.scaladsl.model.MediaTypes import akka.http.scaladsl.model.StatusCode import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.testkit.RouteTestTimeout import akka.http.scaladsl.testkit.ScalatestRouteTest import com.netflix.atlas.akka.RequestHandler import com.netflix.atlas.core.model.Datapoint import com.netflix.atlas.json.Json import com.netflix.spectator.atlas.impl.Subscription import com.typesafe.config.ConfigFactory import org.scalatest.BeforeAndAfter import org.scalatest.funsuite.AnyFunSuite class StatsApiSuite extends AnyFunSuite with ScalatestRouteTest with BeforeAndAfter { import scala.jdk.CollectionConverters._ import scala.concurrent.duration._ private implicit val routeTestTimeout = RouteTestTimeout(5.second) private val config = ConfigFactory.load() private val evaluator = new ExpressionsEvaluator(config) private val endpoint = new StatsApi(evaluator) private val routes = RequestHandler.standardOptions(endpoint.routes) private def assertJsonContentType(response: HttpResponse): Unit = { assert(response.entity.contentType.mediaType === MediaTypes.`application/json`) } private def assertResponse(response: HttpResponse, expected: StatusCode): Unit = { assert(response.status === expected) assertJsonContentType(response) } before { evaluator.clear() } test("empty") { Get("/api/v1/stats") ~> routes ~> check { assertResponse(response, StatusCodes.OK) assert(responseAs[String] === "[]") } } test("has data") { // Add sample subscription val subs = List( new Subscription() .withId("1") .withExpression("name,ssCpuUser,:eq,:sum"), new Subscription() .withId("2") .withExpression("name,ssCpuSystem,:eq,:sum") ) evaluator.sync(subs.asJava) // Stats only get updated when data is sent val datapoints = List( Datapoint(Map("name" -> "ssCpuUser", "node" -> "i-1"), 60000, 42.0), Datapoint(Map("name" -> "ssCpuUser", "node" -> "i-2"), 60000, 44.0) ) evaluator.eval(60000, datapoints) // Query the data Get("/api/v1/stats") ~> routes ~> check { assertResponse(response, StatusCodes.OK) val stats = Json.decode[List[ExpressionsEvaluator.SubscriptionStats]](responseAs[String]) assert(stats.length === 1) assert(stats.head.updateCount.get() === 2) } } }
Example 6
Source File: UpdateApi.scala From iep-apps with Apache License 2.0 | 5 votes |
package com.netflix.atlas.aggregator import javax.inject.Inject import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.model.HttpEntity import akka.http.scaladsl.model.HttpResponse import akka.http.scaladsl.model.MediaTypes import akka.http.scaladsl.model.StatusCode import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.server.Route import com.fasterxml.jackson.core.JsonParser import com.netflix.atlas.akka.CustomDirectives._ import com.netflix.atlas.akka.WebApi import com.netflix.atlas.core.validation.ValidationResult import com.netflix.atlas.eval.stream.Evaluator import com.typesafe.scalalogging.StrictLogging class UpdateApi @Inject()( evaluator: Evaluator, aggrService: AtlasAggregatorService ) extends WebApi with StrictLogging { import UpdateApi._ require(aggrService != null, "no binding for aggregate registry") def routes: Route = { endpointPath("api" / "v4" / "update") { post { parseEntity(customJson(p => processPayload(p, aggrService))) { response => complete(response) } } } } } object UpdateApi { private val decoder = PayloadDecoder.default private[aggregator] def processPayload( parser: JsonParser, service: AtlasAggregatorService ): HttpResponse = { val result = decoder.decode(parser, service) createResponse(result.numDatapoints, result.failures) } private val okResponse = { val entity = HttpEntity(MediaTypes.`application/json`, "{}") HttpResponse(StatusCodes.OK, entity = entity) } private def createErrorResponse(status: StatusCode, msg: FailureMessage): HttpResponse = { val entity = HttpEntity(MediaTypes.`application/json`, msg.toJson) HttpResponse(status, entity = entity) } private def createResponse(numDatapoints: Int, failures: List[ValidationResult]): HttpResponse = { if (failures.isEmpty) { okResponse } else { val numFailures = failures.size if (numDatapoints > numFailures) { // Partial failure val msg = FailureMessage.partial(failures, numFailures) createErrorResponse(StatusCodes.Accepted, msg) } else { // All datapoints dropped val msg = FailureMessage.error(failures, numFailures) createErrorResponse(StatusCodes.BadRequest, msg) } } } }
Example 7
Source File: KgClientError.scala From nexus-kg with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.client import akka.http.scaladsl.model.StatusCode import scala.reflect.ClassTag @SuppressWarnings(Array("IncorrectlyNamedExceptions")) sealed abstract class KgClientError(val message: String) extends Exception { override def fillInStackTrace(): KgClientError = this override val getMessage: String = message } @SuppressWarnings(Array("IncorrectlyNamedExceptions")) object KgClientError { final case class UnmarshallingError[A](reason: String)(implicit A: ClassTag[A]) extends KgClientError( s"Unable to parse or decode the response from Kg to a '${A.runtimeClass.getSimpleName}' due to '$reason'." ) final case class NotFound(entityAsString: String) extends KgClientError("The resource does not exist") final case class UnknownError(status: StatusCode, entityAsString: String) extends KgClientError("The request did not complete successfully.") }
Example 8
Source File: package.scala From nexus-kg with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg import akka.http.scaladsl.model.StatusCode import akka.http.scaladsl.server.Directives.complete import akka.http.scaladsl.server.{MalformedQueryParamRejection, Route} import cats.Functor import cats.data.{EitherT, OptionT} import cats.instances.future._ import ch.epfl.bluebrain.nexus.iam.client.types._ import ch.epfl.bluebrain.nexus.kg.marshallers.instances._ import ch.epfl.bluebrain.nexus.kg.resources.Rejection.NotFound.notFound import ch.epfl.bluebrain.nexus.kg.resources.{Ref, Rejection, ResourceV} import ch.epfl.bluebrain.nexus.kg.routes.OutputFormat.{DOT, Triples} import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri import monix.execution.Scheduler.Implicits.global import scala.concurrent.Future package object routes { private[routes] def completeWithFormat( fetched: Future[Either[Rejection, (StatusCode, ResourceV)]] )(implicit format: NonBinaryOutputFormat): Route = completeWithFormat(EitherT(fetched)) private def completeWithFormat( fetched: EitherT[Future, Rejection, (StatusCode, ResourceV)] )(implicit format: NonBinaryOutputFormat): Route = format match { case f: JsonLDOutputFormat => implicit val format = f complete(fetched.value) case Triples => implicit val format = Triples complete(fetched.map { case (status, resource) => status -> resource.value.graph.ntriples }.value) case DOT => implicit val format = DOT complete(fetched.map { case (status, resource) => status -> resource.value.graph.dot() }.value) } private[routes] val read: Permission = Permission.unsafe("resources/read") private[routes] val schemaError = MalformedQueryParamRejection("schema", "The provided schema does not match the schema on the Uri") private[routes] implicit class FOptionSyntax[F[_], A](private val fOpt: F[Option[A]]) extends AnyVal { def toNotFound(id: AbsoluteIri)(implicit F: Functor[F]): EitherT[F, Rejection, A] = OptionT(fOpt).toRight(notFound(Ref(id))) } }
Example 9
Source File: HttpApiHandlers.scala From vamp with Apache License 2.0 | 5 votes |
package io.vamp.common.http import akka.http.scaladsl.model.StatusCodes._ import akka.http.scaladsl.model.{ ExceptionWithErrorInfo, StatusCode } import akka.http.scaladsl.server._ import com.typesafe.scalalogging.Logger import io.vamp.common.notification.NotificationErrorException import org.slf4j.LoggerFactory trait HttpApiHandlers { this: HttpApiDirectives ⇒ private val logger = Logger(LoggerFactory.getLogger(getClass)) implicit def exceptionHandler: ExceptionHandler = ExceptionHandler { case e: NotificationErrorException ⇒ respondWithError(BadRequest, s"${e.message}") case e: Exception ⇒ extractUri { uri ⇒ logger.error("Request to {} could not be handled normally: {}", uri, e.getMessage) e match { case _: ExceptionWithErrorInfo ⇒ respondWithError(BadRequest) case _ ⇒ respondWithError(InternalServerError) } } } implicit def rejectionHandler: RejectionHandler = RejectionHandler.newBuilder() .handle { case MalformedRequestContentRejection(message, e: NotificationErrorException) ⇒ respondWithError(BadRequest, s"$message") } .handle { case MalformedRequestContentRejection(message, ex) ⇒ logger.error(ex.getMessage) respondWithError(BadRequest) } .handle { case MalformedRequestContentRejection(message, _) ⇒ respondWithError(BadRequest) } .handle { case MalformedHeaderRejection(_, message, _) ⇒ respondWithError(BadRequest, s"$message") } .handle { case ValidationRejection(message, _) ⇒ respondWithError(BadRequest, s"$message") } .result().withFallback(RejectionHandler.default) private def respondWithError(status: StatusCode, message: String = "") = { logger.warn("There has been an error with status code {} with message {}", status.value, message) respondWith( status = status, response = "message" → (if (status == InternalServerError) "Internal server error." else message) ) } }
Example 10
Source File: IamClientError.scala From nexus-iam with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.iam.client import akka.http.scaladsl.model.StatusCode import scala.reflect.ClassTag @SuppressWarnings(Array("IncorrectlyNamedExceptions")) sealed abstract class IamClientError(val message: String) extends Exception { override def fillInStackTrace(): IamClientError = this override val getMessage: String = message } @SuppressWarnings(Array("IncorrectlyNamedExceptions")) object IamClientError { final case class Unauthorized(entityAsString: String) extends IamClientError("The request did not complete successfully due to an invalid authentication method.") final case class Forbidden(entityAsString: String) extends IamClientError("The request did not complete successfully due to lack of access to the resource.") final case class UnmarshallingError[A: ClassTag](reason: String) extends IamClientError( s"Unable to parse or decode the response from IAM to a '${implicitly[ClassTag[A]]}' due to '$reason'." ) final case class UnknownError(status: StatusCode, entityAsString: String) extends IamClientError("The request did not complete successfully.") }
Example 11
Source File: Failover2Spec.scala From affinity with Apache License 2.0 | 5 votes |
package io.amient.affinity.core.cluster import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicInteger import akka.http.scaladsl.model.HttpMethods._ import akka.http.scaladsl.model.StatusCode import akka.http.scaladsl.model.StatusCodes.SeeOther import com.typesafe.config.ConfigValueFactory import io.amient.affinity.Conf import io.amient.affinity.core.util.AffinityTestBase import io.amient.affinity.kafka.EmbeddedKafka import org.scalatest.{FlatSpec, Matchers} import scala.collection.JavaConverters._ import scala.concurrent.duration._ import scala.concurrent.{Await, Future} import scala.language.postfixOps import scala.util.{Failure, Random, Success, Try} class Failover2Spec extends FlatSpec with AffinityTestBase with EmbeddedKafka with Matchers { val specTimeout = 15 seconds override def numPartitions = 2 def config = configure("failoverspecs", Some(zkConnect), Some(kafkaBootstrap)) val node1 = new Node(config.withValue(Conf.Affi.Node.Gateway.Class.path, ConfigValueFactory.fromAnyRef(classOf[FailoverTestGateway].getName))) val node2 = new Node(config.withValue(Conf.Affi.Node.Containers("keyspace1").path, ConfigValueFactory.fromIterable(List(0,1).asJava))) val node3 = new Node(config.withValue(Conf.Affi.Node.Containers("keyspace1").path, ConfigValueFactory.fromIterable(List(0,1).asJava))) override def beforeAll(): Unit = try { node1.start() node2.start() node3.start() node1.awaitClusterReady() } finally { super.beforeAll() } override def afterAll(): Unit = try { node1.shutdown() node2.shutdown() node3.shutdown() } finally { super.afterAll() } "Master Transition" should "not lead to inconsistent state" in { val requestCount = new AtomicInteger(0) val expected = new ConcurrentHashMap[String, String]() import scala.concurrent.ExecutionContext.Implicits.global val random = new Random() val requests = scala.collection.mutable.ListBuffer[Future[Try[StatusCode]]]() for (i <- (1 to 250)) { val key = random.nextInt.toString val value = random.nextInt.toString requests += node1.http(POST, s"/$key/$value") map { case response => expected.put(key, value) if (i == 25) { //after a few writes have succeeded kill one node node2.shutdown() } Success(response.status) } recover { case e: Throwable => Failure(e) } } requestCount.set(requests.size) Await.result(Future.sequence(requests), specTimeout).foreach(_ should be(Success(SeeOther))) println(s"${requests.size} successful requests") expected.asScala.foreach { case (key, value) => val (status, entity) = Await.result(node1.http(GET, s"/$key").map { response => (response.status, response.entity)}, specTimeout / 3) status.intValue should be (200) val expectedEntity = jsonStringEntity(value) entity should be(expectedEntity) } } }
Example 12
Source File: KgClientError.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.client import akka.http.scaladsl.model.StatusCode import scala.reflect.ClassTag @SuppressWarnings(Array("IncorrectlyNamedExceptions")) sealed abstract class KgClientError(val message: String) extends Exception { override def fillInStackTrace(): KgClientError = this override val getMessage: String = message } @SuppressWarnings(Array("IncorrectlyNamedExceptions")) object KgClientError { final case class UnmarshallingError[A](reason: String)(implicit A: ClassTag[A]) extends KgClientError( s"Unable to parse or decode the response from Kg to a '${A.runtimeClass.getSimpleName}' due to '$reason'." ) final case class NotFound(entityAsString: String) extends KgClientError("The resource does not exist") final case class UnknownError(status: StatusCode, entityAsString: String) extends KgClientError("The request did not complete successfully.") }
Example 13
Source File: package.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg import akka.http.scaladsl.model.StatusCode import akka.http.scaladsl.server.Directives.complete import akka.http.scaladsl.server.{MalformedQueryParamRejection, Route} import cats.Functor import cats.data.{EitherT, OptionT} import cats.instances.future._ import ch.epfl.bluebrain.nexus.iam.types.Permission import ch.epfl.bluebrain.nexus.kg.marshallers.instances._ import ch.epfl.bluebrain.nexus.kg.resources.Rejection.NotFound.notFound import ch.epfl.bluebrain.nexus.kg.resources.{Ref, Rejection, ResourceV} import ch.epfl.bluebrain.nexus.kg.routes.OutputFormat.{DOT, Triples} import ch.epfl.bluebrain.nexus.rdf.Iri.AbsoluteIri import monix.execution.Scheduler.Implicits.global import scala.concurrent.Future package object routes { private[routes] def completeWithFormat( fetched: Future[Either[Rejection, (StatusCode, ResourceV)]] )(implicit format: NonBinaryOutputFormat): Route = completeWithFormat(EitherT(fetched)) private def completeWithFormat( fetched: EitherT[Future, Rejection, (StatusCode, ResourceV)] )(implicit format: NonBinaryOutputFormat): Route = format match { case f: JsonLDOutputFormat => implicit val format = f complete(fetched.value) case Triples => implicit val format = Triples complete(fetched.map { case (status, resource) => status -> resource.value.graph.ntriples }.value) case DOT => implicit val format = DOT complete(fetched.map { case (status, resource) => status -> resource.value.graph.dot() }.value) } private[routes] val read: Permission = Permission.unsafe("resources/read") private[routes] val schemaError = MalformedQueryParamRejection("schema", "The provided schema does not match the schema on the Uri") implicit private[routes] class FOptionSyntax[F[_], A](private val fOpt: F[Option[A]]) extends AnyVal { def toNotFound(id: AbsoluteIri)(implicit F: Functor[F]): EitherT[F, Rejection, A] = OptionT(fOpt).toRight(notFound(Ref(id))) } }
Example 14
Source File: ElasticSearchBaseClient.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.commons.es.client import akka.http.scaladsl.model.StatusCodes.GatewayTimeout import akka.http.scaladsl.model.{HttpRequest, StatusCode, StatusCodes} import cats.effect.{Effect, Timer} import cats.implicits._ import ch.epfl.bluebrain.nexus.commons.es.client.ElasticSearchBaseClient._ import ch.epfl.bluebrain.nexus.commons.es.client.ElasticSearchFailure.{ElasticServerError, ElasticUnexpectedError} import ch.epfl.bluebrain.nexus.commons.http.HttpClient.UntypedHttpClient import ch.epfl.bluebrain.nexus.sourcing.RetryStrategyConfig import com.typesafe.scalalogging.Logger import retry.CatsEffect._ import retry.syntax.all._ import retry.{RetryDetails, RetryPolicy} import scala.util.control.NonFatal private[client] def sanitize(index: String, allowWildCard: Boolean): String = { val regex = if (allowWildCard) """[\s|"|\\|<|>|\||,|/|?]""" else """[\s|"|*|\\|<|>|\||,|/|?]""" index.replaceAll(regex, "_").dropWhile(_ == '_') } } object ElasticSearchBaseClient { private[client] val docType = "_doc" private[client] val source = "_source" private[client] val anyIndexPath = "_all" private[client] val ignoreUnavailable = "ignore_unavailable" private[client] val allowNoIndices = "allow_no_indices" private[client] val trackTotalHits = "track_total_hits" }
Example 15
Source File: GraphQLHandler.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.navigator import akka.actor.ActorRef import akka.http.scaladsl.model.StatusCode import akka.http.scaladsl.model.StatusCodes._ import com.daml.navigator.graphql._ import com.daml.navigator.graphql.SprayMarshallers._ import com.daml.navigator.model.PartyState import com.daml.navigator.store.Store.StoreException import com.typesafe.scalalogging.LazyLogging import sangria.ast.Document import sangria.execution._ import sangria.parser.QueryParser import sangria.renderer.SchemaRenderer import sangria.schema.Schema import spray.json._ import scala.concurrent.{ExecutionContext, Future} import scala.util.Try case class ParseResult(ast: Document, operationName: Option[String], variables: JsValue) trait GraphQLHandler { def schema: Schema[GraphQLContext, Unit] def parse(request: String): Try[ParseResult] def parse(request: JsValue): Try[ParseResult] def executeQuery(parsed: ParseResult, party: PartyState): Future[(StatusCode, JsValue)] def renderSchema: String } object GraphQLHandler { type ParseQuery = JsValue => Try[ParseResult] type ExecuteQuery = (ParseResult, PartyState) => Future[(StatusCode, JsValue)] type CustomEndpoints = Set[CustomEndpoint[_]] } case class DefaultGraphQLHandler( customEndpoints: GraphQLHandler.CustomEndpoints, platformStore: Option[ActorRef])( implicit executionContext: ExecutionContext ) extends GraphQLHandler with LazyLogging { def schema: Schema[GraphQLContext, Unit] = new GraphQLSchema(customEndpoints).QuerySchema def parse(request: String): Try[ParseResult] = Try(request.parseJson).flatMap(parse) def parse(request: JsValue): Try[ParseResult] = for { fields <- Try(request.asJsObject.fields) JsString(query) <- Try(fields("query")) operationName = fields.get("operationName").collect { case JsString(value) => value } vars: JsValue = fields.get("variables") match { case Some(obj: JsObject) => obj case _ => JsObject.empty } ast <- QueryParser.parse(query) } yield ParseResult(ast, operationName, vars) def executeQuery(parsed: ParseResult, party: PartyState): Future[(StatusCode, JsValue)] = { platformStore.fold[Future[(StatusCode, JsValue)]]( Future.successful(InternalServerError -> JsString("Platform store not available")) )(store => { val context = GraphQLContext(party, store) Executor .execute( schema, parsed.ast, context, variables = parsed.variables, operationName = parsed.operationName, exceptionHandler = ExceptionHandler { case (_, StoreException(message)) => HandledException(message) } ) .map(OK -> _) .recover { case error: QueryAnalysisError => logger.warn(s"GraphQL analysis error ${error.getMessage}.") BadRequest -> error.resolveError case error: ErrorWithResolver => logger.error("Failed to execute GraphQL query", error) InternalServerError -> error.resolveError } }) } def renderSchema: String = SchemaRenderer.renderSchema(schema) }
Example 16
Source File: AwsErrorCodes.scala From rokku with Apache License 2.0 | 5 votes |
package com.ing.wbaa.rokku.proxy.provider.aws import akka.http.scaladsl.model.{ StatusCode, StatusCodes } import com.ing.wbaa.rokku.proxy.data.RequestId import scala.xml.NodeSeq object AwsErrorCodes { val errors: Map[StatusCode, (String, String)] = Map( StatusCodes.Forbidden -> (("AccessDenied", "Access Denied")), StatusCodes.InternalServerError -> (("InternalServerError", "Internal Server Error")), StatusCodes.Unauthorized -> (("Unauthorized", "Unauthorized")), StatusCodes.TooManyRequests -> (("TooManyRequests", "Too Many Requests")), StatusCodes.ServiceUnavailable -> (("Throttling", "SLOW DOWN"))) def response(code: StatusCode, resource: String = "")(implicit requestId: RequestId = RequestId("")): NodeSeq = { val responseError = errors.getOrElse(code, ("Unexpected Error", "Unexpected Error")) <Error> <Code>{ responseError._1 }</Code> <Message>{ responseError._2 }</Message> <Resource>{ resource }</Resource> <RequestId>{ requestId.value }</RequestId> </Error> } }
Example 17
Source File: LoggerHandlerWithId.scala From rokku with Apache License 2.0 | 5 votes |
package com.ing.wbaa.rokku.proxy.handler import akka.http.scaladsl.model.{ StatusCode, StatusCodes } import com.ing.wbaa.rokku.proxy.data.RequestId import com.ing.wbaa.rokku.proxy.metrics.MetricsFactory import com.ing.wbaa.rokku.proxy.metrics.MetricsFactory._ import com.typesafe.scalalogging.Logger import org.slf4j.{ LoggerFactory, MDC } import scala.collection.mutable class LoggerHandlerWithId { @transient private lazy val log: Logger = Logger(LoggerFactory.getLogger(getClass.getName)) private val requestIdKey = "request.id" private val statusCodeKey = "request.statusCode" def debug(message: String, args: Any*)(implicit id: RequestId): Unit = { MDC.put(requestIdKey, id.value) MDC.put(statusCodeKey, "-") log.debug(message, args.asInstanceOf[mutable.WrappedArray[AnyRef]]: _*) MDC.remove(requestIdKey) MDC.remove(statusCodeKey) } def info(message: String, args: Any*)(implicit id: RequestId): Unit = { MDC.put(requestIdKey, id.value) MDC.put(statusCodeKey, "-") log.info(message, args.asInstanceOf[mutable.WrappedArray[AnyRef]]: _*) MDC.remove(requestIdKey) MDC.remove(statusCodeKey) } def warn(message: String, args: Any*)(implicit id: RequestId, statusCode: StatusCode = StatusCodes.Continue): Unit = { MDC.put(requestIdKey, id.value) MDC.put(statusCodeKey, statusCode.value) if (args.isInstanceOf[mutable.WrappedArray[_]]) log.warn(message, args.asInstanceOf[mutable.WrappedArray[AnyRef]]: _*) else log.warn(message, args.asInstanceOf[scala.collection.immutable.$colon$colon[AnyRef]]: _*) MDC.remove(requestIdKey) MDC.remove(statusCodeKey) } def error(message: String, args: Any*)(implicit id: RequestId, statusCode: StatusCode = StatusCodes.Continue): Unit = { MDC.put(requestIdKey, id.value) MDC.put(statusCodeKey, statusCode.value) countLogErrors(MetricsFactory.ERROR_REPORTED_TOTAL) if (args.isInstanceOf[mutable.WrappedArray[_]]) log.error(message, args.asInstanceOf[mutable.WrappedArray[AnyRef]]: _*) else log.error(message, args.asInstanceOf[scala.collection.immutable.$colon$colon[AnyRef]]: _*) MDC.remove(requestIdKey) MDC.remove(statusCodeKey) } }
Example 18
Source File: AWSMessageEvent.scala From rokku with Apache License 2.0 | 5 votes |
package com.ing.wbaa.rokku.proxy.data import java.time.Instant import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport import akka.http.scaladsl.model.{ HttpMethod, StatusCode } import com.ing.wbaa.rokku.proxy.handler.parsers.RequestParser.{ AWSRequestType, MultipartRequestType } import com.ing.wbaa.rokku.proxy.provider.aws.{ S3ObjectAction, s3MultipartUpload, s3MultipartUploadComplete } import spray.json.DefaultJsonProtocol case class Records(records: List[AWSMessageEvent]) case class UserIdentity(principalId: String) case class RequestParameters(sourceIPAddress: String) case class ResponseElements(`x-amz-request-id`: String, `x-amz-id-2`: String) case class OwnerIdentity(principalId: String) case class BucketProps(name: String, ownerIdentity: OwnerIdentity, arn: String) case class ObjectProps(key: String, size: Int, eTag: String, versionId: String, sequencer: String) case class S3(s3SchemaVersion: String, configurationId: String, bucket: BucketProps, `object`: ObjectProps) case class AWSMessageEvent( eventVersion: String, eventSource: String, awsRegion: String, eventTime: String, eventName: String, userIdentity: UserIdentity, requestParameters: RequestParameters, responseElements: ResponseElements, s3: S3 ) trait AWSMessageEventJsonSupport extends SprayJsonSupport with DefaultJsonProtocol { implicit val ownerIdentityFormat = jsonFormat1(OwnerIdentity) implicit val bucketFormat = jsonFormat3(BucketProps) implicit val objectPropsFormat = jsonFormat5(ObjectProps) implicit val s3Format = jsonFormat4(S3) implicit val userIdentityFormat = jsonFormat1(UserIdentity) implicit val requestParametersFormat = jsonFormat1(RequestParameters) implicit val responseElementsFormat = jsonFormat2(ResponseElements) implicit val AWSMessageEventFormat = jsonFormat9(AWSMessageEvent) implicit val recordsFormat = jsonFormat1(Records) import spray.json._ def prepareAWSMessage(s3Request: S3Request, method: HttpMethod, principalId: String, userIPs: UserIps, s3Action: S3ObjectAction, requestId: RequestId, responseStatus: StatusCode, awsRequest: AWSRequestType): Option[JsValue] = { val toMultipartRequest: AWSRequestType => Option[MultipartRequestType] = { case r: MultipartRequestType => Some(r) case _ => None } val uploadId: Option[String] = toMultipartRequest(awsRequest).map(_.uploadId) val multipartOrS3Action = toMultipartRequest(awsRequest) match { case Some(r) => if (r.completeMultipartUpload) s3MultipartUploadComplete(method.value) else s3MultipartUpload(method.value) case None => s3Action } for { bucketPath <- s3Request.s3BucketPath s3object <- s3Request.s3Object } yield Records(List(AWSMessageEvent( "2.1", "rokku:s3", "us-east-1", Instant.now().toString, multipartOrS3Action.value, UserIdentity(principalId), RequestParameters(userIPs.toString), ResponseElements(requestId.value, responseStatus.value), S3("1.0", "", BucketProps(bucketPath, OwnerIdentity(""), ""), ObjectProps(s3object, 0, "", "", uploadId.getOrElse(""))))) ).toJson } }
Example 19
Source File: ClickhouseException.scala From clickhouse-scala-client with GNU Lesser General Public License v3.0 | 5 votes |
package com.crobox.clickhouse import akka.http.scaladsl.model.StatusCode sealed abstract class ClickhouseExecutionException(msg: String, cause: Throwable = null) extends RuntimeException(msg, cause) { val retryable: Boolean } case class ClickhouseException(message: String, query: String, cause: Throwable = null, statusCode: StatusCode) extends ClickhouseExecutionException(message + s", query $query", cause) { override val retryable: Boolean = true } case class ClickhouseChunkedException(message: String) extends ClickhouseExecutionException(message) { override val retryable: Boolean = true } case class TooManyQueriesException() extends ClickhouseExecutionException( "The client's queue is full, you are trying to execute too many queries at the same time. This can be solved by either: checking the source of the queries to make sure this is not a bug\n Increasing the buffer size under the property `crobox.clickhouse.client.buffer-size`\n Adjust the settings of the super pool under `akka.http.host-connection-pool`" ) { override val retryable: Boolean = false }
Example 20
Source File: HydraJsonSupport.scala From hydra with Apache License 2.0 | 5 votes |
package hydra.core.marshallers import java.io.{PrintWriter, StringWriter} import java.util.UUID import akka.actor.ActorPath import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport import akka.http.scaladsl.model.StatusCode import hydra.common.util.Resource._ import org.joda.time.DateTime import org.joda.time.format.ISODateTimeFormat import spray.json.{JsString, _} import scala.util.{Failure, Success, Try} implicit def tryWriter[R: JsonWriter]: RootJsonWriter[Try[R]] = new RootJsonWriter[Try[R]] { override def write(responseTry: Try[R]): JsValue = { responseTry match { case Success(r) => JsObject("success" -> r.toJson) case Failure(t) => JsObject("failure" -> t.toJson) } } } implicit object StreamTypeFormat extends RootJsonFormat[StreamType] { def read(json: JsValue): StreamType = json match { case JsString("Notification") => Notification case JsString("History") => History case JsString("CurrentState") => CurrentState case JsString("Telemetry") => Telemetry case _ => { import scala.reflect.runtime.{universe => ru} val tpe = ru.typeOf[StreamType] val clazz = tpe.typeSymbol.asClass throw new DeserializationException( s"expected a streamType of ${clazz.knownDirectSubclasses}, but got $json" ) } } def write(obj: StreamType): JsValue = { JsString(obj.toString) } } implicit val genericErrorFormat = jsonFormat2(GenericError) implicit val topicCreationMetadataFormat = jsonFormat8(TopicMetadataRequest) implicit val genericSchemaFormat = jsonFormat2(GenericSchema) } case class GenericError(status: Int, errorMessage: String) case class TopicMetadataRequest( schema: JsObject, streamType: StreamType, derived: Boolean, deprecated: Option[Boolean], dataClassification: String, contact: String, additionalDocumentation: Option[String], notes: Option[String] ) case class GenericSchema(name: String, namespace: String) { def subject = s"$namespace.$name" } sealed trait StreamType case object Notification extends StreamType case object CurrentState extends StreamType case object History extends StreamType case object Telemetry extends StreamType
Example 21
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 22
Source File: IngestionHandler.scala From hydra with Apache License 2.0 | 5 votes |
package hydra.ingest.services import akka.actor.SupervisorStrategy.Stop import akka.actor.{Actor, ActorRef, OneForOneStrategy, ReceiveTimeout} import akka.http.scaladsl.model.{StatusCode, StatusCodes} import hydra.core.ingest.{HydraRequest, IngestionReport, RequestParams} import hydra.ingest.services.IngestorRegistry.{ FindAll, FindByName, LookupResult } import scala.concurrent.duration.FiniteDuration trait IngestionHandler { this: Actor => def timeout: FiniteDuration def request: HydraRequest //we require an actorref here for performance reasons def registry: ActorRef private val targetIngestor = request.metadataValue(RequestParams.HYDRA_INGESTOR_PARAM) targetIngestor match { case Some(ingestor) => registry ! FindByName(ingestor) case None => registry ! FindAll } override def receive: Receive = { case LookupResult(Nil) => val errorCode = targetIngestor .map(i => StatusCodes .custom(404, s"No ingestor named $i was found in the registry.") ) .getOrElse(StatusCodes.BadRequest) complete(errorWith(errorCode)) case LookupResult(ingestors) => context.actorOf( IngestionSupervisor.props(request, self, ingestors, timeout) ) case report: IngestionReport => complete(report) } override val supervisorStrategy = OneForOneStrategy() { case e: Exception => fail(e) Stop } private def errorWith(statusCode: StatusCode) = { IngestionReport(request.correlationId, Map.empty, statusCode.intValue()) } def complete(report: IngestionReport) def fail(e: Throwable) }
Example 23
Source File: ApiError.scala From EncryCore with GNU General Public License v3.0 | 5 votes |
package encry.api.http import akka.http.scaladsl.model.{StatusCode, StatusCodes} import akka.http.scaladsl.server.{Directives, Route} import scala.language.implicitConversions case class ApiError(statusCode: StatusCode, reason: String = "") { def apply(detail: String): Route = complete(detail) def defaultRoute: Route = complete() def complete(detail: String = ""): Route = { val nonEmptyReason = if (reason.isEmpty) statusCode.reason else reason val body = if (detail.isEmpty) nonEmptyReason else s"$nonEmptyReason $detail" Directives.complete(statusCode.intValue() -> body) } } object ApiError { def apply(s: String): Route = InternalError(s) def apply(e: Throwable): Route = InternalError(e.getMessage) def apply(causes: Seq[Throwable]): Route = InternalError(mkString(causes)) def mkString(causes: Seq[Throwable]): String = causes.map(_.getMessage).mkString(", ") implicit def toRoute(error: ApiError): Route = error.defaultRoute object InternalError extends ApiError(StatusCodes.InternalServerError, "internal.error") object InvalidJson extends ApiError(StatusCodes.BadRequest, "invalid.json") object BadRequest extends ApiError(StatusCodes.BadRequest, "bad.request") object ApiKeyNotValid extends ApiError(StatusCodes.Forbidden, "invalid.api-key") object NotExists extends ApiError(StatusCodes.NotFound, "not-found") }
Example 24
Source File: WebsocketClientActor.scala From akka_streams_tutorial with MIT License | 5 votes |
package alpakka.tcp_to_websockets.websockets import akka.actor.{Actor, ActorLogging, ActorRef, Props} import akka.http.scaladsl.model.StatusCode import alpakka.tcp_to_websockets.websockets.WebsocketClientActor._ import org.apache.commons.lang3.exception.ExceptionUtils import scala.concurrent.duration._ case class ConnectionException(cause: String) extends RuntimeException object WebsocketClientActor { def props(id: String, endpoint: String, websocketConnectionStatusActor: ActorRef) = Props(new WebsocketClientActor(id, endpoint, websocketConnectionStatusActor)) final case object Upgraded final case object Connected final case object Terminated final case class ConnectionFailure(ex: Throwable) final case class FailedUpgrade(statusCode: StatusCode) final case class SendMessage(msg: String) } class WebsocketClientActor(id: String, endpoint: String, websocketConnectionStatusActor: ActorRef) extends Actor with ActorLogging { implicit private val system = context.system implicit private val executionContext = system.dispatcher val webSocketClient = WebSocketClient(id, endpoint, self) override def receive: Receive = startup //initial state private def startup: Receive = { case Upgraded => log.info(s"Client$id: WebSocket upgraded") case FailedUpgrade(statusCode) => log.error(s"Client$id: failed to upgrade WebSocket connection: $statusCode") websocketConnectionStatusActor ! WebsocketConnectionStatusActor.Terminated throw ConnectionException(statusCode.toString()) case ConnectionFailure(ex) => log.error(s"Client $id: failed to establish WebSocket connection: $ex") websocketConnectionStatusActor ! WebsocketConnectionStatusActor.Terminated throw ConnectionException(ExceptionUtils.getRootCause(ex).getMessage) case Connected => log.info(s"Client $id: WebSocket connected") websocketConnectionStatusActor ! WebsocketConnectionStatusActor.Connected context.become(running) case SendMessage(msg) => log.warning(s"In state startup. Can not receive message: $msg. Resend after 2 seconds") system.scheduler.scheduleOnce(2.seconds, self, SendMessage(msg)) } private def running: Receive = { case SendMessage(msg) => log.info(s"About to send message to WebSocket: $msg") webSocketClient.sendToWebsocket(msg) case Terminated => log.error(s"Client $id: WebSocket connection terminated") websocketConnectionStatusActor ! WebsocketConnectionStatusActor.Terminated throw ConnectionException(s"Client $id: WebSocket connection terminated") case ConnectionFailure(ex) => log.error(s"Client $id: ConnectionFailure occurred: $ex") websocketConnectionStatusActor ! WebsocketConnectionStatusActor.Terminated throw ConnectionException(ExceptionUtils.getRootCause(ex).getMessage) } override def postStop(): Unit = { websocketConnectionStatusActor ! WebsocketConnectionStatusActor.Terminated } }
Example 25
Source File: WindTurbineSimulator.scala From akka_streams_tutorial with MIT License | 5 votes |
package sample.stream_actor import akka.actor.{Actor, ActorLogging, Props} import akka.http.scaladsl.model.StatusCode import sample.stream_actor.WindTurbineSimulator._ case class WindTurbineSimulatorException(id: String) extends RuntimeException object WindTurbineSimulator { def props(id: String, endpoint: String) = Props(new WindTurbineSimulator(id, endpoint)) final case object Upgraded final case object Connected final case object Terminated final case class ConnectionFailure(ex: Throwable) final case class FailedUpgrade(statusCode: StatusCode) } class WindTurbineSimulator(id: String, endpoint: String) extends Actor with ActorLogging { implicit private val system = context.system implicit private val executionContext = system.dispatcher val webSocketClient = WebSocketClient(id, endpoint, self) override def receive: Receive = startup //initial state private def startup: Receive = { case Upgraded => log.info(s"$id : WebSocket upgraded") case FailedUpgrade(statusCode) => log.error(s"$id : Failed to upgrade WebSocket connection: $statusCode") throw WindTurbineSimulatorException(id) case ConnectionFailure(ex) => log.error(s"$id : Failed to establish WebSocket connection: $ex") throw WindTurbineSimulatorException(id) case Connected => log.info(s"$id : WebSocket connected") context.become(running) } private def running: Receive = { case Terminated => log.error(s"$id : WebSocket connection terminated") throw WindTurbineSimulatorException(id) case ConnectionFailure(ex) => log.error(s"$id : ConnectionFailure occurred: $ex") throw WindTurbineSimulatorException(id) } }
Example 26
Source File: akkaHttp.scala From sup with Apache License 2.0 | 5 votes |
package sup.modules import akka.http.scaladsl.marshalling.ToEntityMarshaller import akka.http.scaladsl.model.StatusCode import akka.http.scaladsl.model.StatusCodes import akka.http.scaladsl.server.Directives.{path => akkaPath, _} import akka.http.scaladsl.server.Route import cats.effect.Effect import cats.syntax.functor._ import cats.syntax.reducible._ import cats.~> import cats.Functor import cats.Reducible import sup.HealthCheck import sup.HealthResult import scala.concurrent.Future import scala.util.Failure import scala.util.Success import akka.http.scaladsl.model.HttpRequest object akkahttp { def healthCheckRoutes[F[_]: Effect, H[_]: Reducible]( healthCheck: HealthCheck[F, H], path: String = "health-check" )( implicit marshaller: ToEntityMarshaller[HealthResult[H]] ): Route = akkaPath(path) { get { onComplete(Effect[F].toIO(healthCheckResponse(healthCheck)).unsafeToFuture()) { case Success(response) => complete(response) case Failure(error) => failWith(error) } } } def healthCheckResponse[F[_]: Functor, H[_]: Reducible]( healthCheck: HealthCheck[F, H] ): F[(StatusCode, HealthResult[H])] = healthCheck.check.map { check => if (check.value.reduce.isHealthy) StatusCodes.OK -> check else StatusCodes.ServiceUnavailable -> check } def healthCheckRoutesWithContext[F[_]: Functor, H[_]: Reducible, R]( healthCheck: HealthCheck[F, H], path: String = "health-check" )( run: HttpRequest => F ~> Future )( implicit marshaller: ToEntityMarshaller[HealthResult[H]] ): Route = akkaPath(path) { get { extractRequest { request => onComplete(run(request)(healthCheckResponse(healthCheck))) { case Success(response) => complete(response) case Failure(error) => failWith(error) } } } } }
Example 27
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 28
Source File: HttpStats.scala From opencensus-scala with Apache License 2.0 | 5 votes |
package io.opencensus.scala.akka.http.stats import akka.http.scaladsl.model.{HttpMethod, StatusCode} import io.opencensus.scala.Stats import io.opencensus.scala.stats._ private[http] trait HttpStats { private[http] def stats: Stats // As defined in https://github.com/census-instrumentation/opencensus-specs/blob/master/stats/HTTP.md private val latencyBucketBoundaries = List(0, 1, 2, 3, 4, 5, 6, 8, 10, 13, 16, 20, 25, 30, 40, 50, 65, 80, 100, 130, 160, 200, 250, 300, 400, 500, 650, 800, 1000, 2000, 5000, 10000, 20000, 50000, 100000).map(_.toDouble) private val ServerMethodTagName = "http_server_method" private val ServerRouteTagName = "http_server_route" private val ServerStatusTagName = "http_server_status" private val ClientMethodTagName = "http_client_method" private val ClientRouteTagName = "http_client_route" private val ClientStatusTagName = "http_client_status" private lazy val serverLatency = for { measure <- Measure.double( name = "opencensus.io/http/server/server_latency", description = "Time between first byte of request headers read to last byte of response sent, or terminal error", unit = "ms" ) distribution <- Distribution(latencyBucketBoundaries) view <- View( name = "opencensus.io/http/server/server_latency", description = "Time between first byte of request headers read to last byte of response sent, or terminal error", measure, List(ServerMethodTagName, ServerRouteTagName, ServerStatusTagName), distribution ) _ <- stats.registerView(view) } yield measure private lazy val clientRoundTripLatency = for { measure <- Measure.double( name = "opencensus.io/http/client/roundtrip_latency", description = "Time between first byte of request headers sent to last byte of response received, or terminal error", unit = "ms" ) distribution <- Distribution(latencyBucketBoundaries) view <- View( name = "opencensus.io/http/client/roundtrip_latency", description = "Time between first byte of request headers sent to last byte of response received, or terminal error", measure, List(ClientMethodTagName, ClientRouteTagName, ClientStatusTagName), distribution ) _ <- stats.registerView(view) } yield measure private[http] def measureClientRoundtripLatency( route: String, method: HttpMethod, status: StatusCode, durationInMs: Double ) = for { measure <- clientRoundTripLatency tags <- Tag( ClientMethodTagName -> method.value, ClientRouteTagName -> route, ClientStatusTagName -> status.intValue.toString ) } yield stats.record(tags, Measurement.double(measure, durationInMs)) private[http] def measureServerLatency( route: String, method: HttpMethod, status: StatusCode, durationInMs: Double ) = for { measure <- serverLatency tags <- Tag( ServerMethodTagName -> method.value, ServerRouteTagName -> route, ServerStatusTagName -> status.intValue.toString ) } yield stats.record(tags, Measurement.double(measure, durationInMs)) }