akka.http.scaladsl.model.ContentTypes Scala Examples
The following examples show how to use akka.http.scaladsl.model.ContentTypes.
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: LinkDescriptionSpec.scala From nexus-kg with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.resources import akka.http.scaladsl.model.Uri.Path import akka.http.scaladsl.model.{ContentType, ContentTypes} import ch.epfl.bluebrain.nexus.commons.test.{EitherValues, Randomness} import ch.epfl.bluebrain.nexus.kg.TestHelper import ch.epfl.bluebrain.nexus.kg.resources.ProjectIdentifier.ProjectRef import ch.epfl.bluebrain.nexus.kg.resources.Rejection.InvalidResourceFormat import ch.epfl.bluebrain.nexus.kg.resources.file.File.{FileDescription, LinkDescription} import ch.epfl.bluebrain.nexus.rdf.implicits._ import io.circe.Json import io.circe.syntax._ import org.scalatest.OptionValues import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike class LinkDescriptionSpec extends AnyWordSpecLike with Matchers with TestHelper with Randomness with EitherValues with OptionValues { private abstract class Ctx { val id = Id(ProjectRef(genUUID), genIri) val p = genString() + "/" + genString() val f = genString() val m = "application/json" def jsonLink(mediaType: String = m, filename: String = f, path: String = p): Json = Json.obj("filename" -> filename.asJson, "path" -> path.asJson, "mediaType" -> mediaType.asJson) } "A Link Description" should { "be decoded correctly" in new Ctx { LinkDescription(id, jsonLink()).rightValue shouldEqual LinkDescription(Path(p), Some(f), ContentType.parse(m).toOption) LinkDescription(id, Json.obj("path" -> p.asJson)).rightValue shouldEqual LinkDescription(Path(p), None, None) } "accept missing filename" in new Ctx { LinkDescription(id, jsonLink().removeKeys("filename")).rightValue shouldEqual LinkDescription(Path(p), None, ContentType.parse(m).toOption) } "reject empty filename" in new Ctx { LinkDescription(id, jsonLink(filename = "")).leftValue shouldBe a[InvalidResourceFormat] } "accept missing mediaType" in new Ctx { LinkDescription(id, jsonLink().removeKeys("mediaType")).rightValue shouldEqual LinkDescription(Path(p), Some(f), None) } "reject wrong mediaType format" in new Ctx { LinkDescription(id, jsonLink(mediaType = genString())).leftValue shouldBe a[InvalidResourceFormat] } "reject missing path" in new Ctx { LinkDescription(id, jsonLink().removeKeys("path")).leftValue shouldBe a[InvalidResourceFormat] } "be converted to a FileDescription correctly" in new Ctx { val fileDesc1 = FileDescription.from(LinkDescription(Path("/foo/bar/file.ext"), None, None)) fileDesc1.filename shouldEqual "file.ext" fileDesc1.mediaType shouldEqual None fileDesc1.defaultMediaType shouldEqual ContentTypes.`application/octet-stream` val fileDesc2 = FileDescription.from(LinkDescription(Path("/foo/bar/somedir/"), None, ContentType.parse(m).toOption)) fileDesc2.filename shouldEqual "somedir" fileDesc2.mediaType.value shouldEqual ContentTypes.`application/json` val fileDesc3 = FileDescription.from(LinkDescription(Path("/foo/bar/baz"), Some("file.json"), ContentType.parse(m).toOption)) fileDesc3.filename shouldEqual "file.json" fileDesc3.mediaType.value shouldEqual ContentTypes.`application/json` } } }
Example 2
Source File: UserEndpointFeature.scala From akka-http-microservice-templates with MIT License | 5 votes |
package features import akka.http.scaladsl.model.{ContentTypes, HttpEntity, StatusCodes} import akka.http.scaladsl.testkit.ScalatestRouteTest import modules.AllModulesTest import org.scalatest.{BeforeAndAfterAll, FeatureSpec, Matchers} class UserEndpointFeature extends FeatureSpec with Matchers with ScalatestRouteTest with BeforeAndAfterAll { val modules = new AllModulesTest val routes = modules.endpoints.routes val httpEntity: (String) => HttpEntity.Strict = (str: String) => HttpEntity(ContentTypes.`application/json`, str) feature("user api") { scenario("success creation") { val validUser = """ { "username": "gabfssilva", "age": 24 } """ Post(s"/api/users", httpEntity(validUser)) ~> routes ~> check { status shouldBe StatusCodes.Created } } scenario("success get after success creation") { val validUser = """ { "username": "gabfssilva", "age": 24 } """ Post(s"/api/users", httpEntity(validUser)) ~> routes ~> check { status shouldBe StatusCodes.Created Get(header("Location").orNull.value()) ~> routes ~> check { status shouldBe StatusCodes.OK } } } scenario("invalid id on get") { Get(s"/api/users/1") ~> routes ~> check { status shouldBe StatusCodes.BadRequest } } scenario("no body") { Post(s"/api/users", httpEntity("{}")) ~> routes ~> check { status shouldBe StatusCodes.BadRequest } } scenario("body without age") { val invalidUser = """ { "username": "gabfssilva" } """ Post(s"/api/users", httpEntity(invalidUser)) ~> routes ~> check { status shouldBe StatusCodes.BadRequest } } scenario("body without username") { val invalidUser = """ { "age": 24 } """ Post(s"/api/users", httpEntity(invalidUser)) ~> routes ~> check { status shouldBe StatusCodes.BadRequest } } } }
Example 3
Source File: Aws4AuthenticatorSpec.scala From vinyldns with Apache License 2.0 | 5 votes |
package vinyldns.api.route import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpRequest} import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec class Aws4AuthenticatorSpec extends AnyWordSpec with Matchers { "getting canonical headers" should { "pull the content type" in { val entity = HttpEntity(ContentTypes.`application/json`, "") val req = HttpRequest( entity = entity ) val canonicalHeaders = new Aws4Authenticator().canonicalHeaders(req, Set("content-type")) canonicalHeaders.keys should contain("content-type") canonicalHeaders("content-type") should contain("application/json") } "pull the content-length" in { val entity = HttpEntity(ContentTypes.`application/json`, "") val req = HttpRequest( entity = entity ) val canonicalHeaders = new Aws4Authenticator().canonicalHeaders(req, Set("content-length")) canonicalHeaders.keys should contain("content-length") canonicalHeaders("content-length") should contain("0") } } }
Example 4
Source File: VinylDNSRouteTestHelper.scala From vinyldns with Apache License 2.0 | 5 votes |
package vinyldns.api.route import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpResponse, StatusCodes} import akka.http.scaladsl.server.Directives.{complete, extractUnmatchedPath} import akka.http.scaladsl.server.{MalformedRequestContentRejection, RejectionHandler} import akka.http.scaladsl.testkit.ScalatestRouteTest import org.json4s.MappingException trait VinylDNSRouteTestHelper { this: ScalatestRouteTest => import scala.concurrent.duration._ import akka.http.scaladsl.testkit.RouteTestTimeout implicit val testTimeout = RouteTestTimeout(10.seconds) implicit def validationRejectionHandler: RejectionHandler = RejectionHandler .newBuilder() .handle { case MalformedRequestContentRejection(msg, MappingException(_, _)) => complete( HttpResponse( status = StatusCodes.BadRequest, entity = HttpEntity(ContentTypes.`application/json`, msg) ) ) } .handleNotFound { extractUnmatchedPath { p => complete((StatusCodes.NotFound, s"The requested path [$p] does not exist.")) } } .result() }
Example 5
Source File: AkkaHttpActionAdapterTest.scala From akka-http-pac4j with Mozilla Public License 2.0 | 5 votes |
package com.stackstate.pac4j import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpRequest, HttpResponse} import org.scalatest.{Matchers, WordSpecLike} import akka.http.scaladsl.model.StatusCodes._ import akka.util.ByteString import com.stackstate.pac4j.AkkaHttpActionAdapterTest.ActionInt import com.stackstate.pac4j.http.AkkaHttpActionAdapter import com.stackstate.pac4j.store.ForgetfulSessionStorage import org.pac4j.core.exception.http.{ BadRequestAction, ForbiddenAction, FoundAction, HttpAction, NoContentAction, OkAction, StatusAction, UnauthorizedAction } import org.scalatest.concurrent.ScalaFutures class AkkaHttpActionAdapterTest extends WordSpecLike with Matchers with ScalaFutures { "AkkaHttpActionAdapter" should { "convert 200 to OK" in withContext { context => AkkaHttpActionAdapter.adapt(new OkAction(""), context).futureValue.response shouldEqual HttpResponse( OK, Nil, HttpEntity(ContentTypes.`application/octet-stream`, ByteString("")) ) } "convert 401 to Unauthorized" in withContext { context => AkkaHttpActionAdapter.adapt(UnauthorizedAction.INSTANCE, context).futureValue.response shouldEqual HttpResponse(Unauthorized) context.getChanges.cookies.map(_.name) shouldBe List(AkkaHttpWebContext.DEFAULT_COOKIE_NAME) } "convert 302 to SeeOther (to support login flow)" in withContext { context => val r = AkkaHttpActionAdapter.adapt(new FoundAction("/login"), context).futureValue.response r.status shouldEqual SeeOther r.headers.head.value() shouldEqual "/login" context.getChanges.cookies.map(_.name) shouldBe List(AkkaHttpWebContext.DEFAULT_COOKIE_NAME) } "convert 400 to BadRequest" in withContext { context => AkkaHttpActionAdapter.adapt(BadRequestAction.INSTANCE, context).futureValue.response shouldEqual HttpResponse(BadRequest) } "convert 201 to Created" in withContext { context => AkkaHttpActionAdapter.adapt(201.action(), context).futureValue.response shouldEqual HttpResponse(Created) } "convert 403 to Forbidden" in withContext { context => AkkaHttpActionAdapter.adapt(ForbiddenAction.INSTANCE, context).futureValue.response shouldEqual HttpResponse(Forbidden) } "convert 204 to NoContent" in withContext { context => AkkaHttpActionAdapter.adapt(NoContentAction.INSTANCE, context).futureValue.response shouldEqual HttpResponse(NoContent) } "convert 200 to OK with content set from the context" in withContext { context => AkkaHttpActionAdapter.adapt(new OkAction("content"), context).futureValue.response shouldEqual HttpResponse .apply(OK, Nil, HttpEntity(ContentTypes.`application/octet-stream`, ByteString("content"))) } "convert 200 to OK with content type set from the context" in withContext { context => context.setResponseContentType("application/json") AkkaHttpActionAdapter.adapt(new OkAction(""), context).futureValue.response shouldEqual HttpResponse .apply(OK, Nil, HttpEntity(ContentTypes.`application/json`, ByteString(""))) } } def withContext(f: AkkaHttpWebContext => Unit): Unit = { f(AkkaHttpWebContext(HttpRequest(), Seq.empty, new ForgetfulSessionStorage, AkkaHttpWebContext.DEFAULT_COOKIE_NAME)) } } object AkkaHttpActionAdapterTest { implicit class ActionInt(val i: Int) extends AnyVal { def action(): HttpAction = new StatusAction(i) } }
Example 6
Source File: HealthEndpoint.scala From akka-http-health with MIT License | 5 votes |
package io.github.lhotari.akka.http.health import java.util.concurrent.atomic.AtomicBoolean import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpResponse, StatusCodes} import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.Route import scala.concurrent.{ExecutionContext, Future} trait HealthEndpoint { protected lazy val checkers = createCheckers protected def createCheckers = { Seq(new LowDiskSpaceDetector(), new LowMemoryDetector()) } private lazy val successResponse: HttpResponse = createSuccessResponse protected def decorateResponse(response: HttpResponse) = response protected def createSuccessResponse = { decorateResponse(HttpResponse(entity = HttpEntity(ContentTypes.`text/plain(UTF-8)`, "OK"))) } private lazy val errorResponse: HttpResponse = createErrorResponse protected def createErrorResponse = { decorateResponse(HttpResponse(status = StatusCodes.ServiceUnavailable)) } private val started = new AtomicBoolean(false) def createHealthRoute(endpoint: String = HealthEndpoint.DefaultEndpoint)(implicit executor: ExecutionContext): Route = get { path(endpoint) { completeHealthCheck } } def completeHealthCheck(implicit executor: ExecutionContext) = { complete { Future { if (isHealthy()) successResponse else errorResponse } } } def start(): Unit = { if (started.compareAndSet(false, true)) { checkers.foreach(_.start()) } } def stop(): Unit = { if (started.compareAndSet(true, false)) { checkers.foreach(_.stop()) } } def isHealthy() = { start() checkers.forall(_.isHealthy()) } } object HealthEndpoint extends HealthEndpoint { lazy val defaultHealthChecker = new HealthEndpoint {} val DefaultEndpoint: String = "health" def createDefaultHealthRoute(endpoint: String = DefaultEndpoint)(implicit executor: ExecutionContext): Route = { defaultHealthChecker.createHealthRoute(endpoint) } }
Example 7
Source File: EntityUtils.scala From asura with MIT License | 5 votes |
package asura.core.http import java.net.URLEncoder import akka.http.scaladsl.model.{ContentType, ContentTypes, HttpEntity, RequestEntity} import akka.util.ByteString import asura.common.util.{LogUtils, StringUtils} import asura.core.es.model.{HttpCaseRequest, KeyValueObject} import asura.core.http.UriUtils.UTF8 import asura.core.runtime.RuntimeContext import asura.core.util.JacksonSupport import com.fasterxml.jackson.core.`type`.TypeReference import com.typesafe.scalalogging.Logger object EntityUtils { val logger = Logger("EntityUtils") def toEntity(cs: HttpCaseRequest, context: RuntimeContext): RequestEntity = { val request = cs.request var contentType: ContentType = ContentTypes.`text/plain(UTF-8)` var byteString: ByteString = ByteString.empty if (StringUtils.isNotEmpty(request.contentType) && null != request.body && request.body.nonEmpty) { request.contentType match { case HttpContentTypes.JSON => contentType = ContentTypes.`application/json` val body = request.body.find(_.contentType == HttpContentTypes.JSON) if (body.nonEmpty) { byteString = ByteString(context.renderBodyAsString(body.get.data)) } case HttpContentTypes.X_WWW_FORM_URLENCODED => contentType = ContentTypes.`application/x-www-form-urlencoded` val body = request.body.find(_.contentType == HttpContentTypes.X_WWW_FORM_URLENCODED) if (body.nonEmpty) { var bodyStr: String = null try { val sb = StringBuilder.newBuilder val params = JacksonSupport.parse(body.get.data, new TypeReference[Seq[KeyValueObject]]() {}) for (pair <- params if (pair.enabled && StringUtils.isNotEmpty(pair.key))) { val rendered = context.renderBodyAsString(pair.value) sb.append(pair.key).append("=").append(URLEncoder.encode(rendered, UTF8)).append("&") } if (sb.nonEmpty) { sb.deleteCharAt(sb.length - 1) } bodyStr = sb.toString } catch { case t: Throwable => val errLog = LogUtils.stackTraceToString(t) logger.warn(errLog) bodyStr = errLog } byteString = ByteString(bodyStr) } case HttpContentTypes.TEXT_PLAIN => contentType = ContentTypes.`text/plain(UTF-8)` val body = request.body.find(_.contentType == HttpContentTypes.TEXT_PLAIN) if (body.nonEmpty) { byteString = ByteString(context.renderBodyAsString(body.get.data)) } case _ => } } HttpEntity(contentType, byteString) } }
Example 8
Source File: JavaFlowSvcSpec.scala From squbs with Apache License 2.0 | 5 votes |
package org.squbs.unicomplex import akka.actor.ActorSystem import akka.http.scaladsl.model.HttpEntity.Chunked import akka.http.scaladsl.model.{ContentTypes, HttpEntity, StatusCodes} import akka.pattern._ import akka.stream.ActorMaterializer import akka.stream.scaladsl.{Keep, Sink, Source} import akka.testkit.TestKit import com.typesafe.config.ConfigFactory import org.scalatest.{AsyncFlatSpecLike, BeforeAndAfterAll, Matchers} import org.squbs.lifecycle.GracefulStop import org.squbs.unicomplex.Timeouts._ object JavaFlowSvcSpec { val classPaths = Array(getClass.getClassLoader.getResource("classpaths/JavaFlowSvc").getPath) val config = ConfigFactory.parseString( s""" |default-listener.bind-port = 0 |squbs { | actorsystem-name = JavaFlowSvcSpec | ${JMX.prefixConfig} = true |} """.stripMargin ) val boot = UnicomplexBoot(config) .createUsing {(name, config) => ActorSystem(name, config)} .scanComponents(classPaths) .initExtensions.start() } class JavaFlowSvcSpec extends TestKit( JavaFlowSvcSpec.boot.actorSystem) with AsyncFlatSpecLike with BeforeAndAfterAll with Matchers { implicit val am = ActorMaterializer() val portBindingsF = (Unicomplex(system).uniActor ? PortBindings).mapTo[Map[String, Int]] val portF = portBindingsF map { bindings => bindings("default-listener") } override def afterAll(): Unit = { Unicomplex(system).uniActor ! GracefulStop } it should "handle a normal request" in { for { port <- portF response <- entityAsString(s"http://127.0.0.1:$port/javaflowsvc/ping") } yield { response shouldBe "pong" } } it should "handle a chunked request and be able to provide a chunked response" in { val requestChunks = Source.single("Hi this is a test") .mapConcat { s => s.split(' ').toList } .map(HttpEntity.ChunkStreamPart(_)) for { port <- portF response <- post(s"http://127.0.0.1:$port/javaflowsvc/chunks", Chunked(ContentTypes.`text/plain(UTF-8)`, requestChunks)) responseString <- response.entity.dataBytes.map(_.utf8String).toMat(Sink.fold("") { _ + _})(Keep.right).run() } yield { response.entity shouldBe 'chunked responseString should be("Received 5 chunks and 13 bytes.\r\nThis is the last chunk!") } } it should "get an InternalServerError with blank response if Flow collapses" in { for { port <- portF errResp <- get(s"http://127.0.0.1:$port/javaflowsvc/throwit") respEntity <- errResp.entity.toStrict(awaitMax) } yield { errResp.status shouldBe StatusCodes.InternalServerError respEntity.data.utf8String shouldBe 'empty } } }
Example 9
Source File: MetronomeFacade.scala From metronome with Apache License 2.0 | 5 votes |
package dcos.metronome.integrationtest.utils import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.client.RequestBuilding.{Get, Post} import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpRequest, HttpResponse} import akka.stream.Materializer import com.mesosphere.utils.http.RestResult import scala.concurrent.Await.result import scala.concurrent.Future import scala.concurrent.duration.{FiniteDuration, _} class MetronomeFacade(val url: String, implicit val waitTime: FiniteDuration = 30.seconds)(implicit val system: ActorSystem, mat: Materializer ) { import scala.concurrent.ExecutionContext.Implicits.global //info -------------------------------------------------- def info(): RestResult[HttpResponse] = { result(request(Get(s"$url/info")), waitTime) } def createJob(jobDef: String): RestResult[HttpResponse] = { val e = HttpEntity(ContentTypes.`application/json`, jobDef) result(request(Post(s"$url/v1/jobs", e)), waitTime) } def startRun(jobId: String): RestResult[HttpResponse] = { val e = HttpEntity(ContentTypes.`application/json`, "") result(request(Post(s"$url/v1/jobs/${jobId}/runs", e)), waitTime) } def getJob(jobId: String): RestResult[HttpResponse] = { result(request(Get(s"$url/v1/jobs/${jobId}")), waitTime) } def getJobs(): RestResult[HttpResponse] = { result(request(Get(s"$url/v1/jobs")), waitTime) } def getRuns(jobId: String): RestResult[HttpResponse] = { result(request(Get(s"$url/v1/jobs/${jobId}/runs")), waitTime) } private[this] def request(request: HttpRequest): Future[RestResult[HttpResponse]] = { Http(system).singleRequest(request).flatMap { response => response.entity.toStrict(waitTime).map(_.data.decodeString("utf-8")).map(RestResult(response, _)) } } }
Example 10
Source File: Routes.scala From akka-ddd-cqrs-es-example with MIT License | 5 votes |
package com.github.j5ik2o.bank.adaptor.controller import akka.actor.ActorSystem import akka.http.scaladsl.model.{ ContentTypes, HttpEntity, HttpResponse } import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.Route import akka.stream.Materializer import cats.syntax.either._ import com.github.j5ik2o.bank.adaptor.generator.IdGenerator import com.github.j5ik2o.bank.domain.model.BankAccountId import com.github.j5ik2o.bank.useCase.{ BankAccountAggregateUseCase, BankAccountReadModelUseCase } import org.hashids.Hashids object Routes { trait ResponseJson { val isSuccessful: Boolean val errorMessages: Seq[String] } case class OpenBankAccountRequestJson(name: String) case class OpenBankAccountResponseJson(id: String, errorMessages: Seq[String] = Seq.empty) extends ResponseJson { override val isSuccessful: Boolean = errorMessages.isEmpty } case class UpdateBankAccountRequestJson(name: String) case class UpdateBankAccountResponseJson(id: String, errorMessages: Seq[String] = Seq.empty) extends ResponseJson { override val isSuccessful: Boolean = errorMessages.isEmpty } case class AddBankAccountEventRequestJson(`type`: String, amount: Long, currencyCode: String) case class AddBankAccountEventResponseJson(id: String, errorMessages: Seq[String] = Seq.empty) extends ResponseJson { override val isSuccessful: Boolean = errorMessages.isEmpty } case class CloseBankAccountRequestJson(id: String) case class CloseBankAccountResponseJson(id: String, errorMessages: Seq[String] = Seq.empty) extends ResponseJson { override val isSuccessful: Boolean = errorMessages.isEmpty } case class BankAccountEventJson(`type`: String, amount: Long, currencyCode: String, createAt: Long) case class ResolveBankAccountEventsResponseJson(id: String, values: Seq[BankAccountEventJson], errorMessages: Seq[String] = Seq.empty) extends ResponseJson { override val isSuccessful: Boolean = errorMessages.isEmpty } case class ValidationErrorsResponseJson(errorMessages: Seq[String]) extends ResponseJson { override val isSuccessful: Boolean = false } implicit class HashidsStringOps(val self: String) extends AnyVal { def decodeFromHashid(implicit hashIds: Hashids): Either[Throwable, Long] = { Either.catchNonFatal(hashIds.decode(self)(0)) } } implicit class HashidsLongOps(val self: Long) extends AnyVal { def encodeToHashid(implicit hashIds: Hashids): Either[Throwable, String] = Either.catchNonFatal(hashIds.encode(self)) } } case class Routes(bankAccountIdGenerator: IdGenerator[BankAccountId], bankAccountAggregateUseCase: BankAccountAggregateUseCase, bankAccountReadModelUseCase: BankAccountReadModelUseCase)( implicit system: ActorSystem, mat: Materializer ) extends BankAccountController { implicit val ec = system.dispatcher def root: Route = RouteLogging.default.httpLogRequestResult { pathEndOrSingleSlash { get { index() } } ~ toBankAccountRoutes } private def index() = complete( HttpResponse( entity = HttpEntity( ContentTypes.`text/plain(UTF-8)`, "Wellcome to Bank API" ) ) ) }
Example 11
Source File: MetricsEndpointsSpec.scala From service-container with Apache License 2.0 | 5 votes |
package com.github.vonnagy.service.container.metrics import java.net.InetAddress import akka.http.scaladsl.model.headers.{Accept, `Remote-Address`} import akka.http.scaladsl.model.{ContentTypes, MediaTypes, RemoteAddress, StatusCodes} import com.github.vonnagy.service.container.Specs2RouteTest import com.github.vonnagy.service.container.http.routing.Rejection.NotFoundRejection import org.specs2.mutable.Specification class MetricsEndpointsSpec extends Specification with Specs2RouteTest { val endpoints = new MetricsEndpoints()(system, system.dispatcher) def remoteAddress(ip: String) = RemoteAddress(InetAddress.getByName(ip)) "The routing infrastructure should support" should { "a call to /metrics to be handled" in { Get("/metrics").withHeaders(`Remote-Address`(remoteAddress("127.0.0.1"))) ~> endpoints.route ~> check { handled must beTrue contentType === ContentTypes.`application/json` status must be equalTo (StatusCodes.OK) } } "a call to /metrics should return json" in { Get("/metrics").withHeaders(Accept(MediaTypes.`application/json`), `Remote-Address`(remoteAddress("127.0.0.1"))) ~> endpoints.route ~> check { handled must beTrue contentType === ContentTypes.`application/json` } } "a call to /metrics should return an error due to CIDR rules" in { Get("/metrics").withHeaders(Accept(MediaTypes.`application/json`), `Remote-Address`(remoteAddress("192.168.1.1"))) ~> endpoints.route ~> check { handled must beFalse rejections.size must beEqualTo(1) rejections.head must be equalTo(NotFoundRejection("The requested resource could not be found")) } } } }
Example 12
Source File: HealthEndpointsSpec.scala From service-container with Apache License 2.0 | 5 votes |
package com.github.vonnagy.service.container.health import java.net.InetAddress import akka.http.scaladsl.model.headers.{Accept, `Remote-Address`} import akka.http.scaladsl.model.{ContentTypes, MediaTypes, RemoteAddress, StatusCodes} import com.github.vonnagy.service.container.Specs2RouteTest import com.github.vonnagy.service.container.http.routing.Rejection.NotFoundRejection import org.specs2.mutable.Specification import scala.concurrent.Future class HealthEndpointsSpec extends Specification with Specs2RouteTest { sequential val endpoints = new HealthEndpoints()(system, system.dispatcher) def remoteAddress(ip: String) = RemoteAddress(InetAddress.getByName(ip)) "The routing infrastructure" should { "support a call to /health" in { Get("/health").withHeaders(`Remote-Address`(remoteAddress("127.0.0.1"))) ~> endpoints.route ~> check { handled must beTrue contentType === ContentTypes.`application/json` status must be equalTo (StatusCodes.OK) } } "support a call to /health that should return json" in { Get("/health").withHeaders(Accept(MediaTypes.`application/json`), `Remote-Address`(remoteAddress("127.0.0.1"))) ~> endpoints.route ~> check { handled must beTrue mediaType === MediaTypes.`application/json` contentType === ContentTypes.`application/json` } } "a call to /health should return an error due to CIDR rules" in { Get("/health").withHeaders(Accept(MediaTypes.`application/json`), `Remote-Address`(remoteAddress("192.168.1.1"))) ~> endpoints.route ~> check { handled must beFalse rejections.size must beEqualTo(1) rejections.head must be equalTo(NotFoundRejection("The requested resource could not be found")) } } "support a call to /health/lb" in { Get("/health/lb").withHeaders(Accept(MediaTypes.`text/plain`), `Remote-Address`(remoteAddress("127.0.0.1"))) ~> endpoints.route ~> check { handled must beTrue mediaType === MediaTypes.`text/plain` responseAs[String].equals("UP") } } "support a call to health/lb that returns a status of `Ok` when a health check is marked as degraded" in { Health(system).addCheck(new HealthCheck { override def getHealth: Future[HealthInfo] = Future { HealthInfo("degraded", HealthState.DEGRADED, "") } }) Get("/health/lb").withHeaders(Accept(MediaTypes.`text/plain`), `Remote-Address`(remoteAddress("127.0.0.1"))) ~> endpoints.route ~> check { handled must beTrue mediaType === MediaTypes.`text/plain` status === StatusCodes.OK responseAs[String].equals("UP") } } "support a call to health/lb that returns a status of `ServiceUnavailable` when a health check is marked as critical" in { Health(system).addCheck(new HealthCheck { override def getHealth: Future[HealthInfo] = Future { HealthInfo("critical", HealthState.CRITICAL, "") } }) Get("/health/lb").withHeaders(Accept(MediaTypes.`text/plain`), `Remote-Address`(remoteAddress("127.0.0.1"))) ~> endpoints.route ~> check { //handled must beTrue mediaType === MediaTypes.`text/plain` status === StatusCodes.ServiceUnavailable responseAs[String].equals("DOWN") } } } }
Example 13
Source File: ConsulStoreActor.scala From vamp with Apache License 2.0 | 5 votes |
package io.vamp.persistence.consul import java.util.Base64 import akka.http.scaladsl.model.ContentTypes import io.vamp.common.{ ClassMapper, Config } import io.vamp.persistence.KeyValueStoreActor import scala.concurrent.Future class ConsulStoreActorMapper extends ClassMapper { val name = "consul" val clazz: Class[_] = classOf[ConsulStoreActor] } class ConsulStoreActor extends KeyValueStoreActor { private lazy val url = Config.string("vamp.persistence.key-value-store.consul.url")() override protected def info(): Future[Any] = httpClient.get[Any](s"$url/v1/agent/self") map { consul ⇒ Map("type" → "consul", "consul" → consul) } override protected def children(path: List[String]): Future[List[String]] = { val key = pathToString(path) checked[List[String]](httpClient.get[List[String]](urlOf(path, keys = true), logError = false) recover { case _ ⇒ Nil }) map { list ⇒ list.flatMap(_.substring(key.length).split('/').headOption) } } override protected def get(path: List[String]): Future[Option[String]] = { httpClient.get[List[_]](urlOf(path), logError = false) recover { case _ ⇒ None } map { case head :: Nil ⇒ Option(result(head.asInstanceOf[Map[_, _]])) case _ ⇒ None } } override protected def set(path: List[String], data: Option[String]): Future[Any] = data match { case None ⇒ httpClient.delete(urlOf(path), logError = false) case Some(value) ⇒ httpClient.put[Any](urlOf(path), value, contentType = ContentTypes.`text/plain(UTF-8)`) } private def urlOf(path: List[String], keys: Boolean = false) = { s"$url/v1/kv${pathToString(path)}${if (keys) "?keys" else ""}" } private def result(map: Map[_, _]): String = map.asInstanceOf[Map[String, _]].get("Value") match { case Some(value) if value != null ⇒ new String(Base64.getDecoder.decode(value.asInstanceOf[String])) case _ ⇒ "" } }
Example 14
Source File: ServerVersionRoute.scala From learn-akka with Apache License 2.0 | 5 votes |
package com.allaboutscala.learn.akka.http.routes import akka.http.scaladsl.model.{ContentTypes, HttpEntity} import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.Route import com.allaboutscala.learn.akka.http.jsonsupport.{JsonSupport, AkkaHttpRestServer} class ServerVersion extends JsonSupport { def route(): Route = { path("server-version") { get { val serverVersion = "1.0.0.0" complete(HttpEntity(ContentTypes.`text/plain(UTF-8)`, serverVersion)) } } } def routeAsJson(): Route = { path("server-version-json") { get { val jsonResponse = """ |{ | "app": "Akka HTTP REST Server", | "version": "1.0.0.0" |} """.stripMargin complete(HttpEntity(ContentTypes.`application/json`, jsonResponse)) } } } def routeAsJsonEncoding(): Route = { path("server-version-json-encoding") { get { val server = AkkaHttpRestServer("Akka HTTP REST Server", "1.0.0.0") complete(server) } } } }
Example 15
Source File: UserEndpointFeature.scala From akka-http-microservice-templates with MIT License | 5 votes |
package features import akka.http.scaladsl.model.{ContentTypes, HttpEntity, StatusCodes} import akka.http.scaladsl.testkit.ScalatestRouteTest import modules.AllModules import org.scalatest.{BeforeAndAfterAll, FeatureSpec, Matchers} import utils.EmbeddedPostgreSQL class UserEndpointFeature extends FeatureSpec with Matchers with ScalatestRouteTest with BeforeAndAfterAll { val modules = new AllModules override def beforeAll(): Unit = { EmbeddedPostgreSQL.start } override def afterAll(): Unit = { EmbeddedPostgreSQL.stop } val routes = modules.endpoints.routes val httpEntity: (String) => HttpEntity.Strict = (str: String) => HttpEntity(ContentTypes.`application/json`, str) feature("user api") { scenario("success creation") { val validUser = """ { "username": "gabfssilva", "age": 24 } """ Post(s"/api/users", httpEntity(validUser)) ~> routes ~> check { status shouldBe StatusCodes.Created } } scenario("success get after success creation") { val validUser = """ { "username": "gabfssilva", "age": 24 } """ Post(s"/api/users", httpEntity(validUser)) ~> routes ~> check { status shouldBe StatusCodes.Created Get(header("Location").orNull.value()) ~> routes ~> check { status shouldBe StatusCodes.OK } } } scenario("invalid id on get") { Get(s"/api/users/asd") ~> routes ~> check { status shouldBe StatusCodes.NotFound } } scenario("no body") { Post(s"/api/users", httpEntity("{}")) ~> routes ~> check { status shouldBe StatusCodes.BadRequest } } scenario("body without age") { val invalidUser = """ { "username": "gabfssilva" } """ Post(s"/api/users", httpEntity(invalidUser)) ~> routes ~> check { status shouldBe StatusCodes.BadRequest } } scenario("body without username") { val invalidUser = """ { "age": 24 } """ Post(s"/api/users", httpEntity(invalidUser)) ~> routes ~> check { status shouldBe StatusCodes.BadRequest } } } }
Example 16
Source File: DiskStorageOperationsSpec.scala From nexus-kg with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.storage import java.nio.file.Paths import akka.http.scaladsl.model.{ContentTypes, Uri} import cats.effect.IO import ch.epfl.bluebrain.nexus.commons.test._ import ch.epfl.bluebrain.nexus.commons.test.io.IOEitherValues import ch.epfl.bluebrain.nexus.kg.config.AppConfig._ import ch.epfl.bluebrain.nexus.kg.config.Settings import ch.epfl.bluebrain.nexus.kg.resources.file.File.FileDescription import ch.epfl.bluebrain.nexus.kg.resources.Id import ch.epfl.bluebrain.nexus.kg.resources.ProjectIdentifier.ProjectRef import ch.epfl.bluebrain.nexus.kg.{KgError, TestHelper} import ch.epfl.bluebrain.nexus.sourcing.RetryStrategyConfig import org.mockito.IdiomaticMockito import org.scalatest.{BeforeAndAfter, OptionValues} import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike import scala.concurrent.duration._ class DiskStorageOperationsSpec extends ActorSystemFixture("DiskStorageOperationsSpec") with AnyWordSpecLike with Matchers with BeforeAndAfter with IdiomaticMockito with IOEitherValues with Resources with TestHelper with OptionValues { private val appConfig = Settings(system).appConfig private implicit val sc: StorageConfig = appConfig.storage.copy( DiskStorageConfig(Paths.get("/tmp"), "SHA-256", read, write, false, 1024L), RemoteDiskStorageConfig("http://example.com", "v1", None, "SHA-256", read, write, true, 1024L), S3StorageConfig("MD5", read, write, true, 1024L), "password", "salt", RetryStrategyConfig("linear", 300.millis, 5.minutes, 100, 1.second) ) private val project = ProjectRef(genUUID) private val storage = Storage.DiskStorage.default(project) private val resId = Id(storage.ref, genIri) private val fileDesc = FileDescription("my file.txt", ContentTypes.`text/plain(UTF-8)`) "DiskStorageOperations" should { "verify when the storage exists" in { val verify = new DiskStorageOperations.VerifyDiskStorage[IO](storage) verify.apply.accepted } "save and fetch files" in { val save = new DiskStorageOperations.SaveDiskFile[IO](storage) val fetch = new DiskStorageOperations.FetchDiskFile[IO]() val source = genSource val attr = save.apply(resId, fileDesc, source).ioValue attr.bytes shouldEqual 16L attr.filename shouldEqual fileDesc.filename attr.mediaType shouldEqual fileDesc.mediaType.value attr.location shouldEqual Uri(s"file:///tmp/${mangle(project, attr.uuid, "my%20file.txt")}") attr.path shouldEqual attr.location.path.tail.tail.tail val fetched = fetch.apply(attr).ioValue consume(source) shouldEqual consume(fetched) } "not link files" in { val link = new DiskStorageOperations.LinkDiskFile[IO]() link.apply(resId, fileDesc, Uri.Path("/foo")).failed[KgError] shouldEqual KgError.UnsupportedOperation } } }
Example 17
Source File: InnerSuite.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.akkaHttp import akka.http.scaladsl.marshalling.{Marshaller, Marshalling, ToResponseMarshaller} import akka.http.scaladsl.model.{ContentTypes, HttpResponse} import akka.http.scaladsl.testkit.ScalatestRouteTest import ru.tinkoff.tschema.syntax._ import org.scalatest.flatspec.AsyncFlatSpec import org.scalatest.matchers.should.Matchers import scala.language.reflectiveCalls class InnerSuite extends AsyncFlatSpec with ScalatestRouteTest with Matchers { object impl { object first { def get: String = "first" def post(message: String) = s"first $message" } val second = new { def get: String = "second" def post(message: String) = s"second $message" } } implicit val unitAsPlainText: ToResponseMarshaller[Unit] = Marshaller.strict(_ => Marshalling.WithFixedContentType(ContentTypes.NoContentType, () => HttpResponse())) def api = ( groupPrefix("first") |> (( opGet |> $$[String] ) <> ( opPost |> queryParam[String]("message") |> $$[String] )) ) <> ( groupPrefix("second") |> (( opGet |> $$[String] ) <> ( opPost |> body[String]("message") |> $$[String] )) ) val route = MkRoute(api)(impl) "first group" should "handle get" in Get("/first") ~> route ~> check { responseAs[String] shouldBe "first" } it should "handle post" in Post("/first?message=hello+oleg") ~> route ~> check { responseAs[String] shouldBe "first hello oleg" } "second group" should "handle get" in Get("/second") ~> route ~> check { responseAs[String] shouldBe "second" } it should "handle post" in Post("/second", "hello oleg") ~> route ~> check { responseAs[String] shouldBe "second hello oleg" } }
Example 18
Source File: TestServer.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.examples import java.util.Locale import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpResponse} import akka.http.scaladsl.server.Directives.{complete, get, pathPrefix, _} import akka.stream.ActorMaterializer import cats.instances.list._ import cats.syntax.foldable._ import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport._ import io.circe.Printer import ru.tinkoff.tschema.swagger.{OpenApiInfo, PathDescription} object TestServer { implicit val system = ActorSystem() implicit val mat = ActorMaterializer() import system.dispatcher val descriptions = PathDescription.utf8I18n("swagger", Locale.forLanguageTag("ru")) val modules = List[ExampleModule]( TestModule, VersionModule, FiltersModule, FormFieldsModule, Authorize, CustomAuth, MultiParameters, ProxyModule ).combineAll private[this] implicit val printer: Printer = Printer.noSpaces.copy(dropNullValues = true) val route = pathPrefix("api") { modules.route } ~ path("swagger")( get( complete( modules.swag .describe(descriptions) .make(OpenApiInfo()) .addServer("/api") ) ) ) ~ pathPrefix("webjars")( getFromResourceDirectory("META-INF/resources/webjars") ) ~ path("swagger.php")( complete( HttpResponse( entity = HttpEntity( contentType = ContentTypes.`text/html(UTF-8)`, string = SwaggerIndex.index.render ) ) ) ) def main(args: Array[String]): Unit = { for (_ <- Http().bindAndHandle(route, "localhost", 8081)) println("server started at http://localhost:8081/swagger.php") } }
Example 19
Source File: JsonUnmarshallers.scala From scala-openrtb with Apache License 2.0 | 5 votes |
package com.powerspace.openrtb.akka.marshallers import akka.http.scaladsl.model.{ContentTypeRange, ContentTypes, HttpRequest} import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, FromRequestUnmarshaller, Unmarshaller} import akka.stream.Materializer import com.google.openrtb.{BidRequest, BidResponse} import io.circe.Decoder import scala.concurrent.{ExecutionContext, Future} import io.circe.parser.decode object JsonUnmarshallers { import akka.http.scaladsl.unmarshalling.PredefinedFromEntityUnmarshallers._ def bidRequestJsonUnmarshaller(implicit decoder: Decoder[BidRequest]): FromEntityUnmarshaller[BidRequest] = stringUnmarshaller .forContentTypes(ContentTypeRange(ContentTypes.`application/json`)) .map(implicit json => decode[BidRequest](json).handlingFailure) def bidResponseJsonUnmarshaller(implicit decoder: Decoder[BidResponse]): FromEntityUnmarshaller[BidResponse] = stringUnmarshaller .forContentTypes(ContentTypeRange(ContentTypes.`application/json`)) .map(implicit json => decode[BidResponse](json).handlingFailure) def bidRequestHttpJsonUnmarshaller(implicit decoder: Decoder[BidRequest]): FromRequestUnmarshaller[BidRequest] = new FromRequestUnmarshaller[BidRequest]() { override def apply( value: HttpRequest)(implicit ec: ExecutionContext, materializer: Materializer): Future[BidRequest] = Unmarshaller .stringUnmarshaller(value.entity) .map(implicit json => decode[BidRequest](json).handlingFailure) } def bidResponseHttpJsonUnmarshaller(implicit decoder: Decoder[BidResponse]): FromRequestUnmarshaller[BidResponse] = new FromRequestUnmarshaller[BidResponse]() { override def apply( value: HttpRequest)(implicit ec: ExecutionContext, materializer: Materializer): Future[BidResponse] = Unmarshaller .stringUnmarshaller(value.entity) .map(implicit json => decode[BidResponse](json).handlingFailure) } implicit class DecodingResultEnhancement[T](decodingResult: Either[_ <: Exception, T]) { def handlingFailure(implicit json: String): T = decodingResult match { case Right(decoded) => decoded case Left(error) => throw new UnsupportedOperationException(error) } } }
Example 20
Source File: JsonMarshallers.scala From scala-openrtb with Apache License 2.0 | 5 votes |
package com.powerspace.openrtb.akka.marshallers import akka.http.scaladsl.marshalling.{ToEntityMarshaller, ToResponseMarshaller} import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpResponse, MediaTypes} import com.google.openrtb.{BidRequest, BidResponse} import io.circe.Encoder object JsonMarshallers { import akka.http.scaladsl.marshalling.Marshaller._ def bidRequestJsonMarshaller(implicit encoder: Encoder[BidRequest]): ToEntityMarshaller[BidRequest] = withFixedContentType(ContentTypes.`application/json`)( bidRequest => HttpEntity(MediaTypes.`application/json`, encoder.apply(bidRequest).toString) ) def bidResponseJsonMarshaller(implicit encoder: Encoder[BidResponse]): ToEntityMarshaller[BidResponse] = withFixedContentType(ContentTypes.`application/json`)( bidResponse => HttpEntity(MediaTypes.`application/json`, encoder.apply(bidResponse).toString) ) def bidRequestHttpJsonMarshaller(implicit encoder: Encoder[BidRequest]): ToResponseMarshaller[BidRequest] = withFixedContentType(ContentTypes.`application/json`)( bidRequest => HttpResponse() .withEntity(HttpEntity(MediaTypes.`application/json`, encoder.apply(bidRequest).toString)) ) def bidResponseHttpJsonMarshaller(implicit encoder: Encoder[BidResponse]): ToResponseMarshaller[BidResponse] = withFixedContentType(ContentTypes.`application/json`)( bidResponse => HttpResponse() .withEntity(HttpEntity(MediaTypes.`application/json`, encoder.apply(bidResponse).toString)) ) }
Example 21
Source File: RestClientSpec.scala From twitter4s with Apache License 2.0 | 5 votes |
package com.danielasfregola.twitter4s.http.clients.rest import akka.http.scaladsl.model.{ContentTypes, HttpResponse, StatusCodes} import com.danielasfregola.twitter4s.exceptions.{Errors, TwitterError, TwitterException} import com.danielasfregola.twitter4s.helpers.ClientSpec import scala.concurrent.Future class RestClientSpec extends ClientSpec { class ClientSpecContext extends RestClientSpecContext { import restClient._ def exampleRequest(): Future[Unit] = Get("an-example-request", ContentTypes.`application/json`).respondAs[Unit] } "Rest Client" should { "throw twitter exception to twitter rejection" in new ClientSpecContext { val response = { val entity = """{"errors":[{"message":"Sorry, that page does not exist","code":34}]}""" HttpResponse(StatusCodes.NotFound, entity = entity) } val result = when(exampleRequest).expectRequest(identity(_)).respondWith(response) val expectedTwitterException = TwitterException(code = StatusCodes.NotFound, errors = Errors(TwitterError("Sorry, that page does not exist", 34))) result.await should throwAn(expectedTwitterException) } "throw twitter exception to generic failure http response" in new ClientSpecContext { val body = "Something bad happened" val response = HttpResponse(StatusCodes.RequestTimeout, entity = body) val result = when(exampleRequest).expectRequest(identity(_)).respondWith(response) val expectedTwitterException = TwitterException(code = StatusCodes.RequestTimeout, errors = Errors(body)) result.await should throwAn(expectedTwitterException) } } }
Example 22
Source File: FormSupportSpec.scala From twitter4s with Apache License 2.0 | 5 votes |
package com.danielasfregola.twitter4s.http.serializers import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpResponse} import com.danielasfregola.twitter4s.exceptions.TwitterException import com.danielasfregola.twitter4s.helpers.{AwaitableFuture, TestActorSystem, TestExecutionContext} import org.specs2.mutable.SpecificationLike import org.specs2.specification.Scope import scala.concurrent.Future class FormSupportSpec extends TestActorSystem with SpecificationLike with AwaitableFuture with TestExecutionContext { case class MyTest(a: String, b: String, c: String, d: Boolean) implicit object MyTestFromMap extends FromMap[MyTest] { def apply(m: Map[String, String]) = for { a <- m.get("a") b <- m.get("b") c <- m.get("c") d <- m.get("d") } yield MyTest(a, b, c, toBoolean(d)) } abstract class FormSupportContext extends Scope def buildResponse(text: String): HttpResponse = HttpResponse(entity = HttpEntity.apply(ContentTypes.`text/html(UTF-8)`, text)) "FormSupport" should { "unmarshall a well-formed text into a case class" in new FormSupportContext { val text = "a=hello&c=test&b=foobar&d=true" val result: Future[MyTest] = FormSupport.unmarshallText[MyTest](buildResponse(text)) result.await === MyTest(a = "hello", b = "foobar", c = "test", d = true) } "throw TwitterException if text is not well formed" in new FormSupportContext { val text = "non-well-formed-string" val result: Future[MyTest] = FormSupport.unmarshallText[MyTest](buildResponse(text)) result.await should throwA[TwitterException] } } }
Example 23
Source File: RedocAkkaHttp.scala From tapir with Apache License 2.0 | 5 votes |
package sttp.tapir.redoc.akkahttp import akka.http.scaladsl.model.{ContentTypes, HttpCharsets, HttpEntity, MediaType, StatusCodes} import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.Route class RedocAkkaHttp(title: String, yaml: String, yamlName: String = "docs.yaml", redocVersion: String = "2.0.0-rc.23") { lazy val html: String = s""" |<!DOCTYPE html> |<html> |<head> | <title>${title}</title> | <!-- needed for adaptive design --> | <meta charset="utf-8"/> | <meta name="viewport" content="width=device-width, initial-scale=1"> | <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet"> | | <!-- | ReDoc doesn't change outer page styles | --> | <style> | body { | margin: 0; | padding: 0; | } | </style> |</head> |<body> |<redoc spec-url='${yamlName}' expand-responses="200,201"></redoc> |<script src="https://cdn.jsdelivr.net/npm/redoc@${redocVersion}/bundles/redoc.standalone.js"></script> |</body> |</html> |""".stripMargin def routes: Route = { get { pathEnd { redirectToTrailingSlashIfMissing(StatusCodes.MovedPermanently) { complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, html)) } } ~ pathSingleSlash { complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, html)) } ~ path(yamlName) { complete(HttpEntity(MediaType.textWithFixedCharset("yaml", HttpCharsets.`UTF-8`), yaml)) } } } }
Example 24
Source File: ModelServiceIntegrationSpec.scala From full-scala-stack with Apache License 2.0 | 5 votes |
package api import akka.http.scaladsl.model.{ContentTypes, HttpEntity} import akka.http.scaladsl.testkit.ScalatestRouteTest import de.heikoseeberger.akkahttpupickle.UpickleSupport import model.{SampleModelObject, SimpleSearch} import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.{AnyWordSpec, AnyWordSpecLike} import routes.ModelRoutes import upickle.default._ import util.ModelPickler import scala.concurrent.ExecutionContext class ModelServiceIntegrationSpec extends AnyWordSpec with Matchers with ScalatestRouteTest with ZIODirectives with UpickleSupport with ModelPickler { val service = new ModelRoutes with LiveEnvironment //TODO test your route here, we would probably not have a test like the one below in reality, since it's super simple. "The Service" should { "return one objects on a get" in { Get("/api/sampleModelObject/1") ~> service.apiRoute("") ~> check { val res = responseAs[Seq[SampleModelObject]].headOption println(res) assert(res.nonEmpty) } } "return some objects on a search" in { Post("/api/sampleModelObject/search", HttpEntity(ContentTypes.`application/json`, write(SimpleSearch()))) ~> service.apiRoute("") ~> check { val str = responseAs[ujson.Value] val res = responseAs[Seq[SampleModelObject]] println(res) assert(res.nonEmpty) } } } }
Example 25
Source File: ModelServiceSpec.scala From full-scala-stack with Apache License 2.0 | 5 votes |
package api import akka.http.scaladsl.marshalling.Marshal import akka.http.scaladsl.model.{ContentType, ContentTypes, HttpEntity, HttpResponse, MessageEntity, RequestEntity} import akka.http.scaladsl.testkit.ScalatestRouteTest import dao.{CRUDOperations, MockRepository, Repository} import de.heikoseeberger.akkahttpupickle.UpickleSupport import mail.{CourierPostman, Postman} import model.{SampleModelObject, SimpleSearch} import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec import routes.{ModelRoutes, SampleModelObjectRoute} import upickle.default._ import util.ModelPickler import zio.{IO, ZIO} import zioslick.RepositoryException import scala.concurrent.ExecutionContext class ModelServiceSpec extends AnyWordSpec with Matchers with ScalatestRouteTest with ZIODirectives with UpickleSupport with ModelPickler { val objects = Seq( SampleModelObject(0, "Zero"), SampleModelObject(1, "One"), SampleModelObject(2, "Two"), SampleModelObject(3, "Three"), SampleModelObject(4, "Four"), ) val service = new SampleModelObjectRoute with MockRepository with CourierPostman with Config { override def repository: Repository.Service = new Repository.Service { override val sampleModelObjectOps: CRUDOperations[SampleModelObject, Int, SimpleSearch, Any] = new MockOps { override def search(search: Option[SimpleSearch])( implicit session: Any ): IO[RepositoryException, Seq[SampleModelObject]] = ZIO.succeed(objects) override def get(pk: Int)(implicit session: Any): IO[RepositoryException, Option[SampleModelObject]] = ZIO.succeed(objects.headOption) } } } //TODO test your route here, we would probably not have a test like the one below in reality, since it's super simple. "The Service" should { "return one objects on a get" in { Get("/sampleModelObject/1") ~> service.crudRoute.route("") ~> check { val res = responseAs[Seq[SampleModelObject]].headOption println(res) res shouldEqual objects.headOption } } "return some objects on a search" in { Post("/sampleModelObject/search", HttpEntity(ContentTypes.`application/json`, write(SimpleSearch()))) ~> service.crudRoute.route("") ~> check { val str = responseAs[ujson.Value] val res = responseAs[Seq[SampleModelObject]] println(res) res shouldEqual objects } } } }
Example 26
Source File: StaticResource.scala From sumobot with Apache License 2.0 | 5 votes |
package com.sumologic.sumobot.http_frontend import akka.http.scaladsl.model.{ContentType, ContentTypes, HttpCharsets, MediaTypes} import org.apache.commons.io.IOUtils object StaticResource { private[http_frontend] val DefaultContentType = ContentTypes.`text/html(UTF-8)` case class ContentTypePair(extension: String, contentType: ContentType) private[http_frontend] val KnownContentTypes = Array( ContentTypePair(".html", ContentTypes.`text/html(UTF-8)`), ContentTypePair(".css", ContentType(MediaTypes.`text/css`, HttpCharsets.`UTF-8`)), ContentTypePair(".js", ContentType(MediaTypes.`application/javascript`, HttpCharsets.`UTF-8`)) ) } case class StaticResource(filename: String) { def contents: Array[Byte] = { val stream = getClass.getResourceAsStream(filename) val result = IOUtils.toByteArray(stream) stream.close() result } def contentType: ContentType = { val contentType = StaticResource.KnownContentTypes.find(contentType => filename.endsWith(contentType.extension)) .map(contentTypePair => contentTypePair.contentType) contentType.getOrElse(StaticResource.DefaultContentType) } }
Example 27
Source File: DynamicResource.scala From sumobot with Apache License 2.0 | 5 votes |
package com.sumologic.sumobot.http_frontend import akka.http.scaladsl.model.{ContentType, ContentTypes} import org.apache.commons.io.IOUtils import org.fusesource.scalate.TemplateEngine import org.fusesource.scalate.util.{FileResourceLoader, Resource} object DynamicResource { private val Engine = new TemplateEngine Engine.allowReload = false Engine.allowCaching = true Engine.resourceLoader = new FileResourceLoader { override def resource(filename: String): Option[Resource] = { val uri = getClass.getResource(filename).toURI.toString val stream = getClass.getResourceAsStream(filename) val templateText = IOUtils.toString(stream) stream.close() Some(Resource.fromText(uri, templateText)) } } } case class DynamicResource(templateFile: String) { DynamicResource.Engine.load(templateFile) def contents(templateVariables: Map[String, Any]): String = { DynamicResource.Engine.layout(templateFile, templateVariables) } val contentType: ContentType.NonBinary = ContentTypes.`text/html(UTF-8)` }
Example 28
Source File: StaticResourceTest.scala From sumobot with Apache License 2.0 | 5 votes |
package com.sumologic.sumobot.http_frontend import akka.http.scaladsl.model.{ContentType, ContentTypes, HttpCharsets, MediaTypes} import com.sumologic.sumobot.test.annotated.SumoBotSpec class StaticResourceTest extends SumoBotSpec { "StaticResource" should { "return correct content type" when { "passing .html file" in { StaticResource("test.html").contentType should be(ContentTypes.`text/html(UTF-8)`) } "passing .css file" in { StaticResource("test.css").contentType should be(ContentType(MediaTypes.`text/css`, HttpCharsets.`UTF-8`)) } "passing unknown extension" in { StaticResource("test.unknown").contentType should be(ContentTypes.`text/html(UTF-8)`) } } } }
Example 29
Source File: SumTypedEntitiesTestSuite.scala From endpoints4s with MIT License | 5 votes |
package endpoints4s.algebra.server import akka.http.scaladsl.model.{ContentTypes, HttpMethods, HttpRequest} import endpoints4s.algebra trait SumTypedEntitiesTestSuite[ T <: algebra.SumTypedEntitiesTestApi ] extends ServerTestBase[T] { "Sum typed route" should { "handle `text/plain` content-type requests" in { serveIdentityEndpoint(serverApi.sumTypedEndpoint) { port => val request = HttpRequest(HttpMethods.POST, s"http://localhost:$port/user-or-name") .withEntity(ContentTypes.`text/plain(UTF-8)`, "Alice") whenReady(sendAndDecodeEntityAsText(request)) { case (response, entity) => assert(response.status.intValue() == 200) assert( response.entity.contentType == ContentTypes.`text/plain(UTF-8)` ) entity shouldEqual "Alice" } () } } "handle `application/json` content-type requests" in { serveIdentityEndpoint(serverApi.sumTypedEndpoint) { port => val request = HttpRequest(HttpMethods.POST, s"http://localhost:$port/user-or-name") .withEntity( ContentTypes.`application/json`, "{\"name\":\"Alice\",\"age\":42}" ) whenReady(sendAndDecodeEntityAsText(request)) { case (response, entity) => assert(response.status.intValue() == 200) assert( response.entity.contentType == ContentTypes.`application/json` ) ujson.read(entity) shouldEqual ujson.Obj( "name" -> ujson.Str("Alice"), "age" -> ujson.Num(42) ) } () } } "handle `application/json` content-type requests with malformed bodies" in { serveIdentityEndpoint(serverApi.sumTypedEndpoint) { port => val request = HttpRequest(HttpMethods.POST, s"http://localhost:$port/user-or-name") .withEntity( ContentTypes.`application/json`, "{\"name\":\"Alice\"}" ) whenReady(sendAndDecodeEntityAsText(request)) { case (response, entity) => assert(response.status.intValue() == 400) } () } } "not handle `application/x-www-form-urlencoded` content-type requests" in { serveIdentityEndpoint(serverApi.sumTypedEndpoint) { port => val request = HttpRequest(HttpMethods.POST, s"http://localhost:$port/user-or-name") .withEntity( ContentTypes.`application/x-www-form-urlencoded`, "name=Alice&age=42" ) whenReady(sendAndDecodeEntityAsText(request)) { case (response, _) => assert(response.status.intValue() == 415) } () } } } }
Example 30
Source File: ValidationRoute.scala From ohara with Apache License 2.0 | 5 votes |
package oharastream.ohara.configurator.route import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ import akka.http.scaladsl.model.{ContentTypes, _} import akka.http.scaladsl.server import akka.http.scaladsl.server.Directives.{as, complete, entity, path, pathPrefix, put, _} import oharastream.ohara.agent.WorkerCollie import oharastream.ohara.client.configurator.ConnectorApi import oharastream.ohara.client.configurator.ConnectorApi.Creation import oharastream.ohara.client.configurator.ValidationApi._ import oharastream.ohara.configurator.store.DataStore import scala.concurrent.ExecutionContext private[configurator] object ValidationRoute { def apply( implicit dataStore: DataStore, workerCollie: WorkerCollie, executionContext: ExecutionContext ): server.Route = pathPrefix(VALIDATION_KIND) { path(ConnectorApi.KIND) { put { entity(as[Creation])( req => complete( connectorAdmin(req.workerClusterKey) { (_, connectorAdmin) => connectorAdmin .connectorValidator() .settings(req.plain) .className(req.className) // the topic name is composed by group and name. However, the kafka topic is still a pure string. // Hence, we can't just push Ohara topic "key" to kafka topic "name". // The name of topic is a required for connector and hence we have to fill the filed when starting // connector. .topicKeys(req.topicKeys) // add the connector key manually since the arguments exposed to user is "group" and "name" than "key" .connectorKey(req.key) .run() }.map(settingInfo => HttpEntity(ContentTypes.`application/json`, settingInfo.toJsonString)) ) ) } } } }
Example 31
Source File: Registry.scala From kanadi with MIT License | 5 votes |
package org.zalando.kanadi.api import java.net.URI import defaults._ import akka.http.scaladsl.HttpExt import akka.http.scaladsl.model.headers.RawHeader import akka.http.scaladsl.model.{ContentTypes, HttpMethods, HttpRequest, Uri} import akka.http.scaladsl.unmarshalling.Unmarshal import akka.stream.Materializer import com.typesafe.scalalogging.{Logger, LoggerTakingImplicit} import de.heikoseeberger.akkahttpcirce.ErrorAccumulatingCirceSupport._ import org.mdedetrich.webmodels.{FlowId, OAuth2TokenProvider} import org.mdedetrich.webmodels.RequestHeaders.`X-Flow-ID` import org.zalando.kanadi.models._ import scala.concurrent.{ExecutionContext, Future} case class Registry(baseUri: URI, oAuth2TokenProvider: Option[OAuth2TokenProvider] = None)(implicit kanadiHttpConfig: HttpConfig, http: HttpExt, materializer: Materializer) extends RegistryInterface { protected val logger: LoggerTakingImplicit[FlowId] = Logger.takingImplicit[FlowId](classOf[Registry]) private val baseUri_ = Uri(baseUri.toString) def partitionStrategies(implicit flowId: FlowId = randomFlowId(), executionContext: ExecutionContext): Future[List[PartitionStrategy]] = { val uri = baseUri_.withPath(baseUri_.path / "registry" / "partition-strategies") val baseHeaders = List(RawHeader(`X-Flow-ID`, flowId.value)) for { headers <- oAuth2TokenProvider match { case None => Future.successful(baseHeaders) case Some(futureProvider) => futureProvider.value().map { oAuth2Token => toHeader(oAuth2Token) +: baseHeaders } } request = HttpRequest(HttpMethods.GET, uri, headers) _ = logger.debug(request.toString) response <- http.singleRequest(request) result <- { if (response.status.isSuccess()) { Unmarshal(response.entity.httpEntity.withContentType(ContentTypes.`application/json`)) .to[List[PartitionStrategy]] } else processNotSuccessful(request, response) } } yield result } }
Example 32
Source File: S2GraphMutateRoute.scala From incubator-s2graph with Apache License 2.0 | 5 votes |
package org.apache.s2graph.http import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpResponse, StatusCodes} import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.{ExceptionHandler, Route} import com.fasterxml.jackson.core.JsonParseException import org.apache.s2graph.core.rest.RequestParser import org.apache.s2graph.core.storage.MutateResponse import org.apache.s2graph.core.{GraphElement, S2Graph} import org.slf4j.LoggerFactory import play.api.libs.json.{JsValue, Json} import scala.concurrent.{ExecutionContext, Future} trait S2GraphMutateRoute extends PlayJsonSupport { val s2graph: S2Graph val logger = LoggerFactory.getLogger(this.getClass) lazy val parser = new RequestParser(s2graph) lazy val exceptionHandler = ExceptionHandler { case ex: JsonParseException => complete(StatusCodes.BadRequest -> ex.getMessage) case ex: java.lang.IllegalArgumentException => complete(StatusCodes.BadRequest -> ex.getMessage) } lazy val mutateVertex = path("vertex" / Segments) { params => implicit val ec = s2graph.ec val (operation, serviceNameOpt, columnNameOpt) = params match { case operation :: serviceName :: columnName :: Nil => (operation, Option(serviceName), Option(columnName)) case operation :: Nil => (operation, None, None) case _ => throw new RuntimeException("invalid params") } entity(as[JsValue]) { payload => val future = vertexMutate(payload, operation, serviceNameOpt, columnNameOpt).map(Json.toJson(_)) complete(future) } } lazy val mutateEdge = path("edge" / Segment) { operation => implicit val ec = s2graph.ec entity(as[JsValue]) { payload => val future = edgeMutate(payload, operation, withWait = true).map(Json.toJson(_)) complete(future) } } def vertexMutate(jsValue: JsValue, operation: String, serviceNameOpt: Option[String] = None, columnNameOpt: Option[String] = None, withWait: Boolean = true)(implicit ec: ExecutionContext): Future[Seq[Boolean]] = { val vertices = parser.toVertices(jsValue, operation, serviceNameOpt, columnNameOpt) val verticesToStore = vertices.filterNot(_.isAsync) s2graph.mutateVertices(verticesToStore, withWait).map(_.map(_.isSuccess)) } def edgeMutate(elementsWithTsv: Seq[(GraphElement, String)], withWait: Boolean)(implicit ec: ExecutionContext): Future[Seq[Boolean]] = { val elementWithIdxs = elementsWithTsv.zipWithIndex val (elementSync, elementAsync) = elementWithIdxs.partition { case ((element, tsv), idx) => !element.isAsync } val retToSkip = elementAsync.map(_._2 -> MutateResponse.Success) val (elementsToStore, _) = elementSync.map(_._1).unzip val elementsIdxToStore = elementSync.map(_._2) s2graph.mutateElements(elementsToStore, withWait).map { mutateResponses => elementsIdxToStore.zip(mutateResponses) ++ retToSkip }.map(_.sortBy(_._1).map(_._2.isSuccess)) } def edgeMutate(jsValue: JsValue, operation: String, withWait: Boolean)(implicit ec: ExecutionContext): Future[Seq[Boolean]] = { val edgesWithTsv = parser.parseJsonFormat(jsValue, operation) edgeMutate(edgesWithTsv, withWait) } // expose routes lazy val mutateRoute: Route = post { concat( handleExceptions(exceptionHandler) { mutateVertex }, handleExceptions(exceptionHandler) { mutateEdge } ) } }
Example 33
Source File: Server.scala From incubator-s2graph with Apache License 2.0 | 5 votes |
package org.apache.s2graph.http import java.time.Instant import scala.language.postfixOps import scala.concurrent.{Await, ExecutionContext, Future} import scala.concurrent.duration.Duration import scala.util.{Failure, Success} import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpResponse, StatusCodes} import akka.http.scaladsl.server.Route import akka.http.scaladsl.server.Directives._ import akka.stream.ActorMaterializer import com.typesafe.config.ConfigFactory import org.apache.s2graph.core.S2Graph import org.slf4j.LoggerFactory object Server extends App with S2GraphTraversalRoute with S2GraphAdminRoute with S2GraphMutateRoute with S2GraphQLRoute { implicit val system: ActorSystem = ActorSystem("S2GraphHttpServer") implicit val materializer: ActorMaterializer = ActorMaterializer() implicit val executionContext: ExecutionContext = system.dispatcher val config = ConfigFactory.load() override val s2graph = new S2Graph(config) override val logger = LoggerFactory.getLogger(this.getClass) val port = sys.props.get("http.port").fold(8000)(_.toInt) val interface = sys.props.get("http.interface").fold("0.0.0.0")(identity) val startAt = System.currentTimeMillis() def uptime = System.currentTimeMillis() - startAt def serverHealth = s"""{ "port": ${port}, "interface": "${interface}", "started_at": ${Instant.ofEpochMilli(startAt)}, "uptime": "${uptime} millis" """ def health = HttpResponse(status = StatusCodes.OK, entity = HttpEntity(ContentTypes.`application/json`, serverHealth)) // Allows you to determine routes to expose according to external settings. lazy val routes: Route = concat( pathPrefix("graphs")(traversalRoute), pathPrefix("mutate")(mutateRoute), pathPrefix("admin")(adminRoute), pathPrefix("graphql")(graphqlRoute), get(complete(health)) ) val binding: Future[Http.ServerBinding] = Http().bindAndHandle(routes, interface, port) binding.onComplete { case Success(bound) => logger.info(s"Server online at http://${bound.localAddress.getHostString}:${bound.localAddress.getPort}/") case Failure(e) => logger.error(s"Server could not start!", e) } scala.sys.addShutdownHook { () => s2graph.shutdown() system.terminate() logger.info("System terminated") } Await.result(system.whenTerminated, Duration.Inf) }
Example 34
Source File: OrderBookHttpInfo.scala From matcher with MIT License | 5 votes |
package com.wavesplatform.dex.api.http import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpResponse, StatusCodes} import com.wavesplatform.dex.actors.OrderBookAskAdapter import com.wavesplatform.dex.actors.orderbook.AggregatedOrderBookActor.Depth import com.wavesplatform.dex.api.http.entities.MatcherResponse.toHttpResponse import com.wavesplatform.dex.api.http.entities.{HttpMarketStatus, HttpOrderBook, OrderBookUnavailable, SimpleResponse} import com.wavesplatform.dex.domain.asset.{Asset, AssetPair} import com.wavesplatform.dex.model.MatcherModel.{DecimalsFormat, Denormalized} import com.wavesplatform.dex.time.Time import play.api.libs.json.Json import scala.concurrent.{ExecutionContext, Future} class OrderBookHttpInfo(settings: OrderBookHttpInfo.Settings, askAdapter: OrderBookAskAdapter, time: Time, assetDecimals: Asset => Option[Int])( implicit ec: ExecutionContext) { private val marketStatusNotFound = toHttpResponse( SimpleResponse(StatusCodes.NotFound, Json.obj("message" -> "There is no information about this asset pair")) ) def getMarketStatus(assetPair: AssetPair): Future[HttpResponse] = askAdapter.getMarketStatus(assetPair).map { case Left(e) => toHttpResponse(OrderBookUnavailable(e)) case Right(maybeMarketStatus) => maybeMarketStatus match { case Some(ms) => toHttpResponse(SimpleResponse(HttpMarketStatus fromMarketStatus ms)) case None => marketStatusNotFound } } def getHttpView(assetPair: AssetPair, format: DecimalsFormat, depth: Option[Depth]): Future[HttpResponse] = askAdapter.getHttpView(assetPair, format, settings.nearestBigger(depth)).map { case Right(x) => x.getOrElse(getDefaultHttpView(assetPair, format)) case Left(e) => toHttpResponse(OrderBookUnavailable(e)) } private def getDefaultHttpView(assetPair: AssetPair, format: DecimalsFormat): HttpResponse = { val entity = HttpOrderBook(time.correctedTime(), assetPair, Seq.empty, Seq.empty, assetPairDecimals(assetPair, format)) HttpResponse( entity = HttpEntity( ContentTypes.`application/json`, HttpOrderBook.toJson(entity) ) ) } private def assetPairDecimals(assetPair: AssetPair, format: DecimalsFormat): Option[(Depth, Depth)] = format match { case Denormalized => assetDecimals(assetPair.amountAsset).zip(assetDecimals(assetPair.priceAsset)).headOption case _ => None } } object OrderBookHttpInfo { case class Settings(depthRanges: List[Int], defaultDepth: Option[Int]) { def nearestBigger(to: Option[Int]): Int = to.orElse(defaultDepth) .flatMap(desiredDepth => depthRanges.find(_ >= desiredDepth)) .getOrElse(depthRanges.max) } }
Example 35
Source File: LogCollectorRoutes.scala From pulse with Apache License 2.0 | 5 votes |
package io.phdata.pulse.logcollector import akka.http.scaladsl.common.EntityStreamingSupport import akka.http.scaladsl.model.{ ContentTypes, HttpEntity, StatusCodes } import akka.http.scaladsl.server.Directives._ import com.typesafe.scalalogging.LazyLogging import io.phdata.pulse.common.domain.{ LogEvent, TimeseriesRequest } post { // create a streaming Source from the incoming json string entity(as[TimeseriesRequest]) { eventRequest => kuduService .map { client => eventRequest.payload.map(event => client.save(eventRequest.table_name, List(event))) } .getOrElse(complete(StatusCodes.NotImplemented)) complete(HttpEntity(ContentTypes.`application/json`, "ok")) } } } }
Example 36
Source File: ApplicationApiRouteTest.scala From Sidechains-SDK with MIT License | 5 votes |
package com.horizen.api.http import akka.http.scaladsl.model.{ContentTypes, StatusCodes} import akka.http.scaladsl.server.Route import org.junit.Assert.{assertEquals, assertTrue} import scala.collection.JavaConverters._ class ApplicationApiRouteTest extends SidechainApiRouteTest { override val basePath = "/simpleApi/" "The Api should to" should { "reject and reply with http error" in { Get(basePath) ~> Route.seal(applicationApiRoute) ~> check { status.intValue() shouldBe StatusCodes.NotFound.intValue responseEntity.getContentType() shouldEqual ContentTypes.`application/json` } } "reply at /allSecrets" in { Post(basePath + "allSecrets") ~> applicationApiRoute ~> check { status.intValue() shouldBe StatusCodes.OK.intValue responseEntity.getContentType() shouldEqual ContentTypes.`application/json` mapper.readTree(entityAs[String]).get("result") match { case result => assertEquals(1, result.elements().asScala.length) assertTrue(result.get("secrets").isArray) assertEquals(2, result.get("secrets").elements().asScala.length) result.get("secrets").elements().asScala.toList.foreach(node => { assertTrue(node.isObject) assertEquals(0, node.elements().asScala.length) }) case _ => fail("Serialization failed for object SidechainApiResponseBody") } } sidechainApiMockConfiguration.setShould_nodeViewHolder_GetDataFromCurrentSidechainNodeView_reply(false) Post(basePath + "allSecrets") ~> applicationApiRoute ~> check { status.intValue() shouldBe StatusCodes.OK.intValue responseEntity.getContentType() shouldEqual ContentTypes.`application/json` assertsOnSidechainErrorResponseSchema(entityAs[String], new ErrorAllSecrets("", None).code()) } } } }
Example 37
Source File: SidechainRejectionApiRouteTest.scala From Sidechains-SDK with MIT License | 5 votes |
package com.horizen.api.http import akka.http.scaladsl.model.{ContentTypes, StatusCodes} import akka.http.scaladsl.server._ import Directives._ class SidechainRejectionApiRouteTest extends SidechainApiRouteTest { override val basePath: String = "/wallet/" "The Api should to" should { "reply at /balance" in { Post(basePath + "balance") ~> (sidechainWalletApiRoute ~ walletBalanceApiRejected) ~> check { response shouldEqual ((Post(basePath + "balance") ~> sidechainWalletApiRoute).response) } } "reject and reply with http error" in { Post(basePath + "balance") ~> Route.seal({ walletBalanceApiRejected ~ sidechainWalletApiRoute }) ~> check { status.intValue() shouldBe StatusCodes.NotFound.intValue responseEntity.getContentType() shouldEqual ContentTypes.`application/json` } Post(basePath + "balance") ~> Route.seal({ walletApiRejected ~ sidechainWalletApiRoute }) ~> check { status.intValue() shouldBe StatusCodes.NotFound.intValue responseEntity.getContentType() shouldEqual ContentTypes.`application/json` } Post(basePath) ~> Route.seal({ walletApiRejected ~ sidechainWalletApiRoute }) ~> check { status.intValue() shouldBe StatusCodes.NotFound.intValue responseEntity.getContentType() shouldEqual ContentTypes.`application/json` } } } }
Example 38
Source File: EncryBaseApiRoute.scala From EncryCore with GNU General Public License v3.0 | 5 votes |
package encry.api.http.routes import akka.http.scaladsl.model.{ContentTypes, HttpEntity, StatusCodes} import akka.http.scaladsl.server.{Directive, Directive1, Route} import encry.api.http.ApiRoute import io.circe.Json import org.encryfoundation.common.crypto.encoding.Base58Check import org.encryfoundation.common.modifiers.mempool.transaction.EncryAddress.Address import org.encryfoundation.common.utils.Algos import org.encryfoundation.common.utils.TaggedTypes.{ADKey, ModifierId} import scala.concurrent.{ExecutionContextExecutor, Future} import scala.util.Success trait EncryBaseApiRoute extends ApiRoute { implicit val ec: ExecutionContextExecutor = context.dispatcher protected def toJsonResponse(js: Json): Route = { val resp = complete(HttpEntity(ContentTypes.`application/json`, js.spaces2)) withCors(resp) } protected def toJsonResponse(fn: Future[Json]): Route = onSuccess(fn) { toJsonResponse } protected def toJsonOptionalResponse(fn: Future[Option[Json]]): Route = { onSuccess(fn) { case Some(v) => toJsonResponse(v) case None => withCors(complete(StatusCodes.NotFound)) } } val paging: Directive[(Int, Int)] = parameters("offset".as[Int] ? 0, "limit".as[Int] ? 50) val modifierId: Directive1[ModifierId] = pathPrefix(Segment).flatMap { h => Algos.decode(h) match { case Success(header) => provide(ModifierId @@ header) case _ => reject } } implicit class OkJsonResp(fn: Future[Json]) { def okJson(): Route = toJsonResponse(fn) } implicit class OkJsonOptResp(fn: Future[Option[Json]]) { def okJson(): Route = toJsonOptionalResponse(fn) } }
Example 39
Source File: HydraKafkaJsonSupport.scala From hydra with Apache License 2.0 | 5 votes |
package hydra.kafka.marshallers import akka.http.scaladsl.marshalling.{Marshaller, Marshalling} import akka.http.scaladsl.model.ContentTypes import akka.util.ByteString import hydra.core.marshallers.HydraJsonSupport import org.apache.kafka.common.{Node, PartitionInfo} import spray.json.{JsNumber, JsObject, JsString, JsValue, JsonFormat} import scala.concurrent.Future trait HydraKafkaJsonSupport extends HydraJsonSupport { implicit object NodeJsonFormat extends JsonFormat[Node] { override def write(node: Node): JsValue = { JsObject( "id" -> JsNumber(node.idString), "host" -> JsString(node.host), "port" -> JsNumber(node.port) ) } override def read(json: JsValue): Node = { json.asJsObject.getFields("id", "host", "port") match { case Seq(id, host, port) => new Node( id.convertTo[Int], host.convertTo[String], port.convertTo[Int] ) case other => spray.json.deserializationError( "Cannot deserialize Node. Invalid input: " + other ) } } } implicit object PartitionInfoJsonFormat extends JsonFormat[PartitionInfo] { import spray.json._ override def write(p: PartitionInfo): JsValue = { JsObject( "partition" -> JsNumber(p.partition()), "leader" -> p.leader().toJson, "isr" -> JsArray(p.inSyncReplicas().toJson) ) } override def read(json: JsValue): PartitionInfo = ??? } implicit val stringFormat = Marshaller[String, ByteString] { ec ⇒ s => Future.successful { List( Marshalling.WithFixedContentType( ContentTypes.`application/json`, () => ByteString(s) ) ) } } }
Example 40
Source File: DropwizardMarshallers.scala From akka-http-metrics with Apache License 2.0 | 5 votes |
package fr.davit.akka.http.metrics.dropwizard.marshalling import java.io.StringWriter import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller} import akka.http.scaladsl.model.{ContentTypes, HttpEntity} import com.fasterxml.jackson.databind.ObjectMapper import fr.davit.akka.http.metrics.dropwizard.DropwizardRegistry trait DropwizardMarshallers { implicit val registryToEntityMarshaller: ToEntityMarshaller[DropwizardRegistry] = { val writer = new ObjectMapper().writer() Marshaller.opaque { registry => val output = new StringWriter() try { writer.writeValue(output, registry.underlying) HttpEntity(output.toString).withContentType(ContentTypes.`application/json`) } finally { output.close() } } } } object DropwizardMarshallers extends DropwizardMarshallers
Example 41
Source File: AkkaHttpBackend.scala From drunk with Apache License 2.0 | 5 votes |
package com.github.jarlakxen.drunk.backend import scala.collection.immutable import scala.concurrent.{ExecutionContext, Future} import akka.actor.ActorSystem import akka.http.scaladsl.{Http, HttpExt} import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpHeader, HttpMethods, HttpRequest, Uri} import akka.stream.ActorMaterializer class AkkaHttpBackend private[AkkaHttpBackend] ( uri: Uri, headers: immutable.Seq[HttpHeader], httpExt: HttpExt )(override implicit val as: ActorSystem, override implicit val mat: ActorMaterializer) extends AkkaBackend { def send(body: String): Future[(Int, String)] = { implicit val ec: ExecutionContext = as.dispatcher val req = HttpRequest(HttpMethods.POST, uri, headers, HttpEntity(ContentTypes.`application/json`, body)) val res = httpExt.singleRequest(req) res.flatMap { hr => val code = hr.status.intValue() val charsetFromHeaders = encodingFromContentType(hr.entity.contentType.toString).getOrElse("utf-8") val decodedResponse = decodeResponse(hr) val stringBody = bodyToString(decodedResponse, charsetFromHeaders) if (code >= 200 && code < 300) { stringBody.map { body => hr.discardEntityBytes() (code, body) } } else { stringBody.flatMap { body => hr.discardEntityBytes() Future.failed(new RuntimeException(s"${uri.toString} return $code with body: $body")) } } } } } object AkkaHttpBackend { val ContentTypeHeader = "Content-Type" def apply( uri: Uri, headers: immutable.Seq[HttpHeader] = Nil, httpExt: Option[HttpExt] = None )(implicit as: ActorSystem, mat: ActorMaterializer): AkkaHttpBackend = { val http = httpExt.getOrElse { Http(as) } new AkkaHttpBackend(uri, headers, http) } }
Example 42
Source File: CsvStreamingRoute.scala From akka-http-test with Apache License 2.0 | 5 votes |
package com.github.dnvriend.component.simpleserver.route import akka.http.scaladsl.common.{ CsvEntityStreamingSupport, EntityStreamingSupport } import akka.http.scaladsl.marshalling.{ Marshaller, Marshalling } import akka.http.scaladsl.model.ContentTypes import akka.http.scaladsl.server.{ Directives, Route } import akka.util.ByteString import com.github.dnvriend.component.repository.PersonRepository import com.github.dnvriend.component.simpleserver.dto.http.Person import de.heikoseeberger.akkahttpplayjson.PlayJsonSupport object CsvStreamingRoute extends Directives with PlayJsonSupport { implicit val personAsCsv = Marshaller.strict[Person, ByteString] { person => Marshalling.WithFixedContentType(ContentTypes.`text/csv(UTF-8)`, () => { ByteString(List(person.name.replace(",", "."), person.age, person.married).mkString(",")) }) } implicit val csvStreamingSupport: CsvEntityStreamingSupport = EntityStreamingSupport.csv() def route(dao: PersonRepository): Route = path("stream" / IntNumber) { numberOfPeople => pathEnd { get { complete(dao.people(numberOfPeople)) } } } }
Example 43
Source File: SinkRouteHandler.scala From ohara with Apache License 2.0 | 5 votes |
package oharastream.ohara.shabondi.sink import java.time.{Duration => JDuration} import java.util.concurrent.TimeUnit import akka.actor.ActorSystem import akka.http.scaladsl.model.{ContentTypes, HttpEntity, StatusCodes} import akka.http.scaladsl.server.{ExceptionHandler, Route} import com.typesafe.scalalogging.Logger import oharastream.ohara.common.data.Row import oharastream.ohara.common.util.Releasable import oharastream.ohara.shabondi.common.{JsonSupport, RouteHandler, ShabondiUtils} import org.apache.commons.lang3.StringUtils import scala.collection.mutable.ArrayBuffer import scala.compat.java8.DurationConverters._ import scala.concurrent.ExecutionContextExecutor import scala.concurrent.duration.Duration import spray.json.DefaultJsonProtocol._ import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._ private[shabondi] object SinkRouteHandler { def apply(config: SinkConfig)(implicit actorSystem: ActorSystem) = new SinkRouteHandler(config) } private[shabondi] class SinkRouteHandler(config: SinkConfig)(implicit actorSystem: ActorSystem) extends RouteHandler { implicit private val contextExecutor: ExecutionContextExecutor = actorSystem.dispatcher private val log = Logger(classOf[SinkRouteHandler]) private[sink] val dataGroups = SinkDataGroups(config) def scheduleFreeIdleGroups(interval: JDuration, idleTime: JDuration): Unit = actorSystem.scheduler.scheduleWithFixedDelay(Duration(1, TimeUnit.SECONDS), interval.toScala) { () => { log.trace("scheduled free group, total group: {} ", dataGroups.size) dataGroups.freeIdleGroup(idleTime) } } private val exceptionHandler = ExceptionHandler { case ex: Throwable => log.error(ex.getMessage, ex) complete((StatusCodes.InternalServerError, ex.getMessage)) } private def fullyPollQueue(queue: RowQueue): Seq[Row] = { val buffer = ArrayBuffer.empty[Row] var item: Row = queue.poll() while (item != null) { buffer += item item = queue.poll() } buffer.toSeq } private def apiUrl = ShabondiUtils.apiUrl def route(): Route = handleExceptions(exceptionHandler) { path("groups" / Segment) { groupId => get { if (StringUtils.isAlphanumeric(groupId)) { val group = dataGroups.createIfAbsent(groupId) val result = fullyPollQueue(group.queue).map(row => JsonSupport.toRowData(row)) complete(result) } else { val entity = HttpEntity(ContentTypes.`text/plain(UTF-8)`, "Illegal group name, only accept alpha and numeric.") complete(StatusCodes.NotAcceptable -> entity) } } ~ { complete(StatusCodes.MethodNotAllowed -> s"Unsupported method, please reference: $apiUrl") } } ~ { complete(StatusCodes.NotFound -> s"Please reference: $apiUrl") } } override def close(): Unit = { Releasable.close(dataGroups) } }
Example 44
Source File: CounterTest.scala From endpoints4s with MIT License | 5 votes |
package quickstart import java.net.ServerSocket import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpMethods, HttpRequest, StatusCodes} import akka.http.scaladsl.server.Directives._ import org.scalatest.BeforeAndAfterAll import scala.concurrent.Await import scala.concurrent.duration.DurationInt import org.scalatest.freespec.AsyncFreeSpec class CounterTest extends AsyncFreeSpec with BeforeAndAfterAll { implicit val actorSystem: ActorSystem = ActorSystem() val routes = CounterServer.routes ~ DocumentationServer.routes val interface = "0.0.0.0" val port = findOpenPort() val server = Http().bindAndHandle(routes, interface, port) override protected def afterAll(): Unit = { Await.result( Await.result(server, 10.seconds).terminate(3.seconds), 15.seconds ) Await.result(actorSystem.terminate(), 5.seconds) super.afterAll() } "CounterServer" - { "Query counter value" in { for { response <- Http().singleRequest( HttpRequest(uri = uri("/current-value")) ) entity <- response.entity.toStrict(1.second) } yield { assert(response.status == StatusCodes.OK) assert(entity.contentType == ContentTypes.`application/json`) assert(entity.data.utf8String == "{\"value\":0}") } } "Increment counter value" in { val request = HttpRequest( method = HttpMethods.POST, uri = uri("/increment"), entity = HttpEntity(ContentTypes.`application/json`, "{\"step\":1}") ) for { response <- Http().singleRequest(request) } yield { assert(response.status == StatusCodes.OK) } } "Query API documentation" in { for { response <- Http().singleRequest( HttpRequest(uri = uri("/documentation.json")) ) entity <- response.entity.toStrict(1.second) } yield { assert(response.status == StatusCodes.OK) assert(entity.contentType == ContentTypes.`application/json`) } } } def findOpenPort(): Int = { val socket = new ServerSocket(0) try socket.getLocalPort finally if (socket != null) socket.close() } def uri(suffix: String) = s"http://$interface:$port$suffix" }
Example 45
Source File: ChunkedEntities.scala From endpoints4s with MIT License | 5 votes |
package endpoints4s.akkahttp.client import akka.http.scaladsl.model.{ContentType, ContentTypes, HttpEntity} import akka.stream.scaladsl.Source import akka.util.ByteString import endpoints4s.algebra import scala.concurrent.Future trait ChunkedJsonEntities extends algebra.ChunkedJsonEntities with ChunkedEntities with JsonEntitiesFromCodecs { def jsonChunksRequest[A](implicit codec: JsonCodec[A] ): RequestEntity[Chunks[A]] = { val encoder = stringCodec(codec) chunkedRequestEntity( ContentTypes.`application/json`, a => ByteString.fromString(encoder.encode(a)) ) } def jsonChunksResponse[A](implicit codec: JsonCodec[A] ): ResponseEntity[Chunks[A]] = { val decoder = stringCodec(codec) chunkedResponseEntity { byteString => val string = byteString.utf8String decoder .decode(string) .toEither .left .map(errors => new Throwable(errors.mkString(". "))) } } }
Example 46
Source File: ChunkedEntities.scala From endpoints4s with MIT License | 5 votes |
package endpoints4s.akkahttp.server import akka.http.scaladsl.marshalling.Marshaller import akka.http.scaladsl.model.{ContentType, ContentTypes, HttpEntity, HttpRequest, MessageEntity} import akka.http.scaladsl.server.Directives import akka.http.scaladsl.unmarshalling.Unmarshaller import akka.stream.scaladsl.Source import akka.util.ByteString import endpoints4s.algebra import scala.concurrent.Future trait ChunkedJsonEntities extends algebra.ChunkedJsonEntities with ChunkedEntities with JsonEntitiesFromCodecs { def jsonChunksRequest[A](implicit codec: JsonCodec[A] ): RequestEntity[Chunks[A]] = { val decoder = stringCodec(codec) chunkedRequestEntity { byteString => val string = byteString.utf8String decoder .decode(string) .toEither .left .map(errors => new Throwable(errors.mkString(". "))) } } def jsonChunksResponse[A](implicit codec: JsonCodec[A] ): ResponseEntity[Chunks[A]] = { val encoder = stringCodec(codec) chunkedResponseEntity( ContentTypes.`application/json`, a => ByteString(encoder.encode(a)) ) } }
Example 47
Source File: HttpClientTransformers.scala From wix-http-testkit with MIT License | 5 votes |
package com.wix.e2e.http.client.transformers import java.io.File import akka.http.scaladsl.model.{ContentType, ContentTypes, HttpCharsets, MediaTypes} import com.wix.e2e.http.client.transformers.internals._ trait HttpClientTransformers extends HttpClientRequestUrlTransformers with HttpClientRequestHeadersTransformers with HttpClientRequestBodyTransformers with HttpClientRequestTransformersOps object HttpClientTransformers extends HttpClientTransformers trait HttpClientContentTypes { val TextPlain = ContentTypes.`text/plain(UTF-8)` val JsonContent = ContentTypes.`application/json` val XmlContent = ContentType(MediaTypes.`application/xml`, HttpCharsets.`UTF-8`) val BinaryStream = ContentTypes.`application/octet-stream` val FormUrlEncoded = ContentTypes.`application/x-www-form-urlencoded` } object HttpClientContentTypes extends HttpClientContentTypes sealed trait RequestPart case class PlainRequestPart(body: String, contentType: ContentType = TextPlain) extends RequestPart case class BinaryRequestPart(body: Array[Byte], contentType: ContentType = BinaryStream, filename: Option[String] = None) extends RequestPart case class FileRequestPart(file: File, contentType: ContentType = BinaryStream, filename: Option[String] = None) extends RequestPart case class FileNameRequestPart(filepath: String, contentType: ContentType = BinaryStream, filename: Option[String] = None) extends RequestPart
Example 48
Source File: ApiVersionRoute.scala From scala-for-beginners with Apache License 2.0 | 5 votes |
package com.allaboutscala.donutstore.routes import akka.http.scaladsl.model.{ContentTypes, HttpEntity} import akka.http.scaladsl.server.Directives.{complete, get, path, _} import akka.http.scaladsl.server.Route import com.allaboutscala.donutstore.config.DonutStoreConfig import com.allaboutscala.donutstore.data.DataApi import scala.util.Try class ApiVersionRoute extends HttpRoute { import spray.json._ override def routes()(implicit config: DonutStoreConfig, dataApi: DataApi): Route = { val apiVersion = s""" |{ | "app": "${config.app}", | "version": "${config.httpServer.apiVersion}" |}""".stripMargin path("api-version") { get { parameter("prettyPrint" ? "true") { prettyPrint => // the prettyPrint parameter is optional and we also default to true val shouldPrettyPrint = Try(prettyPrint.toBoolean).getOrElse(true) // we'll default to pretty print val apiVersionOutput = if (shouldPrettyPrint) apiVersion.parseJson.prettyPrint else apiVersion.parseJson.toString complete(HttpEntity(ContentTypes.`application/json`, apiVersionOutput)) } } } } }
Example 49
Source File: ApiVersionRoute.scala From scala-for-beginners with Apache License 2.0 | 5 votes |
package com.allaboutscala.donutstore.httpserver.routes import akka.http.scaladsl.model.{ContentTypes, HttpEntity} import akka.http.scaladsl.server.Directives.{complete, get, path, _} import akka.http.scaladsl.server._ import com.allaboutscala.donutstore.config.DonutStoreConfig import com.allaboutscala.donutstore.data.DataApi import scala.util.Try class ApiVersionRoute extends HttpRoute { import spray.json._ override def routes()(implicit config: DonutStoreConfig, dataApi: DataApi): Route = { val apiVersion = s""" |{ | "app": "${config.app}", | "version": "${config.httpServer.apiVersion}" |}""".stripMargin path("api-version") { get { parameter("prettyPrint" ? "true") { prettyPrint => // the prettyPrint parameter is optional and we also default to true val shouldPrettyPrint = Try(prettyPrint.toBoolean).getOrElse(true) // we'll default to pretty print val apiVersionOutput = if (shouldPrettyPrint) apiVersion.parseJson.prettyPrint else apiVersion.parseJson.toString complete(HttpEntity(ContentTypes.`application/json`, apiVersionOutput)) } } } } }
Example 50
Source File: FileUploadStream.scala From introduction-to-akkahttp with Apache License 2.0 | 5 votes |
package com.shashank.akkahttp.basic.routing import akka.http.scaladsl.model.{ContentTypes, HttpEntity, Multipart, StatusCodes} import akka.http.scaladsl.server.Directives._ import akka.stream.scaladsl.Framing import akka.util.ByteString import scala.concurrent.Future object FileUploadStream extends BaseSpec{ def main(args: Array[String]) { val route = extractRequestContext { ctx => implicit val materializer = ctx.materializer implicit val ec = ctx.executionContext fileUpload("csv") { case (metadata, byteSource) => val sumF: Future[Int] = // sum the numbers as they arrive so that we can byteSource.via(Framing.delimiter(ByteString("\n"), 1024)) .mapConcat(_.utf8String.split(",").toVector) .map(_.toInt) .runFold(0) { (acc, n) => acc + n } onSuccess(sumF) { sum => complete(s"Sum: $sum") } } } //Test file upload stream val multipartForm = Multipart.FormData(Multipart.FormData.BodyPart.Strict( "csv", HttpEntity(ContentTypes.`text/plain(UTF-8)`, "2,3,5\n7,11,13,17,23\n29,31,37\n"), Map("filename" -> "primes.csv"))) Post("/", multipartForm) ~> route ~> check { status shouldEqual StatusCodes.OK responseAs[String] shouldEqual "Sum: 178" } system.terminate() } } //File upload direct //curl --form "[email protected]" http://<host>:<port>
Example 51
Source File: MinimalHttpServer.scala From Akka-Cookbook with MIT License | 5 votes |
package com.packt.chapter9 import akka.http.scaladsl.model.{ContentTypes, HttpEntity} import akka.http.scaladsl.server.HttpApp import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.settings.ServerSettings import com.typesafe.config.ConfigFactory object MinimalHttpServer extends HttpApp { def route = pathPrefix("v1") { path("id" / Segment) { id => get { complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, s"<h1>Hello $id from Akka Http!</h1>")) } ~ post { entity(as[String]) { entity => complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, s"<b>Thanks $id for posting your message <i>$entity</i></b>")) } } } } } object MinimalHttpServerApplication extends App { MinimalHttpServer.startServer("0.0.0.0", 8088, ServerSettings(ConfigFactory.load)) }
Example 52
Source File: ExtraDirectives.scala From eclair with Apache License 2.0 | 5 votes |
package fr.acinq.eclair.api import akka.http.scaladsl.marshalling.ToResponseMarshaller import akka.http.scaladsl.model.StatusCodes.NotFound import akka.http.scaladsl.model.{ContentTypes, HttpResponse} import akka.http.scaladsl.server.{Directive1, Directives, MalformedFormFieldRejection, Route} import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.Crypto.PublicKey import fr.acinq.eclair.ApiTypes.ChannelIdentifier import fr.acinq.eclair.api.FormParamExtractors._ import fr.acinq.eclair.api.JsonSupport._ import fr.acinq.eclair.payment.PaymentRequest import fr.acinq.eclair.{MilliSatoshi, ShortChannelId} import scala.concurrent.Future import scala.util.{Failure, Success} trait ExtraDirectives extends Directives { // named and typed URL parameters used across several routes val shortChannelIdFormParam = "shortChannelId".as[ShortChannelId](shortChannelIdUnmarshaller) val shortChannelIdsFormParam = "shortChannelIds".as[List[ShortChannelId]](shortChannelIdsUnmarshaller) val channelIdFormParam = "channelId".as[ByteVector32](sha256HashUnmarshaller) val channelIdsFormParam = "channelIds".as[List[ByteVector32]](sha256HashesUnmarshaller) val nodeIdFormParam = "nodeId".as[PublicKey] val nodeIdsFormParam = "nodeIds".as[List[PublicKey]](pubkeyListUnmarshaller) val paymentHashFormParam = "paymentHash".as[ByteVector32](sha256HashUnmarshaller) val fromFormParam = "from".as[Long] val toFormParam = "to".as[Long] val amountMsatFormParam = "amountMsat".as[MilliSatoshi] val invoiceFormParam = "invoice".as[PaymentRequest] // custom directive to fail with HTTP 404 (and JSON response) if the element was not found def completeOrNotFound[T](fut: Future[Option[T]])(implicit marshaller: ToResponseMarshaller[T]): Route = onComplete(fut) { case Success(Some(t)) => complete(t) case Success(None) => complete(HttpResponse(NotFound).withEntity(ContentTypes.`application/json`, serialization.writePretty(ErrorResponse("Not found")))) case Failure(_) => reject } def withChannelIdentifier: Directive1[ChannelIdentifier] = formFields(channelIdFormParam.?, shortChannelIdFormParam.?).tflatMap { case (Some(channelId), None) => provide(Left(channelId)) case (None, Some(shortChannelId)) => provide(Right(shortChannelId)) case _ => reject(MalformedFormFieldRejection("channelId/shortChannelId", "Must specify either the channelId or shortChannelId (not both)")) } def withChannelsIdentifier: Directive1[List[ChannelIdentifier]] = formFields(channelIdFormParam.?, channelIdsFormParam.?, shortChannelIdFormParam.?, shortChannelIdsFormParam.?).tflatMap { case (None, None, None, None) => reject(MalformedFormFieldRejection("channelId(s)/shortChannelId(s)", "Must specify channelId, channelIds, shortChannelId or shortChannelIds")) case (channelId_opt, channelIds_opt, shortChannelId_opt, shortChannelIds_opt) => val channelId: List[ChannelIdentifier] = channelId_opt.map(cid => Left(cid)).toList val channelIds: List[ChannelIdentifier] = channelIds_opt.map(_.map(cid => Left(cid))).toList.flatten val shortChannelId: List[ChannelIdentifier] = shortChannelId_opt.map(scid => Right(scid)).toList val shortChannelIds: List[ChannelIdentifier] = shortChannelIds_opt.map(_.map(scid => Right(scid))).toList.flatten provide((channelId ++ channelIds ++ shortChannelId ++ shortChannelIds).distinct) } }
Example 53
Source File: AdminService.scala From heimdallr with Apache License 2.0 | 5 votes |
package chat.admin import scala.concurrent.ExecutionContext import akka.actor._ import akka.stream.ActorMaterializer import akka.http.scaladsl.model.{ContentTypes, HttpEntity} import akka.http.scaladsl.server.Directives._ import chat.{HealthyService, WebService} class AdminService(healthy: HealthyService) (implicit system: ActorSystem, mat: ActorMaterializer, dispatcher: ExecutionContext) extends WebService with CommonApi { private var chatSuper: ActorRef = null private val servicePort = 8090 private val serviceRoute= //<- adjustable depended on client url get { pathPrefix("health") { path("up") { healthy.start() httpRespJson( "200 OK" ) } ~ path("down") { healthy.stop() httpRespJson( "200 OK" ) } path("view") { var result: String = "" if(chatSuper != null) { chatSuper ! "akka://heimdallr/user/*" chatSuper ! "akka://heimdallr/user/cs/*" result = "200 OK" } else { result = "ChatSupervisor ActorRef is NULL" } httpRespJson(result) } } } def httpRespJson(body: String) = { complete( HttpEntity(ContentTypes.`application/json`, body+"\r\n") ) } def setChatSupervisorActorRef(actorRef: ActorRef) = { chatSuper = actorRef } def start(): Unit = { log.debug( "Admin Server staring ..." ) serviceBind(this.getClass.getSimpleName, serviceRoute, servicePort) } def stop(): Unit = { serviceUnbind(this.getClass.getSimpleName) } }
Example 54
Source File: LinkDescriptionSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.resources import akka.http.scaladsl.model.Uri.Path import akka.http.scaladsl.model.{ContentType, ContentTypes} import ch.epfl.bluebrain.nexus.commons.test.{EitherValues, Randomness} import ch.epfl.bluebrain.nexus.kg.TestHelper import ch.epfl.bluebrain.nexus.kg.resources.ProjectIdentifier.ProjectRef import ch.epfl.bluebrain.nexus.kg.resources.Rejection.InvalidResourceFormat import ch.epfl.bluebrain.nexus.kg.resources.file.File.{FileDescription, LinkDescription} import ch.epfl.bluebrain.nexus.rdf.implicits._ import io.circe.Json import io.circe.syntax._ import org.scalatest.OptionValues import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike class LinkDescriptionSpec extends AnyWordSpecLike with Matchers with TestHelper with Randomness with EitherValues with OptionValues { abstract private class Ctx { val id = Id(ProjectRef(genUUID), genIri) val p = genString() + "/" + genString() val f = genString() val m = "application/json" def jsonLink(mediaType: String = m, filename: String = f, path: String = p): Json = Json.obj("filename" -> filename.asJson, "path" -> path.asJson, "mediaType" -> mediaType.asJson) } "A Link Description" should { "be decoded correctly" in new Ctx { LinkDescription(id, jsonLink()).rightValue shouldEqual LinkDescription(Path(p), Some(f), ContentType.parse(m).toOption) LinkDescription(id, Json.obj("path" -> p.asJson)).rightValue shouldEqual LinkDescription(Path(p), None, None) } "accept missing filename" in new Ctx { LinkDescription(id, jsonLink().removeKeys("filename")).rightValue shouldEqual LinkDescription(Path(p), None, ContentType.parse(m).toOption) } "reject empty filename" in new Ctx { LinkDescription(id, jsonLink(filename = "")).leftValue shouldBe a[InvalidResourceFormat] } "accept missing mediaType" in new Ctx { LinkDescription(id, jsonLink().removeKeys("mediaType")).rightValue shouldEqual LinkDescription(Path(p), Some(f), None) } "reject wrong mediaType format" in new Ctx { LinkDescription(id, jsonLink(mediaType = genString())).leftValue shouldBe a[InvalidResourceFormat] } "reject missing path" in new Ctx { LinkDescription(id, jsonLink().removeKeys("path")).leftValue shouldBe a[InvalidResourceFormat] } "be converted to a FileDescription correctly" in new Ctx { val fileDesc1 = FileDescription.from(LinkDescription(Path("/foo/bar/file.ext"), None, None)) fileDesc1.filename shouldEqual "file.ext" fileDesc1.mediaType shouldEqual None fileDesc1.defaultMediaType shouldEqual ContentTypes.`application/octet-stream` val fileDesc2 = FileDescription.from(LinkDescription(Path("/foo/bar/somedir/"), None, ContentType.parse(m).toOption)) fileDesc2.filename shouldEqual "somedir" fileDesc2.mediaType.value shouldEqual ContentTypes.`application/json` val fileDesc3 = FileDescription.from(LinkDescription(Path("/foo/bar/baz"), Some("file.json"), ContentType.parse(m).toOption)) fileDesc3.filename shouldEqual "file.json" fileDesc3.mediaType.value shouldEqual ContentTypes.`application/json` } } }
Example 55
Source File: DiskStorageOperationsSpec.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.kg.storage import java.nio.file.Paths import akka.http.scaladsl.model.{ContentTypes, Uri} import cats.effect.IO import ch.epfl.bluebrain.nexus.commons.test._ import ch.epfl.bluebrain.nexus.commons.test.io.IOEitherValues import ch.epfl.bluebrain.nexus.kg.config.KgConfig._ import ch.epfl.bluebrain.nexus.kg.resources.file.File.FileDescription import ch.epfl.bluebrain.nexus.kg.resources.Id import ch.epfl.bluebrain.nexus.kg.resources.ProjectIdentifier.ProjectRef import ch.epfl.bluebrain.nexus.kg.{KgError, TestHelper} import ch.epfl.bluebrain.nexus.service.config.Settings import ch.epfl.bluebrain.nexus.sourcing.RetryStrategyConfig import org.mockito.IdiomaticMockito import org.scalatest.{BeforeAndAfter, OptionValues} import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike import scala.concurrent.duration._ class DiskStorageOperationsSpec extends ActorSystemFixture("DiskStorageOperationsSpec") with AnyWordSpecLike with Matchers with BeforeAndAfter with IdiomaticMockito with IOEitherValues with Resources with TestHelper with OptionValues { implicit private val appConfig = Settings(system).serviceConfig implicit private val sc: StorageConfig = appConfig.kg.storage.copy( DiskStorageConfig(Paths.get("/tmp"), "SHA-256", read, write, false, 1024L), RemoteDiskStorageConfig("http://example.com", "v1", None, "SHA-256", read, write, true, 1024L), S3StorageConfig("MD5", read, write, true, 1024L), "password", "salt", RetryStrategyConfig("linear", 300.millis, 5.minutes, 100, 1.second) ) private val project = ProjectRef(genUUID) private val storage = Storage.DiskStorage.default(project) private val resId = Id(storage.ref, genIri) private val fileDesc = FileDescription("my file.txt", ContentTypes.`text/plain(UTF-8)`) "DiskStorageOperations" should { "verify when the storage exists" in { val verify = new DiskStorageOperations.VerifyDiskStorage[IO](storage) verify.apply.accepted } "save and fetch files" in { val save = new DiskStorageOperations.SaveDiskFile[IO](storage) val fetch = new DiskStorageOperations.FetchDiskFile[IO]() val source = genSource val attr = save.apply(resId, fileDesc, source).ioValue attr.bytes shouldEqual 16L attr.filename shouldEqual fileDesc.filename attr.mediaType shouldEqual fileDesc.mediaType.value attr.location shouldEqual Uri(s"file:///tmp/${mangle(project, attr.uuid, "my%20file.txt")}") attr.path shouldEqual attr.location.path.tail.tail.tail val fetched = fetch.apply(attr).ioValue consume(source) shouldEqual consume(fetched) } "not link files" in { val link = new DiskStorageOperations.LinkDiskFile[IO]() link.apply(resId, fileDesc, Uri.Path("/foo")).failed[KgError] shouldEqual KgError.UnsupportedOperation } } }
Example 56
Source File: WebhookDelivererWorker.scala From graphcool-framework with Apache License 2.0 | 5 votes |
package cool.graph.worker.workers import akka.http.scaladsl.model.ContentTypes import cool.graph.akkautil.http.{RequestFailedError, SimpleHttpClient} import cool.graph.cuid.Cuid import cool.graph.messagebus.{QueueConsumer, QueuePublisher} import cool.graph.worker.payloads.{LogItem, Webhook} import cool.graph.worker.utils.Utils import play.api.libs.json.{JsArray, JsObject, Json} import scala.concurrent.{ExecutionContext, Future} import scala.util.{Failure, Success, Try} case class WebhookDelivererWorker( httpClient: SimpleHttpClient, webhooksConsumer: QueueConsumer[Webhook], logsPublisher: QueuePublisher[LogItem] )(implicit ec: ExecutionContext) extends Worker { import scala.concurrent.ExecutionContext.Implicits.global // Current decision: Do not retry delivery, treat all return codes as work item "success" (== ack). val consumeFn = (wh: Webhook) => { val startTime = System.currentTimeMillis() def handleError(msg: String) = { val timing = System.currentTimeMillis() - startTime val timestamp = Utils.msqlDateTime3Timestamp() val logItem = LogItem(Cuid.createCuid(), wh.projectId, wh.functionId, wh.requestId, "FAILURE", timing, timestamp, formatFunctionErrorMessage(msg)) logsPublisher.publish(logItem) } httpClient .post(wh.url, wh.payload, ContentTypes.`application/json`, wh.headers.toList) .map { response => val timing = System.currentTimeMillis() - startTime val body = response.body val timestamp = Utils.msqlDateTime3Timestamp() val functionReturnValue = formatFunctionSuccessMessage(wh.payload, body.getOrElse("")) val logItem = LogItem(Cuid.createCuid(), wh.projectId, wh.functionId, wh.requestId, "SUCCESS", timing, timestamp, functionReturnValue) logsPublisher.publish(logItem) } .recover { case e: RequestFailedError => val message = s"Call to ${wh.url} failed with status ${e.response.status}, response body '${e.response.body.getOrElse("")}' and headers [${formatHeaders(e.response.headers)}]" handleError(message) case e: Throwable => val message = s"Call to ${wh.url} failed with: ${e.getMessage}" handleError(message) } } lazy val consumerRef = webhooksConsumer.withConsumer(consumeFn) def formatFunctionErrorMessage(errMsg: String): JsObject = Json.obj("error" -> errMsg) override def start: Future[_] = Future { consumerRef } override def stop: Future[_] = Future { consumerRef.stop } }