com.twitter.finagle.Service Scala Examples
The following examples show how to use com.twitter.finagle.Service.
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: CirceSpec.scala From featherbed with Apache License 2.0 | 6 votes |
package featherbed.circe import cats.implicits._ import com.twitter.util.Future import io.circe._ import io.circe.generic.auto._ import io.circe.parser.parse import io.circe.syntax._ import org.scalatest.FlatSpec import shapeless.{Coproduct, Witness} import shapeless.union.Union case class Foo(someText: String, someInt: Int) class CirceSpec extends FlatSpec { "post request of a case class" should "derive JSON encoder" in { import com.twitter.util.{Future, Await} import com.twitter.finagle.{Service, Http} import com.twitter.finagle.http.{Request, Response} import java.net.InetSocketAddress val server = Http.serve(new InetSocketAddress(8766), new Service[Request, Response] { def apply(request: Request): Future[Response] = Future { val rep = Response() rep.contentString = s"${request.contentString}" rep.setContentTypeJson() rep } }) import java.net.URL val client = new featherbed.Client(new URL("http://localhost:8766/api/")) import io.circe.generic.auto._ val req = client.post("foo/bar") .withContent(Foo("Hello world!", 42), "application/json") .accept[Coproduct.`"application/json"`.T] val result = Await.result { req.send[Foo]() } Foo("test", 42).asJson.toString parse("""{"someText": "test", "someInt": 42}""").toValidated.map(_.as[Foo]) Await.result(server.close()) } "API example" should "compile" in { import shapeless.Coproduct import java.net.URL import com.twitter.util.Await case class Post(userId: Int, id: Int, title: String, body: String) case class Comment(postId: Int, id: Int, name: String, email: String, body: String) class JSONPlaceholderAPI(baseUrl: URL) { private val client = new featherbed.Client(baseUrl) type JSON = Coproduct.`"application/json"`.T object posts { private val listRequest = client.get("posts").accept[JSON] private val getRequest = (id: Int) => client.get(s"posts/$id").accept[JSON] def list(): Future[Seq[Post]] = listRequest.send[Seq[Post]]() def get(id: Int): Future[Post] = getRequest(id).send[Post]() } object comments { private val listRequest = client.get("comments").accept[JSON] private val getRequest = (id: Int) => client.get(s"comments/$id").accept[JSON] def list(): Future[Seq[Comment]] = listRequest.send[Seq[Comment]]() def get(id: Int): Future[Comment] = getRequest(id).send[Comment]() } } val apiClient = new JSONPlaceholderAPI(new URL("http://jsonplaceholder.typicode.com/")) Await.result(apiClient.posts.list()) } }
Example 2
Source File: ExceptionTranslationFilter.scala From finatra-activator-thrift-seed with Apache License 2.0 | 5 votes |
package com.example import com.twitter.finagle.{Service, TimeoutException} import com.twitter.finatra.thrift.thriftscala.ClientErrorCause.RequestTimeout import com.twitter.finatra.thrift.thriftscala.ServerErrorCause.InternalServerError import com.twitter.finatra.thrift.thriftscala.{ClientError, ServerError} import com.twitter.finatra.thrift.{ThriftFilter, ThriftRequest} import com.twitter.inject.Logging import com.twitter.util.{Future, NonFatal} import javax.inject.Singleton @Singleton class ExceptionTranslationFilter extends ThriftFilter with Logging { override def apply[T, U](request: ThriftRequest[T], service: Service[ThriftRequest[T], U]): Future[U] = { service(request).rescue { case e: TimeoutException => Future.exception( ClientError(RequestTimeout, e.getMessage)) case e: ClientError => Future.exception(e) case NonFatal(e) => error("Unhandled exception", e) Future.exception( ServerError(InternalServerError, e.getMessage)) } } }
Example 3
Source File: FinagleRetryFilter.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe.http.finagle import com.twitter.finagle.http.{Request, Response, Status} import com.twitter.finagle.util.DefaultTimer import com.twitter.finagle.{Service, SimpleFilter, http} import com.twitter.util._ import wvlet.airframe.control.ResultClass import wvlet.airframe.control.Retry.{MaxRetryException, RetryContext} import wvlet.airframe.http.{HttpClientException, HttpClientMaxRetryException} import wvlet.log.LogSupport class FinagleRetryFilter(retry: RetryContext, timer: Timer = DefaultTimer) extends SimpleFilter[http.Request, http.Response] with LogSupport { import com.twitter.conversions.DurationOps._ private[this] def schedule(d: Duration)(f: => Future[Response]) = { if (d > 0.seconds) { val promise = new Promise[Response] timer.schedule(Time.now + d) { promise.become(f) } promise } else { f } } private def dispatch( retryContext: RetryContext, request: Request, service: Service[Request, Response] ): Future[Response] = { val rep = service(request) rep.transform { x => val classifier = x match { case Throw(e) => retryContext.errorClassifier(e) case Return(r) => retryContext.resultClassifier(r) } classifier match { case ResultClass.Succeeded => rep case ResultClass.Failed(isRetryable, cause, extraWait) => { if (!retryContext.canContinue) { // Reached the max retry rep.flatMap { r => Future.exception(HttpClientMaxRetryException(FinagleHttpResponseWrapper(r), retryContext, cause)) } } else if (!isRetryable) { // Non-retryable failure Future.exception(cause) } else { Future .value { // Update the retry count retryContext.withExtraWait(extraWait).nextRetry(cause) }.flatMap { nextRetryContext => // Wait until the next retry schedule(nextRetryContext.nextWaitMillis.millis) { // Run the same request again dispatch(nextRetryContext, request, service) } } } } } } } override def apply(request: Request, service: Service[Request, Response]): Future[Response] = { val retryContext = retry.init(Option(request)) dispatch(retryContext, request, service) } }
Example 4
Source File: FinagleBackend.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe.http.finagle import java.util.concurrent.atomic.AtomicReference import com.twitter.finagle.Service import com.twitter.finagle.context.Contexts import com.twitter.finagle.http.{Request, Response, Status} import com.twitter.util.{Future, Promise, Return, Throw} import wvlet.airframe.http.{HttpBackend, HttpRequestAdapter, HttpStatus} import wvlet.log.LogSupport import scala.concurrent.ExecutionContext import scala.util.{Failure, Success} import scala.{concurrent => sc} object FinagleBackend extends HttpBackend[Request, Response, Future] { override protected implicit val httpRequestAdapter: HttpRequestAdapter[Request] = FinagleHttpRequestAdapter override def wrapException(e: Throwable): Future[Response] = { Future.exception(e) } override def newResponse(status: HttpStatus, content: String): Response = { val r = Response(Status.fromCode(status.code)) r.contentString = content r } def wrapFilter(filter: com.twitter.finagle.Filter[Request, Response, Request, Response]): FinagleFilter = { new FinagleFilter with LogSupport { override def apply(request: Request, context: Context): Future[Response] = { filter(request, Service.mk { req: Request => context(req) }) } } } override def toFuture[A](a: A): Future[A] = Future.value(a) override def toScalaFuture[A](a: Future[A]): sc.Future[A] = { val promise: sc.Promise[A] = sc.Promise() a.respond { case Return(value) => promise.success(value) case Throw(exception) => promise.failure(exception) } promise.future } override def toFuture[A](a: sc.Future[A], e: ExecutionContext): Future[A] = { val promise: Promise[A] = Promise() a.onComplete { case Success(value) => promise.setValue(value) case Failure(exception) => promise.setException(exception) }(e) promise } override def isFutureType(cl: Class[_]): Boolean = { classOf[Future[_]].isAssignableFrom(cl) } override def isRawResponseType(cl: Class[_]): Boolean = { classOf[Response].isAssignableFrom(cl) } override def mapF[A, B](f: Future[A], body: A => B): Future[B] = { f.map(body) } private val contextParamHolderKey = new Contexts.local.Key[AtomicReference[collection.mutable.Map[String, Any]]] override def withThreadLocalStore(body: => Future[Response]): Future[Response] = { val newParamHolder = collection.mutable.Map.empty[String, Any] Contexts.local .let(contextParamHolderKey, new AtomicReference[collection.mutable.Map[String, Any]](newParamHolder)) { body } } override def setThreadLocal[A](key: String, value: A): Unit = { Contexts.local.get(contextParamHolderKey).foreach { ref => ref.get().put(key, value) } } override def getThreadLocal[A](key: String): Option[A] = { Contexts.local.get(contextParamHolderKey).flatMap { ref => ref.get.get(key).asInstanceOf[Option[A]] } } }
Example 5
Source File: FinagleFilter.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe.http.finagle import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Service, SimpleFilter} import com.twitter.util.Future import wvlet.airframe.Session import wvlet.airframe.codec.MessageCodecFactory import wvlet.airframe.http.{HttpBackend, HttpFilter} import wvlet.airframe.http.router.HttpRequestDispatcher abstract class FinagleFilter extends HttpFilter[Request, Response, Future] { override def backend: HttpBackend[Request, Response, Future] = FinagleBackend } class FinagleRouter(session: Session, private[finagle] val config: FinagleServerConfig) extends SimpleFilter[Request, Response] { private val dispatcher = HttpRequestDispatcher.newDispatcher( session, config.router, config.controllerProvider, FinagleBackend, config.responseHandler, MessageCodecFactory.defaultFactory.orElse(MessageCodecFactory.newFactory(config.customCodec)) ) override def apply(request: Request, service: Service[Request, Response]): Future[Response] = { dispatcher.apply(request, FinagleBackend.newContext { request: Request => service(request) }) } }
Example 6
Source File: FinagleServerFactoryTest.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe.http.finagle import com.twitter.finagle.Service import com.twitter.finagle.http.{Request, Response, Status} import com.twitter.finagle.tracing.ConsoleTracer import com.twitter.util.Future import wvlet.airframe.control.Control._ import wvlet.airframe.http.Router import wvlet.airspec.AirSpec class FinagleServerFactoryTest extends AirSpec { def `start multiple FinagleServers`: Unit = { val router1 = Router.add[MyApi] val router2 = Router.add[MyApi] val serverConfig1 = Finagle.server .withName("server1") .withRouter(router1) val serverConfig2 = Finagle.server .withName("server2") .withRouter(router2) finagleDefaultDesign.build[FinagleServerFactory] { factory => val server1 = factory.newFinagleServer(serverConfig1) val server2 = factory.newFinagleServer(serverConfig2) withResources( Finagle.newSyncClient(s"localhost:${server1.port}"), Finagle.newSyncClient(s"localhost:${server2.port}") ) { (client1, client2) => client1.send(Request("/v1/info")).contentString shouldBe "hello MyApi" client2.send(Request("/v1/info")).contentString shouldBe "hello MyApi" } } } def `allow customize services`: Unit = { val d = Finagle.server.withFallbackService { new Service[Request, Response] { override def apply(request: Request): Future[Response] = { val r = Response(Status.Ok) r.contentString = "hello custom server" Future.value(r) } } }.design d.build[FinagleServer] { server => withResource(Finagle.newSyncClient(s"localhost:${server.port}")) { client => client.send(Request("/v1")).contentString shouldBe "hello custom server" } } } def `allow customize Finagle Http Server`: Unit = { Finagle.server .withTracer(ConsoleTracer) .withFallbackService( new Service[Request, Response] { override def apply(request: Request): Future[Response] = { val r = Response(Status.Ok) r.contentString = "hello custom server with tracer" Future.value(r) } } ) .start { server => withResource(Finagle.newSyncClient(server.localAddress)) { client => client.send(Request("/v1")).contentString shouldBe "hello custom server with tracer" } } } }
Example 7
Source File: CorsFilterTest.scala From airframe with Apache License 2.0 | 5 votes |
package wvlet.airframe.http.finagle import com.twitter.finagle.{Service, SimpleFilter} import com.twitter.finagle.http.{Request, Response} import com.twitter.util.Future import wvlet.airframe.Design import wvlet.airframe.http.Router import wvlet.airframe.http.finagle.CorsFilterTest.{CheckFilter, LogFilter, SimpleFilter} import wvlet.airframe.http.finagle.filter.CorsFilter import wvlet.airspec.AirSpec import wvlet.log.LogSupport object CorsFilterTest { // Test SimpleFilter of Finagle object CheckFilter extends SimpleFilter[Request, Response] with LogSupport { override def apply(request: Request, service: Service[Request, Response]): Future[Response] = { info(s"checking request: ${request}") service(request) } } object LogFilter extends FinagleFilter with LogSupport { override def apply( request: Request, context: LogFilter.Context ): Future[Response] = { info(s"logging request: ${request}") context(request) } } object SimpleFilter extends FinagleFilter with LogSupport { override def apply( request: Request, context: SimpleFilter.Context ): Future[Response] = { toFuture { info(s"handling request: ${request}") val r = Response() r.contentString = request.headerMap.mkString(", ") r } } } } class CorsFilterTest extends AirSpec { override protected def design: Design = { val r = Router .add(LogFilter) .andThen(FinagleBackend.wrapFilter(CheckFilter)) .andThen(CorsFilter.unsafePermissiveFilter) .andThen(SimpleFilter) debug(r) newFinagleServerDesign(router = r) .add(finagleSyncClientDesign) } def `support CORS filter`(client: FinagleSyncClient): Unit = { val resp = client.get[String]("/") debug(resp) } }
Example 8
Source File: QueryCacheFilter.scala From the-finagle-docs with MIT License | 5 votes |
package net.gutefrage.filter import com.redis._ import com.redis.serialization.Parse.Implicits._ import com.twitter.finagle.{Service, SimpleFilter} import com.twitter.util.Future import net.gutefrage.filter.ThriftByteArray._ class QueryCacheFilter(val methodsToCache: Option[Seq[String]] = None, redisClient: RedisClient) extends SimpleFilter[Array[Byte], Array[Byte]] { def bytesToInt(bytes: Array[Byte]): Int = java.nio.ByteBuffer.wrap(bytes).getInt def apply(request: Array[Byte], service: Service[Array[Byte], Array[Byte]]): Future[Array[Byte]] = { val (methodName, seqId) = request.binaryProtocolMethodNameSeqId if (methodsToCache.isEmpty || methodsToCache.get.contains(methodName)) { println(s"Incoming request with method: $methodName -> Try to serve it from cache.") val redisKey = request.binaryProtocolChangeSeqId(Array[Byte](0, 0, 0, 0)).requestHashKey redisClient.get[Array[Byte]](redisKey) match { case Some(response) => { println("Data in redis found, returning from cache") Future.value(response) } case None => { println("data not in cache yet") service(request) map { result => redisClient.setex(redisKey, 15, result) result } } } } else { println(s"Incoming request with method: $methodName -> Don't serve it from cache.") service(request) } } }
Example 9
Source File: RoundTripThriftSmallBenchmark.scala From finagle-serial with Apache License 2.0 | 5 votes |
package io.github.finagle.serial.benchmark import java.net.InetSocketAddress import java.util.concurrent.TimeUnit import com.twitter.finagle.{Client, Server, Service, ThriftMux} import com.twitter.util.{Closable, Await, Future} import org.openjdk.jmh.annotations._ @State(Scope.Thread) class RoundTripThriftSmallBenchmark { private val smallSize = 20 val small: thriftscala.Small = thriftscala.Small((for (i <- 1 to smallSize) yield i % 2 == 0).toList, "foo bar baz") val echo = new thriftscala.EchoService.FutureIface { def echo(small: thriftscala.Small) = Future.value(small) } var s: Closable = _ var c: thriftscala.EchoService.FutureIface = _ @Setup def setUp(): Unit = { s = ThriftMux.serveIface(new InetSocketAddress(8124), echo) c = ThriftMux.newIface[thriftscala.EchoService.FutureIface]("localhost:8124") } @TearDown def tearDown(): Unit = { Await.ready(s.close()) } @Benchmark @BenchmarkMode(Array(Mode.Throughput)) @OutputTimeUnit(TimeUnit.SECONDS) def test: thriftscala.Small = Await.result(c.echo(small)) }
Example 10
Source File: RoundTripBenchmark.scala From finagle-serial with Apache License 2.0 | 5 votes |
package io.github.finagle.serial.benchmark import java.net.InetSocketAddress import java.util.concurrent.TimeUnit import com.twitter.finagle.{Server, Client, Service} import com.twitter.util.{Closable, Await, Future} import org.openjdk.jmh.annotations._ @State(Scope.Thread) abstract class RoundTripBenchmark[A](val workload: A) { val echo = new Service[A, A] { override def apply(a: A) = Future.value(a) } var s: Closable = _ var c: Service[A, A] = _ def server: Server[A, A] def client: Client[A, A] @Setup def setUp(): Unit = { s = server.serve(new InetSocketAddress(8123), echo) c = client.newService("localhost:8123") } @TearDown def tearDown(): Unit = { Await.ready(c.close()) Await.ready(s.close()) } @Benchmark @BenchmarkMode(Array(Mode.Throughput)) @OutputTimeUnit(TimeUnit.SECONDS) def test: A = Await.result(c(workload)) }
Example 11
Source File: SerialIntegrationTest.scala From finagle-serial with Apache License 2.0 | 5 votes |
package io.github.finagle.serial.tests import com.twitter.finagle.{Client, ListeningServer, Server, Service} import com.twitter.util.{Await, Future, Try} import io.github.finagle.serial.Serial import java.net.{InetAddress, InetSocketAddress} import org.scalatest.Matchers import org.scalatest.prop.Checkers import org.scalacheck.{Arbitrary, Gen, Prop} def testFunctionService[I, O]( f: I => O )(implicit inCodec: C[I], outCodec: C[O], arb: Arbitrary[I] ): Unit = { val (fServer, fClient) = createServerAndClient(f)(inCodec, outCodec) check(serviceFunctionProp(fClient)(f)(arb.arbitrary)) Await.result(fServer.close()) } }
Example 12
Source File: service.scala From catbird with Apache License 2.0 | 5 votes |
package io.catbird.finagle import cats.arrow.{ Category, Profunctor } import io.catbird.util.twitterFutureInstance import com.twitter.finagle.Service trait ServiceInstances { implicit val serviceInstance: Category[Service] with Profunctor[Service] = new Category[Service] with Profunctor[Service] { final def id[A]: Service[A, A] = Service.mk(twitterFutureInstance.pure) final def compose[A, B, C](f: Service[B, C], g: Service[A, B]): Service[A, C] = Service.mk(a => g(a).flatMap(f)) final def dimap[A, B, C, D](fab: Service[A, B])(f: C => A)(g: B => D): Service[C, D] = Service.mk(c => fab.map(f)(c).map(g)) override final def lmap[A, B, C](fab: Service[A, B])(f: C => A): Service[C, B] = fab.map(f) } }
Example 13
Source File: service.scala From catbird with Apache License 2.0 | 5 votes |
package io.catbird.finagle import cats.instances.int._ import cats.kernel.Eq import cats.laws.discipline._ import cats.laws.discipline.eq._ import com.twitter.conversions.DurationOps._ import com.twitter.finagle.Service import org.scalatest.funsuite.AnyFunSuite import org.scalatest.prop.Configuration import org.typelevel.discipline.scalatest.FunSuiteDiscipline class ServiceSuite extends AnyFunSuite with FunSuiteDiscipline with Configuration with ServiceInstances with ArbitraryInstances with EqInstances { implicit val eq: Eq[Service[Boolean, Int]] = serviceEq(1.second) checkAll("Service", CategoryTests[Service].compose[Boolean, Int, Boolean, Int]) checkAll("Service", CategoryTests[Service].category[Boolean, Int, Boolean, Int]) checkAll("Service", ProfunctorTests[Service].profunctor[Boolean, Int, Boolean, Int, Boolean, Int]) }
Example 14
Source File: TodoListApp.scala From freestyle with Apache License 2.0 | 5 votes |
package examples.todolist import cats._ import cats.effect.IO import cats.implicits._ import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, ListeningServer, Service} import com.twitter.server.TwitterServer import com.twitter.util.{Await, Future} import doobie.util.transactor.Transactor import examples.todolist.http.Api import examples.todolist.persistence.Persistence import examples.todolist.services.Services import freestyle.tagless.config.ConfigM import freestyle.tagless.config.implicits._ import freestyle.tagless.effects.error.ErrorM import freestyle.tagless.effects.error.implicits._ import freestyle.tagless.logging.LoggingM import freestyle.tagless.loggingJVM.log4s.implicits._ import freestyle.tagless.module import io.circe.generic.auto._ import io.finch.circe._ @module trait App[F[_]] { val persistence: Persistence[F] val services: Services[F] } object TodoListApp extends TwitterServer { import examples.todolist.runtime.implicits._ def bootstrap[F[_]: Monad]( implicit app: App[F], handler: F ~> Future, T: Transactor[F], api: Api[F]): F[ListeningServer] = { val service: Service[Request, Response] = api.endpoints.toService val log: LoggingM[F] = app.services.log val cfg: ConfigM[F] = app.services.config for { _ <- log.info("Trying to load application.conf") config <- cfg.load host = config.string("http.host").getOrElse("localhost") port = config.int("http.port").getOrElse("8080") _ <- log.debug(s"Host: $host") _ <- log.debug(s"Port $port") } yield Await.ready( Http.server.withAdmissionControl .concurrencyLimit(maxConcurrentRequests = 10, maxWaiters = 10) .serve(s"$host:$port", service) ) } def main() = bootstrap[IO].unsafeRunAsync { case Left(error) => println(s"Error executing server. ${error.getMessage}") case Right(server) => server.close() } }
Example 15
Source File: CustomTelemetryService.scala From finagle-prometheus with MIT License | 5 votes |
package com.samstarling.prometheusfinagle.examples import java.text.SimpleDateFormat import java.util.Calendar import com.samstarling.prometheusfinagle.metrics.Telemetry import com.twitter.finagle.Service import com.twitter.finagle.http.{Request, Response, Status} import com.twitter.util.Future class CustomTelemetryService(telemetry: Telemetry) extends Service[Request, Response] { private val dayOfWeekFormat = new SimpleDateFormat("E") private val counter = telemetry.counter("requests_by_day_of_week", "Help text", Seq("day_of_week")) override def apply(request: Request): Future[Response] = { dayOfWeek counter.labels(dayOfWeek).inc() val rep = Response(request.version, Status.Ok) rep.setContentString("Your request was logged!") Future(rep) } private def dayOfWeek: String = { dayOfWeekFormat.format(Calendar.getInstance.getTime) } }
Example 16
Source File: EmojiService.scala From finagle-prometheus with MIT License | 5 votes |
package com.samstarling.prometheusfinagle.examples import com.twitter.finagle.{Http, Service} import com.twitter.finagle.http.{Method, Request, Response, Status} import com.twitter.finagle.loadbalancer.LoadBalancerFactory import com.twitter.finagle.stats.{DefaultStatsReceiver, StatsReceiver} import com.twitter.util.Future class EmojiService(statsReceiver: StatsReceiver) extends Service[Request, Response] { private val client = Http.client .withTls("api.github.com") .withStatsReceiver(statsReceiver) .withHttpStats .configured(LoadBalancerFactory.HostStats(statsReceiver.scope("host"))) .newService("api.github.com:443", "GitHub") private val emojiRequest = Request(Method.Get, "/emojis") emojiRequest.headerMap.add("User-Agent", "My-Finagle-Example") override def apply(request: Request): Future[Response] = { client.apply(emojiRequest).map { resp => val r = Response(request.version, Status.Ok) r.setContentString(resp.getContentString()) r } } }
Example 17
Source File: TestServer.scala From finagle-prometheus with MIT License | 5 votes |
package com.samstarling.prometheusfinagle.examples import java.net.InetSocketAddress import com.samstarling.prometheusfinagle.PrometheusStatsReceiver import com.samstarling.prometheusfinagle.metrics.{MetricsService, Telemetry} import com.twitter.finagle.builder.ServerBuilder import com.twitter.finagle.http._ import com.twitter.finagle.http.path._ import com.twitter.finagle.http.service.{NotFoundService, RoutingService} import com.twitter.finagle.loadbalancer.perHostStats import com.twitter.finagle.{Http, Service} import io.prometheus.client.CollectorRegistry object TestServer extends App { perHostStats.parse("true") val registry = CollectorRegistry.defaultRegistry val statsReceiver = new PrometheusStatsReceiver(registry) val telemetry = new Telemetry(registry, "namespace") val emojiService = new EmojiService(statsReceiver) val metricsService = new MetricsService(registry) val echoService = new EchoService val customTelemetryService = new CustomTelemetryService(telemetry) val router: Service[Request, Response] = RoutingService.byMethodAndPathObject { case (Method.Get, Root / "emoji") => emojiService case (Method.Get, Root / "metrics") => metricsService case (Method.Get, Root / "echo") => echoService case (Method.Get, Root / "custom") => customTelemetryService case _ => new NotFoundService } ServerBuilder() .stack(Http.server) .name("testserver") .bindTo(new InetSocketAddress(8080)) .build(router) }
Example 18
Source File: MetricsService.scala From finagle-prometheus with MIT License | 5 votes |
package com.samstarling.prometheusfinagle.metrics import java.io.StringWriter import com.twitter.finagle.Service import com.twitter.finagle.http.{Request, Response, Status} import com.twitter.util.Future import io.prometheus.client.CollectorRegistry import io.prometheus.client.exporter.common.TextFormat class MetricsService(registry: CollectorRegistry) extends Service[Request, Response] { override def apply(request: Request): Future[Response] = { val writer = new StringWriter TextFormat.write004(writer, registry.metricFamilySamples()) val response = Response(request.version, Status.Ok) response.setContentString(writer.toString) Future(response) } }
Example 19
Source File: HttpMonitoringFilter.scala From finagle-prometheus with MIT License | 5 votes |
package com.samstarling.prometheusfinagle.filter import com.samstarling.prometheusfinagle.metrics.Telemetry import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Service, SimpleFilter} import com.twitter.util.Future class HttpMonitoringFilter(telemetry: Telemetry, labeller: ServiceLabeller[Request, Response] = new HttpServiceLabeller) extends SimpleFilter[Request, Response] { private val counter = telemetry.counter( name = "incoming_http_requests_total", help = "The number of incoming HTTP requests", labelNames = labeller.keys ) override def apply(request: Request, service: Service[Request, Response]): Future[Response] = { service(request) onSuccess { response => counter.labels(labeller.labelsFor(request, response): _*).inc() } } }
Example 20
Source File: HttpLatencyMonitoringFilter.scala From finagle-prometheus with MIT License | 5 votes |
package com.samstarling.prometheusfinagle.filter import com.samstarling.prometheusfinagle.metrics.Telemetry import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Service, SimpleFilter} import com.twitter.util.{Future, Stopwatch} class HttpLatencyMonitoringFilter(telemetry: Telemetry, buckets: Seq[Double], labeller: ServiceLabeller[Request, Response] = new HttpServiceLabeller) extends SimpleFilter[Request, Response] { private val histogram = telemetry.histogram( name = "incoming_http_request_latency_seconds", help = "A histogram of the response latency for HTTP requests", labelNames = labeller.keys, buckets = buckets ) override def apply(request: Request, service: Service[Request, Response]): Future[Response] = { val stopwatch = Stopwatch.start() service(request) onSuccess { response => histogram .labels(labeller.labelsFor(request, response): _*) .observe(stopwatch().inMilliseconds / 1000.0) } } }
Example 21
Source File: HttpLatencyMonitoringFilterSpec.scala From finagle-prometheus with MIT License | 5 votes |
package com.samstarling.prometheusfinagle.filter import com.samstarling.prometheusfinagle.UnitTest import com.samstarling.prometheusfinagle.helper.{CollectorHelper, CollectorRegistryHelper} import com.samstarling.prometheusfinagle.metrics.Telemetry import com.twitter.finagle.Service import com.twitter.finagle.http.{Method, Request, Response, Status} import com.twitter.finagle.util.DefaultTimer import com.twitter.util.{Await, Duration, Future, Timer} import io.prometheus.client.CollectorRegistry import org.specs2.specification.Scope class HttpLatencyMonitoringFilterSpec extends UnitTest { class SlowService extends Service[Request, Response] { implicit val timer = DefaultTimer.twitter override def apply(request: Request): Future[Response] = { Future .value(Response(request.version, Status.Ok)) .delayed(Duration.fromMilliseconds(1500)) } } trait Context extends Scope { val registry = new CollectorRegistry(true) val registryHelper = CollectorRegistryHelper(registry) val telemetry = new Telemetry(registry, "test") val buckets = Seq(1.0, 2.0) val labeller = new TestLabeller val filter = new HttpLatencyMonitoringFilter(telemetry, buckets, labeller) val service = mock[Service[Request, Response]] val slowService = new SlowService val request = Request(Method.Get, "/foo/bar") val serviceResponse = Response(Status.Created) val histogram = telemetry.histogram(name = "incoming_http_request_latency_seconds") service.apply(request) returns Future.value(serviceResponse) } "HttpLatencyMonitoringFilter" >> { "passes requests on to the next service" in new Context { Await.result(filter.apply(request, service)) there was one(service).apply(request) } "returns the Response from the next service" in new Context { val actualResponse = Await.result(filter.apply(request, service)) actualResponse ==== serviceResponse } "counts the request" in new Context { Await.result(filter.apply(request, slowService)) registryHelper.samples .get("test_incoming_http_request_latency_seconds_count") .map(_.map(_.value).sum) must beSome(1.0).eventually } "increments the counter with the labels from the labeller" in new Context { Await.result(filter.apply(request, service)) registryHelper.samples .get("test_incoming_http_request_latency_seconds_count") .map(_.head.dimensions.get("foo").get) must beSome("bar").eventually } "categorises requests into the correct bucket" in new Context { Await.result(filter.apply(request, slowService)) // Our request takes ~1500ms, so it should NOT fall into the "less than or equal to 1 second" bucket (le=0.5) registryHelper.samples .get("test_incoming_http_request_latency_seconds_bucket") .flatMap(_.find(_.dimensions.get("le").contains("1.0"))) .map(_.value) must beSome(0.0).eventually // However, it should fall into the "less than or equal to 2 seconds" bucket (le=0.5) registryHelper.samples .get("test_incoming_http_request_latency_seconds_bucket") .flatMap(_.find(_.dimensions.get("le").contains("2.0"))) .map(_.value) must beSome(1.0).eventually // It should also fall into the "+Inf" bucket registryHelper.samples .get("test_incoming_http_request_latency_seconds_bucket") .flatMap(_.find(_.dimensions.get("le").contains("+Inf"))) .map(_.value) must beSome(1.0).eventually } } }
Example 22
Source File: HttpMonitoringFilterSpec.scala From finagle-prometheus with MIT License | 5 votes |
package com.samstarling.prometheusfinagle.filter import com.samstarling.prometheusfinagle.UnitTest import com.samstarling.prometheusfinagle.helper.CollectorHelper import com.samstarling.prometheusfinagle.metrics.Telemetry import com.twitter.finagle.Service import com.twitter.finagle.http.{Method, Request, Response, Status} import com.twitter.util.{Await, Future} import io.prometheus.client.CollectorRegistry import org.specs2.specification.Scope import scala.collection.JavaConverters._ class HttpMonitoringFilterSpec extends UnitTest { trait Context extends Scope { val registry = new CollectorRegistry(true) val telemetry = new Telemetry(registry, "test") val labeller = new TestLabeller val filter = new HttpMonitoringFilter(telemetry, labeller) val service = mock[Service[Request, Response]] val request = Request(Method.Get, "/foo/bar") val serviceResponse = Response(Status.Created) val counter = telemetry.counter(name = "incoming_http_requests_total") service.apply(request) returns Future.value(serviceResponse) } "HttpMonitoringFilter" >> { "passes requests on to the next service" in new Context { Await.result(filter.apply(request, service)) there was one(service).apply(request) } "returns the Response from the next service" in new Context { val actualResponse = Await.result(filter.apply(request, service)) actualResponse ==== serviceResponse } "increments the incoming_http_requests_total counter" in new Context { Await.result(filter.apply(request, service)) Await.result(filter.apply(request, service)) CollectorHelper.firstSampleFor(counter).map { sample => sample.value ==== 2.0 } } "adds the correct help label" in new Context { Await.result(filter.apply(request, service)) CollectorHelper.firstMetricFor(counter).map { metric => metric.help ==== "The number of incoming HTTP requests" } } "increments the counter with the labels from the labeller" in new Context { Await.result(filter.apply(request, service)) CollectorHelper.firstSampleFor(counter).map { sample => sample.labelNames.asScala(0) ==== "foo" sample.labelValues.asScala(0) ==== "bar" } } } }
Example 23
Source File: CrossFieldValidation.scala From fintrospect with Apache License 2.0 | 5 votes |
package examples.validation import com.twitter.finagle.Service import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.Request import com.twitter.finagle.http.path.Root import com.twitter.util.Await.result import io.fintrospect.formats.PlainText.ResponseBuilder._ import io.fintrospect.parameters.Query import io.fintrospect.util.HttpRequestResponseUtil.statusAndContentFrom import io.fintrospect.util.{Extracted, ExtractionFailed, Extractor} import io.fintrospect.{RouteModule, RouteSpec} case class Person(gender: Option[String], experience: Int) case class SchoolClass(pupils: Int, teacher: Person) object CrossFieldValidation extends App { type Predicate[T] = T => Boolean // lower level extractor: extracts a person from the request val person: Extractor[Request, Person] = Extractor.mk { req: Request => for { gender <- Query.optional.string("gender") <--? req exp <- Query.required.int("experience") <--? req } yield Person(gender, exp) } // higher-level extractor: uses other extractors and validation rules val acceptableClassSize: Extractor[Request, SchoolClass] = { // this is a cross-field validation rule, which is basically a predicate and a reason for failure def lessThanYearsExperience(teacher: Person): Predicate[Int] = number => teacher.experience > number Extractor.mk { req: Request => for { teacher <- person <--? req pupils <- Query.required.int("pupils") <--? (req, "Too many pupils", lessThanYearsExperience(teacher)) } yield { SchoolClass(pupils, teacher) } } } // HTTP route which applies the validation - returning the overall Extraction result in case of success val checkClassSize = RouteSpec().at(Get) bindTo Service.mk { req: Request => { acceptableClassSize <--? req match { case Extracted(clazz) => Ok(clazz.toString) case ExtractionFailed(sp) => BadRequest(sp.mkString(", ")) } } } val svc = RouteModule(Root).withRoute(checkClassSize).toService // print succeeding and failing cases println("Missing parameters case: " + statusAndContentFrom(result(svc(Request("?gender=male&pupils=10"))))) println("Failing logic case: " + statusAndContentFrom(result(svc(Request("?gender=male&experience=9&pupils=10"))))) println("Successful case: " + statusAndContentFrom(result(svc(Request("?gender=female&experience=16&pupils=15"))))) }
Example 24
Source File: TemplatingApp.scala From fintrospect with Apache License 2.0 | 5 votes |
package examples.templating import java.net.URL import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.Request import com.twitter.finagle.http.filter.Cors import com.twitter.finagle.http.filter.Cors.HttpFilter import com.twitter.finagle.http.path.Root import com.twitter.finagle.{Http, Service} import com.twitter.util.Await import io.fintrospect.formats.PlainText import io.fintrospect.renderers.SiteMapModuleRenderer import io.fintrospect.templating.{MustacheTemplates, RenderView} import io.fintrospect.{RouteModule, RouteSpec} object TemplatingApp extends App { val devMode = true val renderer = if (devMode) MustacheTemplates.HotReload("src/main/resources") else MustacheTemplates.CachingClasspath(".") val renderView = new RenderView(PlainText.ResponseBuilder, renderer) val module = RouteModule(Root, new SiteMapModuleRenderer(new URL("http://my.cool.app")), renderView) .withRoute(RouteSpec().at(Get) / "echo" bindTo Service.mk { rq: Request => MustacheView(rq.uri) }) println("See the Sitemap description at: http://localhost:8181") Await.ready( Http.serve(":8181", new HttpFilter(Cors.UnsafePermissivePolicy).andThen(module.toService)) ) }
Example 25
Source File: StrictMultiContentTypeRoute.scala From fintrospect with Apache License 2.0 | 5 votes |
package examples.strictcontenttypes import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.Request import com.twitter.finagle.http.filter.Cors import com.twitter.finagle.http.filter.Cors.HttpFilter import com.twitter.finagle.http.path.Root import com.twitter.finagle.{Http, Service} import com.twitter.util.Await import io.fintrospect.ContentTypes.{APPLICATION_JSON, APPLICATION_XML} import io.fintrospect.filters.RequestFilters import io.fintrospect.parameters.Path import io.fintrospect.renderers.simplejson.SimpleJson import io.fintrospect.util.StrictContentTypeNegotiation import io.fintrospect.{RouteModule, RouteSpec} object StrictMultiContentTypeRoute extends App { private def serveJson(name: String) = Service.mk { req: Request => import io.fintrospect.formats.Argo.JsonFormat._ import io.fintrospect.formats.Argo.ResponseBuilder._ Ok(obj("field" -> string(name))) } private def serveXml(name: String) = Service.mk { import io.fintrospect.formats.Xml.ResponseBuilder._ req: Request => Ok(<root> <field> {name} </field> </root>) } val route = RouteSpec() .producing(APPLICATION_XML, APPLICATION_JSON) .at(Get) / "multi" / Path.string("name") bindTo StrictContentTypeNegotiation(APPLICATION_XML -> serveXml, APPLICATION_JSON -> serveJson) val jsonOnlyRoute = RouteSpec() .producing(APPLICATION_JSON) .at(Get) / "json" / Path.string("name") bindTo ((s) => RequestFilters.StrictAccept(APPLICATION_JSON).andThen(serveJson(s))) println("See the service description at: http://localhost:8080 . The route at /multi should match wildcard Accept headers set in a browser.") Await.ready( Http.serve(":8080", new HttpFilter(Cors.UnsafePermissivePolicy) .andThen(RouteModule(Root, SimpleJson()).withRoute(route).toService)) ) }
Example 26
Source File: MultiBodyTypeRoute.scala From fintrospect with Apache License 2.0 | 5 votes |
package examples.strictcontenttypes import com.twitter.finagle.http.Method.Post import com.twitter.finagle.http.Request import com.twitter.finagle.http.filter.Cors import com.twitter.finagle.http.filter.Cors.HttpFilter import com.twitter.finagle.http.path.Root import com.twitter.finagle.{Http, Service} import com.twitter.util.Await import io.fintrospect.parameters.Body import io.fintrospect.renderers.simplejson.SimpleJson import io.fintrospect.util.MultiBodyType import io.fintrospect.{RouteModule, RouteSpec} object MultiBodyTypeRoute extends App { private val json = Body.json("json body") private val echoJson = Service.mk { (rq: Request) => import io.fintrospect.formats.Argo.ResponseBuilder._ Ok(json <-- rq) } private val xml = Body.xml("xml body") private val echoXml = Service.mk { (rq: Request) => import io.fintrospect.formats.Xml.ResponseBuilder._ Ok(xml <-- rq) } val route = RouteSpec("echo posted content in either JSON or XML").at(Post) / "echo" bindTo MultiBodyType(json -> echoJson, xml -> echoXml) println("See the service description at: http://localhost:8080") Await.ready( Http.serve(":8080", new HttpFilter(Cors.UnsafePermissivePolicy) .andThen(RouteModule(Root, SimpleJson()).withRoute(route).toService)) ) }
Example 27
Source File: ContractProxyExample.scala From fintrospect with Apache License 2.0 | 5 votes |
package examples.clients import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.filter.Cors import com.twitter.finagle.http.filter.Cors.HttpFilter import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import com.twitter.util.Await import io.fintrospect.configuration.{Credentials, Host, Port} import io.fintrospect.filters.RequestFilters.{AddHost, BasicAuthorization} import io.fintrospect.parameters.Query import io.fintrospect.{Contract, ContractEndpoint, ContractProxyModule, RouteSpec} object ContractProxyExample extends App { val proxyModule = ContractProxyModule("brewdog", BrewdogApiHttp(), BrewdogApiContract) Await.ready( Http.serve(":9000", new HttpFilter(Cors.UnsafePermissivePolicy).andThen(proxyModule.toService)) ) } object BrewdogApiHttp { private val apiAuthority = Host("punkapi.com").toAuthority(Port(443)) def apply(): Service[Request, Response] = { AddHost(apiAuthority) .andThen(BasicAuthorization(Credentials("22244d6b88574064bbbfe284f1631eaf", ""))) .andThen(Http.client.withTlsWithoutValidation.newService(apiAuthority.toString)) } } object BrewdogApiContract extends Contract { object LookupBeers extends ContractEndpoint { val brewedBefore = Query.optional.string("brewed_before", "e.g. 01-2010 (format is mm-yyyy)") val alcoholContent = Query.optional.int("abv_gt", "Minimum alcohol %") override val route = RouteSpec("lookup beers") .taking(brewedBefore) .taking(alcoholContent) .at(Get) / "api" / "v1" / "beers" } object RandomBeer extends ContractEndpoint { override val route = RouteSpec("get a random beer recipe") .at(Get) / "api" / "v1" / "beers" / "random" } }
Example 28
Source File: ClientSideAndSharedRouteSpecExample.scala From fintrospect with Apache License 2.0 | 5 votes |
package examples.clients import java.time.LocalDate import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import com.twitter.util.Await import io.fintrospect.RouteSpec import io.fintrospect.formats.PlainText.ResponseBuilder._ import io.fintrospect.parameters._ import io.fintrospect.testing.TestHttpServer import io.fintrospect.util.HttpRequestResponseUtil.{headersFrom, statusAndContentFrom} object ClientSideAndSharedRouteSpecExample extends App { val theDate = Path.localDate("date") val theWeather = Query.optional.string("weather") val theUser = Header.required.string("user") val gender = FormField.optional.string("gender") val body = Body.form(gender) val sharedRouteSpec = RouteSpec() .taking(theUser) .taking(theWeather) .body(body) .at(Get) / "firstSection" / theDate val fakeServerRoute = sharedRouteSpec bindTo (dateFromPath => Service.mk[Request, Response] { request: Request => { println("URL was " + request.uri) println("Headers were " + headersFrom(request)) println("Form sent was " + (body <-- request)) println("Date send was " + dateFromPath.toString) Ok(dateFromPath.toString) } }) Await.result(new TestHttpServer(10000, fakeServerRoute).start()) val client = sharedRouteSpec bindToClient Http.newService("localhost:10000") val theCall = client(theWeather --> Option("sunny"), body --> Form(gender --> "male"), theDate --> LocalDate.of(2015, 1, 1), theUser --> System.getenv("USER")) val response = Await.result(theCall) println("Response headers: " + headersFrom(response)) println("Response: " + statusAndContentFrom(response)) }
Example 29
Source File: BookAdd.scala From fintrospect with Apache License 2.0 | 5 votes |
package examples.extended import com.twitter.finagle.Service import com.twitter.finagle.http.{Method, Request, Response, Status} import io.fintrospect.formats.Argo.ResponseBuilder._ import io.fintrospect.parameters.{Body, Path} import io.fintrospect.{ResponseSpec, RouteSpec} class BookAdd(books: Books) { private val exampleBook = Book("the title", "the author", 666) private val bookExistsResponse = Conflict("Book with that ISBN exists") private val jsonBody = Body.json("book content", exampleBook.toJson) private def addBook(isbn: String) = Service.mk { request: Request => books.lookup(isbn) match { case Some(_) => bookExistsResponse case None => { val book = Book.unapply(jsonBody <-- request).get books.add(isbn, book) Created(book.toJson) } } } val route = RouteSpec("add book by isbn number", "This book must not already exist") .body(jsonBody) .returning(ResponseSpec.json(Status.Created -> "we added your book", exampleBook.toJson)) .returning(bookExistsResponse) .at(Method.Post) / "book" / Path.string("isbn", "the isbn of the book") bindTo addBook }
Example 30
Source File: BookLengthSearch.scala From fintrospect with Apache License 2.0 | 5 votes |
package examples.extended import java.lang.Integer.MIN_VALUE import com.twitter.finagle.Service import com.twitter.finagle.http.Method.Post import com.twitter.finagle.http.{Request, Status} import io.fintrospect.ContentTypes.APPLICATION_JSON import io.fintrospect.RouteSpec import io.fintrospect.formats.Argo.JsonFormat.array import io.fintrospect.formats.Argo.ResponseBuilder._ import io.fintrospect.parameters.{Body, FormField} class BookLengthSearch(books: Books) { private val minPages = FormField.optional.int("minPages", "min number of pages in book") private val maxPages = FormField.required.int("maxPages", "max number of pages in book") private val form = Body.form(minPages, maxPages) private val search = Service.mk { request: Request => { val requestForm = form <-- request Ok(array(books.search(minPages <-- requestForm getOrElse MIN_VALUE, maxPages <-- requestForm, Seq("")).map(_.toJson))) } } val route = RouteSpec("search for books by number of pages", "This won't work in Swagger because it's a form... :(") .body(form) .returning(Status.Ok -> "we found some books", array(Book("a book", "authorName", 99).toJson)) .returning(Status.BadRequest -> "invalid request") .producing(APPLICATION_JSON) .at(Post) / "lengthSearch" bindTo search }
Example 31
Source File: BookTermSearch.scala From fintrospect with Apache License 2.0 | 5 votes |
package examples.extended import java.lang.Integer.{MAX_VALUE, MIN_VALUE} import com.twitter.finagle.Service import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.{Request, Status} import io.fintrospect.ContentTypes.APPLICATION_JSON import io.fintrospect.RouteSpec import io.fintrospect.formats.Argo.JsonFormat.array import io.fintrospect.formats.Argo.ResponseBuilder._ import io.fintrospect.parameters.Query class BookTermSearch(books: Books) { private val titleTerms = Query.required.*.string("term", "parts of the title to look for") private val search = Service.mk { request: Request => Ok(array(books.search(MIN_VALUE, MAX_VALUE, titleTerms <-- request).map(_.toJson))) } val route = RouteSpec("search for book by title fragment") .taking(titleTerms) .returning(Status.Ok -> "we found some books", array(Book("a book", "authorName", 99).toJson)) .producing(APPLICATION_JSON) .at(Get) / "titleSearch" bindTo search }
Example 32
Source File: BookLookup.scala From fintrospect with Apache License 2.0 | 5 votes |
package examples.extended import com.twitter.finagle.Service import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.{Request, Response, Status} import io.fintrospect.ContentTypes.APPLICATION_JSON import io.fintrospect.RouteSpec import io.fintrospect.formats.Argo.ResponseBuilder._ import io.fintrospect.parameters.Path class BookLookup(books: Books) { private def lookupByIsbn(isbn: String) = Service.mk { request: Request => books.lookup(isbn) match { case Some(book) => Ok(book.toJson) case _ => NotFound("No book found with isbn") } } val route = RouteSpec("lookup book by isbn number") .producing(APPLICATION_JSON) .returning(NotFound("no book was found with this ISBN")) .returning(Status.Ok -> "we found your book", Book("a book", "authorName", 99).toJson) .at(Get) / "book" / Path.string("isbn", "the isbn of the book") bindTo lookupByIsbn }
Example 33
Source File: AddMessage.scala From fintrospect with Apache License 2.0 | 5 votes |
package examples.circe import com.twitter.finagle.Service import com.twitter.finagle.http.Method.Post import com.twitter.finagle.http.{Request, Response, Status} import com.twitter.util.Future import io.circe.generic.auto._ import io.fintrospect.RouteSpec import io.fintrospect.formats.Circe import io.fintrospect.formats.Circe.Auto._ import io.fintrospect.formats.Circe.responseSpec import io.fintrospect.parameters.{Body, Path} class AddMessage(emails: Emails) { private val exampleEmail = Email(EmailAddress("[email protected]"), EmailAddress("[email protected]"), "when are you going to be home for dinner", 250) private val email = Body.of(Circe.bodySpec[Email](), "email", exampleEmail) private def addEmail(address: EmailAddress): Service[Request, Response] = InOut(Service.mk { newEmail: Email => { // validate that the receiver is as passed as the one in the URL if (address == newEmail.to) emails.add(newEmail) Future(emails.forUser(newEmail.to)) } }) val route = RouteSpec("add an email and return the new inbox contents for the receiver") .body(email) .returning(responseSpec(Status.Ok -> "new list of emails for the 'to' user", Seq(exampleEmail))) .at(Post) / "email" / Path.of(EmailAddress.spec, "email") bindTo addEmail }
Example 34
Source File: FindUserWithEmail.scala From fintrospect with Apache License 2.0 | 5 votes |
package examples.circe import com.twitter.finagle.Service import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.Request import com.twitter.finagle.http.Status.{NotFound, Ok} import com.twitter.util.Future import io.circe.generic.auto._ import io.fintrospect.RouteSpec import io.fintrospect.formats.Circe.Auto._ import io.fintrospect.parameters.Path class FindUserWithEmail(emails: Emails) { private def findByEmail(email: EmailAddress) = { val lookupUserByEmail: Service[Request, Option[EmailAddress]] = Service.mk { _: Request => Future(emails.users().find(_.address == email.address)) } OptionalOut(lookupUserByEmail) } val route = RouteSpec("Get the user for the particular email address") .returning(Ok -> "found the user") .returning(NotFound -> "who is that?") .at(Get) / "user" / Path.of(EmailAddress.spec, "address", "user email") bindTo findByEmail }
Example 35
Source File: FakeRemoteLibrary.scala From fintrospect with Apache License 2.0 | 5 votes |
package presentation._6 import com.twitter.finagle.http.filter.Cors import com.twitter.finagle.http.filter.Cors.HttpFilter import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import io.fintrospect.RouteModule import io.fintrospect.formats.PlainText.ResponseBuilder._ import io.fintrospect.renderers.simplejson.SimpleJson import presentation.Books class FakeRemoteLibrary(books: Books) { def search(titlePart: String) = Service.mk[Request, Response] { request => { val results = books.titles().filter(_.toLowerCase.contains(titlePart.toLowerCase)) Ok(results.mkString(",")) } } val service = RouteModule(Root, SimpleJson()) .withRoute(RemoteBooks.route bindTo search) .toService val searchService = new HttpFilter(Cors.UnsafePermissivePolicy).andThen(service) Http.serve(":10000", searchService) }
Example 36
Source File: SearchApp.scala From fintrospect with Apache License 2.0 | 5 votes |
package presentation._6 import com.twitter.finagle.http.Method.{Get, Post} import com.twitter.finagle.http.filter.Cors import com.twitter.finagle.http.filter.Cors.HttpFilter import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response, Status} import com.twitter.finagle.{Http, Service} import io.fintrospect.formats.Argo.JsonFormat.array import io.fintrospect.formats.Argo.ResponseBuilder._ import io.fintrospect.parameters.{Body, BodySpec, Query} import io.fintrospect.renderers.swagger2dot0.{ApiInfo, Swagger2dot0Json} import io.fintrospect.{ResponseSpec, RouteModule, RouteSpec} import presentation.Book class SearchRoute(books: RemoteBooks) { private val titlePartParam = Query.required.string("titlePart") def search() = Service.mk[Request, Response] { request => { val titlePart = titlePartParam <-- request books.search(titlePart) .map(results => results.split(",").map(Book(_)).toSeq) .map(books => Ok(array(books.map(_.toJson)))) } } val route = RouteSpec("search books") .taking(titlePartParam) .returning(ResponseSpec.json(Status.Ok -> "search results", array(Book("1984").toJson))) .at(Get) / "search" bindTo search } class BookAvailable(books: RemoteBooks) { private val bodySpec = BodySpec.json().map(Book.fromJson, (b: Book) => b.toJson) private val body = Body.of(bodySpec, "a book", Book("1984")) def availability() = Service.mk[Request, Response] { request => { val book = body <-- request books.search(book.title) .map(results => { if (results.length > 0) Ok("cool") else NotFound("!") }) } } val route = RouteSpec("find if the book is owned") .body(body) .returning(Status.Ok -> "book is available") .returning(Status.NotFound -> "book not found") .at(Post) / "availability" bindTo availability } class SearchApp { private val apiInfo = ApiInfo("search some books", "1.0", "an api for searching our book collection") val service = RouteModule(Root, Swagger2dot0Json(apiInfo)) .withRoute(new SearchRoute(new RemoteBooks).route) .withRoute(new BookAvailable(new RemoteBooks).route) .toService val searchService = new HttpFilter(Cors.UnsafePermissivePolicy).andThen(service) Http.serve(":9000", searchService) }
Example 37
Source File: FakeRemoteLibrary.scala From fintrospect with Apache License 2.0 | 5 votes |
package presentation._5 import com.twitter.finagle.http.filter.Cors import com.twitter.finagle.http.filter.Cors.HttpFilter import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import io.fintrospect.RouteModule import io.fintrospect.formats.PlainText.ResponseBuilder._ import io.fintrospect.renderers.simplejson.SimpleJson import presentation.Books class FakeRemoteLibrary(books: Books) { def search(titlePart: String) = Service.mk[Request, Response] { request => Ok(books.titles().filter(_.toLowerCase.contains(titlePart.toLowerCase)).mkString(",")) } val service = RouteModule(Root, SimpleJson()) .withRoute(RemoteBooks.route bindTo search) .toService val searchService = new HttpFilter(Cors.UnsafePermissivePolicy).andThen(service) Http.serve(":10000", searchService) }
Example 38
Source File: SearchApp.scala From fintrospect with Apache License 2.0 | 5 votes |
package presentation._5 import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.filter.Cors import com.twitter.finagle.http.filter.Cors.HttpFilter import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response, Status} import com.twitter.finagle.{Http, Service} import io.fintrospect.formats.Argo.JsonFormat.array import io.fintrospect.formats.Argo.ResponseBuilder._ import io.fintrospect.parameters.Query import io.fintrospect.renderers.swagger2dot0.{ApiInfo, Swagger2dot0Json} import io.fintrospect.{ResponseSpec, RouteModule, RouteSpec} import presentation.Book class SearchRoute(books: RemoteBooks) { private val titlePartParam = Query.required.string("titlePart") def search() = Service.mk[Request, Response] { request => { val titlePart = titlePartParam <-- request books.search(titlePart) .map(results => results.split(",").map(Book(_)).toSeq) .map(books => Ok(array(books.map(_.toJson)))) } } val route = RouteSpec("search books") .taking(titlePartParam) .returning(ResponseSpec.json(Status.Ok -> "search results", array(Book("1984").toJson))) .at(Get) / "search" bindTo search } class SearchApp { private val apiInfo = ApiInfo("search some books", "1.0", "an api for searching our book collection") val service = RouteModule(Root, Swagger2dot0Json(apiInfo)) .withRoute(new SearchRoute(new RemoteBooks).route) .toService val searchService = new HttpFilter(Cors.UnsafePermissivePolicy).andThen(service) Http.serve(":9000", searchService) }
Example 39
Source File: FakeRemoteLibrary.scala From fintrospect with Apache License 2.0 | 5 votes |
package presentation._4 import com.twitter.finagle.http.filter.Cors import com.twitter.finagle.http.filter.Cors.HttpFilter import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import io.fintrospect.RouteModule import io.fintrospect.formats.PlainText.ResponseBuilder._ import io.fintrospect.renderers.simplejson.SimpleJson import presentation.Books class FakeRemoteLibrary(books: Books) { def search(titlePart: String) = Service.mk[Request, Response] { _ => Ok(books.titles().filter(_.toLowerCase.contains(titlePart.toLowerCase)).mkString(",")) } val service = RouteModule(Root, SimpleJson()) .withRoute(RemoteBooks.route bindTo search) .toService val searchService = new HttpFilter(Cors.UnsafePermissivePolicy).andThen(service) Http.serve(":10000", searchService) }
Example 40
Source File: SearchApp.scala From fintrospect with Apache License 2.0 | 5 votes |
package presentation._4 import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.filter.Cors import com.twitter.finagle.http.filter.Cors.HttpFilter import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import io.fintrospect.formats.PlainText.ResponseBuilder._ import io.fintrospect.parameters.Query import io.fintrospect.renderers.swagger2dot0.{ApiInfo, Swagger2dot0Json} import io.fintrospect.{RouteModule, RouteSpec} class SearchRoute(books: RemoteBooks) { private val titlePartParam = Query.required.string("titlePart") def search() = Service.mk[Request, Response] { request => { val titlePart = titlePartParam <-- request books.search(titlePart) .map(results => Ok(results)) } } val route = RouteSpec("search books") .taking(titlePartParam) .at(Get) / "search" bindTo search } class SearchApp { private val apiInfo = ApiInfo("search some books", "1.0", "an api for searching our book collection") val service = RouteModule(Root, Swagger2dot0Json(apiInfo)) .withRoute(new SearchRoute(new RemoteBooks).route) .toService val searchService = new HttpFilter(Cors.UnsafePermissivePolicy).andThen(service) Http.serve(":9000", searchService) }
Example 41
Source File: SearchApp.scala From fintrospect with Apache License 2.0 | 5 votes |
package presentation._3 import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.filter.Cors import com.twitter.finagle.http.filter.Cors.HttpFilter import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import io.fintrospect.formats.PlainText.ResponseBuilder._ import io.fintrospect.parameters.Query import io.fintrospect.renderers.swagger2dot0.{ApiInfo, Swagger2dot0Json} import io.fintrospect.{RouteModule, RouteSpec} import presentation.Books class SearchRoute(books: Books) { private val titlePartParam = Query.required.string("titlePart") def search() = Service.mk[Request, Response] { request => { val titlePart = titlePartParam <-- request val results = books.titles().filter(_.toLowerCase.contains(titlePart.toLowerCase)) Ok(results.toString()) } } val route = RouteSpec("search books") .taking(titlePartParam) .at(Get) / "search" bindTo search } class SearchApp(books: Books) { private val apiInfo = ApiInfo("search some books", "1.0", "an api for searching our book collection") val service = RouteModule(Root, Swagger2dot0Json(apiInfo)) .withRoute(new SearchRoute(books).route) .toService val searchService = new HttpFilter(Cors.UnsafePermissivePolicy).andThen(service) Http.serve(":9000", searchService) } object Environment extends App { new SearchApp(new Books) Thread.currentThread().join() }
Example 42
Source File: SearchApp.scala From fintrospect with Apache License 2.0 | 5 votes |
package presentation._2 import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.filter.Cors import com.twitter.finagle.http.filter.Cors.HttpFilter import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import io.fintrospect.formats.PlainText.ResponseBuilder._ import io.fintrospect.renderers.swagger2dot0.{ApiInfo, Swagger2dot0Json} import io.fintrospect.{RouteModule, RouteSpec} import presentation.Books class SearchApp(books: Books) { def search() = Service.mk[Request, Response] { _ => Ok(books.titles().toString()) } private val apiInfo = ApiInfo("search some books", "1.0", "an api for searching our book collection") val service = RouteModule(Root, Swagger2dot0Json(apiInfo)) .withRoute(RouteSpec("search books").at(Get) / "search" bindTo search) .toService val searchService = new HttpFilter(Cors.UnsafePermissivePolicy).andThen(service) Http.serve(":9000", searchService) } object Environment extends App { new SearchApp(new Books) Thread.currentThread().join() }
Example 43
Source File: MultiPart_Web_Form_Example.scala From fintrospect with Apache License 2.0 | 5 votes |
package cookbook.forms // fintrospect-core object MultiPart_Web_Form_Example extends App { import com.twitter.finagle.http.Method.Post import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import com.twitter.util.Await.ready import com.twitter.util.Future import io.fintrospect.formats.PlainText.ResponseBuilder._ import io.fintrospect.parameters.{Body, Form, FormField, MultiPartFile} import io.fintrospect.{Module, RouteModule, RouteSpec, ServerRoute} val usernameField = FormField.required.string("user") val fileField = FormField.required.file("data") val form: Body[Form] = Body.multiPartWebForm(usernameField -> "everyone has a name!", fileField -> "file is required!") val svc: Service[Request, Response] = Service.mk[Request, Response] { req => { val postedForm: Form = form <-- req if (postedForm.isValid) successMessage(postedForm) else failureMessage(postedForm) } } def failureMessage(postedForm: Form): Future[Response] = { val errorString = postedForm.errors.map(e => e.param.name + ": " + e.reason).mkString("\n") BadRequest("errors were: " + errorString) } def successMessage(postedForm: Form): Future[Response] = { val name: String = usernameField <-- postedForm val data: MultiPartFile = fileField <-- postedForm Ok(s"$name posted ${data.filename} which is ${data.length}" + " bytes") } val route: ServerRoute[Request, Response] = RouteSpec() .body(form) .at(Post) bindTo svc val module: Module = RouteModule(Root).withRoute(route) ready(Http.serve(":9999", module.toService)) }
Example 44
Source File: Web_Form_Example.scala From fintrospect with Apache License 2.0 | 5 votes |
package cookbook.forms // fintrospect-core object Web_Form_Example extends App { import com.twitter.finagle.http.Method.Post import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import com.twitter.util.Await.ready import com.twitter.util.Future import io.fintrospect.formats.PlainText.ResponseBuilder._ import io.fintrospect.parameters.{Body, Form, FormField} import io.fintrospect.{Module, RouteModule, RouteSpec, ServerRoute} val nameField = FormField.required.string("name") val ageField = FormField.optional.int("age") val form: Body[Form] = Body.webForm(nameField -> "everyone has a name!", ageField -> "age is an int!") val svc: Service[Request, Response] = Service.mk[Request, Response] { req => { val postedForm: Form = form <-- req if (postedForm.isValid) successMessage(postedForm) else failureMessage(postedForm) } } def failureMessage(postedForm: Form): Future[Response] = { val errorString = postedForm.errors.map(e => e.param.name + ": " + e.reason).mkString("\n") BadRequest("errors were: " + errorString) } def successMessage(postedForm: Form): Future[Response] = { val name: String = nameField <-- postedForm val age: Option[Int] = ageField <-- postedForm Ok(s"$name is ${age.map(_.toString).getOrElse("too old to admit it")}") } val route: ServerRoute[Request, Response] = RouteSpec() .body(form) .at(Post) bindTo svc val module: Module = RouteModule(Root).withRoute(route) ready(Http.serve(":9999", module.toService)) } //curl -v -H"Content-Type: application/x-www-form-urlencoded" -XPOST http://localhost:9999/ --data '&age=asd' //curl -v -H"Content-Type: application/x-www-form-urlencoded" -XPOST http://localhost:9999/ --data 'name=david&age=12'
Example 45
Source File: Simple_Form_Example.scala From fintrospect with Apache License 2.0 | 5 votes |
package cookbook.forms // fintrospect-core object Simple_Form_Example extends App { import com.twitter.finagle.http.Method.Post import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import com.twitter.util.Await.ready import io.fintrospect.formats.PlainText.ResponseBuilder._ import io.fintrospect.parameters.{Body, Form, FormField} import io.fintrospect.{Module, RouteModule, RouteSpec, ServerRoute} val nameField = FormField.required.string("name") val ageField = FormField.optional.int("age") val form: Body[Form] = Body.form(nameField, ageField) val svc: Service[Request, Response] = Service.mk[Request, Response] { req => { val formInstance: Form = form <-- req val name: String = nameField <-- formInstance val age: Option[Int] = ageField <-- formInstance Ok(s"$name is ${age.map(_.toString).getOrElse("too old to admit it")}") } } val route: ServerRoute[Request, Response] = RouteSpec() .body(form) .at(Post) bindTo svc val module: Module = RouteModule(Root).withRoute(route) ready(Http.serve(":9999", module.toService)) } //curl -v -H"Content-Type: application/x-www-form-urlencoded" -XPOST http://localhost:9999/ --data '&age=asd' //curl -v -H"Content-Type: application/x-www-form-urlencoded" -XPOST http://localhost:9999/ --data 'name=david&age=12'
Example 46
Source File: MultiPart_Form_Example.scala From fintrospect with Apache License 2.0 | 5 votes |
package cookbook.forms // fintrospect-core object MultiPart_Form_Example extends App { import com.twitter.finagle.http.Method.Post import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import com.twitter.util.Await.ready import io.fintrospect.formats.PlainText.ResponseBuilder._ import io.fintrospect.parameters.{Body, Form, FormField, MultiPartFile} import io.fintrospect.{Module, RouteModule, RouteSpec, ServerRoute} val usernameField = FormField.required.string("user") val fileField = FormField.required.file("data") val form: Body[Form] = Body.multiPartForm(usernameField, fileField) val svc: Service[Request, Response] = Service.mk[Request, Response] { req => { val postedForm: Form = form <-- req val name: String = usernameField <-- postedForm val data: MultiPartFile = fileField <-- postedForm Ok(s"$name posted ${data.filename} which is ${data.length}" + " bytes") } } val route: ServerRoute[Request, Response] = RouteSpec() .body(form) .at(Post) bindTo svc val module: Module = RouteModule(Root).withRoute(route) ready(Http.serve(":9999", module.toService)) }
Example 47
Source File: MsgPack_Example.scala From fintrospect with Apache License 2.0 | 5 votes |
package cookbook.msgpack object MsgPack_Example extends App { import com.twitter.finagle.http.Method.Post import com.twitter.finagle.http.Request import com.twitter.finagle.http.path.Root import com.twitter.finagle.{Http, Service} import com.twitter.util.Await.result import com.twitter.util.Future import io.fintrospect.formats.MsgPack.Auto._ import io.fintrospect.formats.MsgPack.Format.{decode, encode} import io.fintrospect.{RouteModule, RouteSpec} case class StreetAddress(address: String) case class Letter(to: StreetAddress, from: StreetAddress, message: String) val replyToLetter = RouteSpec() .at(Post) / "reply" bindTo InOut[StreetAddress, Letter]( Service.mk { in: StreetAddress => Future(Letter(StreetAddress("2 Bob St"), in, "hi fools!")) }) val module = RouteModule(Root).withRoute(replyToLetter) Http.serve(":8181", module.toService) val request = Request(Post, "reply") request.content = encode(StreetAddress("1 hello street")) val response = result(Http.newService("localhost:8181")(request)) println("Response was:" + decode[Letter](response.content)) }
Example 48
Source File: Handlebars_Example.scala From fintrospect with Apache License 2.0 | 5 votes |
package cookbook.templating // fintrospect-core // fintrospect-handlebars case class HandlebarsView(name: String, age: Int) extends io.fintrospect.templating.View object Handlebars_Example extends App { import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import com.twitter.util.Await.ready import io.fintrospect.formats.Html import io.fintrospect.parameters.Path import io.fintrospect.templating.{HandlebarsTemplates, RenderView, View} import io.fintrospect.{Module, RouteModule, RouteSpec, ServerRoute} def showAgeIn30(name: String, age: Int): Service[Request, Response] = { val svc = Service.mk[Request, View] { req => MustacheView(name, age + 30) } new RenderView(Html.ResponseBuilder, HandlebarsTemplates.CachingClasspath(".")).andThen(svc) } val route: ServerRoute[Request, Response] = RouteSpec() .at(Get) / Path.string("name") / Path.int("age") bindTo showAgeIn30 val module: Module = RouteModule(Root).withRoute(route) ready(Http.serve(":9999", module.toService)) } //curl -v http://localhost:9999/david/100
Example 49
Source File: Semi_Auto_Marshalling_Example.scala From fintrospect with Apache License 2.0 | 5 votes |
package cookbook.json_libraries case class Person(name: String, age: Option[Int]) // fintrospect-core // fintrospect-circe object Semi_Auto_Marshalling_Example extends App { import com.twitter.finagle.http.Method.Post import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import com.twitter.util.Await.ready import io.circe.generic.auto._ import io.fintrospect.formats.Circe import io.fintrospect.formats.Circe.JsonFormat._ import io.fintrospect.formats.Circe.ResponseBuilder._ import io.fintrospect.parameters.Body import io.fintrospect.{Module, RouteModule, RouteSpec, ServerRoute} val personBody = Body.of(Circe.bodySpec[Person]()) val insultMe: Service[Request, Response] = Service.mk[Request, Response] { req => val person: Person = personBody <-- req val smellyPerson: Person = person.copy(name = person.name + " Smells") Ok(encode(smellyPerson)) } val route: ServerRoute[Request, Response] = RouteSpec() .body(personBody) .at(Post) bindTo insultMe val module: Module = RouteModule(Root).withRoute(route) ready(Http.serve(":9999", module.toService)) } //curl -v -XPOST http://localhost:9999/ --data '{"name":"David", "age": 50}'
Example 50
Source File: Patching_Endpoint_Example.scala From fintrospect with Apache License 2.0 | 5 votes |
package cookbook.json_libraries case class Employee(name: String, age: Option[Int]) // fintrospect-core // fintrospect-circe object Patching_Endpoint_Example extends App { import com.twitter.finagle.http.Method.Post import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import com.twitter.util.Await.ready import com.twitter.util.Future import io.circe.generic.auto._ import io.fintrospect.formats.Circe import io.fintrospect.formats.Circe.JsonFormat._ import io.fintrospect.formats.Circe.ResponseBuilder._ import io.fintrospect.parameters.Path import io.fintrospect.{Module, RouteModule, RouteSpec, ServerRoute} import scala.collection.mutable val employees = mutable.Map[Int, Employee](1 -> Employee("David", None)) val patchBody = Circe.patchBody[Employee]() def updateAge(id: Int): Service[Request, Response] = Service.mk[Request, Response] { req => val patcher = patchBody <-- req Future(employees.get(id) match { case Some(employee) => employees(id) = patcher(employee) Ok(encode(employees.get(id))) case _ => NotFound(s"with id $id") }) } val route: ServerRoute[Request, Response] = RouteSpec() .body(patchBody) .at(Post) / Path.int("id") bindTo updateAge val module: Module = RouteModule(Root).withRoute(route) ready(Http.serve(":9999", module.toService)) } //curl -v -XPOST http://localhost:9999/1 --data '{"age": 50}'
Example 51
Source File: Full_Auto_Service_Wrappers_Example.scala From fintrospect with Apache License 2.0 | 5 votes |
package cookbook.json_libraries case class Profile(name: String, age: Option[Int]) // fintrospect-core // fintrospect-circe object Full_Auto_Marshalling_Example extends App { import com.twitter.finagle.http.Method.Post import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import com.twitter.util.Await.ready import com.twitter.util.Future import io.circe.generic.auto._ import io.fintrospect.formats.Circe import io.fintrospect.formats.Circe.Auto._ import io.fintrospect.parameters.Body import io.fintrospect.{Module, RouteModule, RouteSpec, ServerRoute} val insultMe: Service[Profile, Profile] = Service.mk[Profile, Profile] { inProfile => Future(inProfile.copy(name = inProfile.name + " Smells")) } val route: ServerRoute[Request, Response] = RouteSpec() .body(Body.of(Circe.bodySpec[Profile]())) .at(Post) bindTo InOut(insultMe) val module: Module = RouteModule(Root).withRoute(route) ready(Http.serve(":9999", module.toService)) } //curl -v -XPOST http://localhost:9999/ --data '{"name":"David", "age": 50}'
Example 52
Source File: Composite_Request_Parameters_Example.scala From fintrospect with Apache License 2.0 | 5 votes |
package cookbook.core // fintrospect-core object Composite_Request_Parameters_Example extends App { import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import com.twitter.util.Await.ready import io.fintrospect.formats.PlainText.ResponseBuilder._ import io.fintrospect.parameters.{Binding, Composite, Header, Query} import io.fintrospect.util.Extraction import io.fintrospect.{Module, RouteModule, RouteSpec, ServerRoute} case class FooBar(foo: String, bar: Int) object FooBar extends Composite[FooBar] { private val fooQ = add(Header.required.string("foo")) private val barQ = add(Query.required.int("bar")) override def -->(foobar: FooBar): Iterable[Binding] = (fooQ --> foobar.foo) ++ (barQ --> foobar.bar) override def <--?(req: Request): Extraction[FooBar] = { for { foo <- fooQ <--? req bar <- barQ <--? req } yield FooBar(foo, bar) } } val route: ServerRoute[Request, Response] = RouteSpec() .taking(FooBar).at(Get) bindTo Service.mk { req: Request => Ok("you sent: " + (FooBar <-- req)) } val module: Module = RouteModule(Root).withRoute(route) ready(Http.serve(":9999", module.toService)) } //curl -v -H"foo: foo" http://localhost:9999?bar=123
Example 53
Source File: Serving_Multiple_Content_Types_Example.scala From fintrospect with Apache License 2.0 | 5 votes |
package cookbook.core // fintrospect-core object Serving_Multiple_Content_Types_Example extends App { import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import com.twitter.util.Await.ready import io.fintrospect.ContentTypes.{APPLICATION_JSON, APPLICATION_XML} import io.fintrospect.parameters.Path import io.fintrospect.util.StrictContentTypeNegotiation import io.fintrospect.{RouteModule, RouteSpec} def serveJson(name: String) = Service.mk[Request, Response] { req => import io.fintrospect.formats.Argo.JsonFormat._ import io.fintrospect.formats.Argo.ResponseBuilder._ Ok(obj("field" -> string(name))) } def serveXml(name: String) = Service.mk[Request, Response] { import io.fintrospect.formats.Xml.ResponseBuilder._ req => Ok(<root> <field> {name} </field> </root>) } val route = RouteSpec() .at(Get) / Path.string("name") bindTo StrictContentTypeNegotiation(APPLICATION_XML -> serveXml, APPLICATION_JSON -> serveJson) ready(Http.serve(":9999", RouteModule(Root).withRoute(route).toService)) } //curl -v -H"Accept: application/json" http://localhost:9999/David //curl -v -H"Accept: application/xml" http://localhost:9999/David
Example 54
Source File: Simple_XML_Example.scala From fintrospect with Apache License 2.0 | 5 votes |
package cookbook.core // fintrospect-core object Simple_XML_Example extends App { import com.twitter.finagle.http.Method.Post import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import com.twitter.util.Await.ready import io.fintrospect.formats.Xml.ResponseBuilder._ import io.fintrospect.parameters.Body import io.fintrospect.{Module, RouteModule, RouteSpec, ServerRoute} import scala.xml.Elem val document: Body[Elem] = Body.xml() val analyse: Service[Request, Response] = Service.mk[Request, Response] { req => { val postedDoc: Elem = document <-- req Ok( <document> <number-of-root-elements> {postedDoc.length} </number-of-root-elements> </document> ) } } val route: ServerRoute[Request, Response] = RouteSpec().body(document).at(Post) bindTo analyse val module: Module = RouteModule(Root).withRoute(route) ready(Http.serve(":9999", module.toService)) } //curl -v -XPOST http://localhost:9999/ --data '<person name="david" age="100"/>'
Example 55
Source File: Swagger_Auto_Docs_Example.scala From fintrospect with Apache License 2.0 | 5 votes |
package cookbook.core // fintrospect-core object Swagger_Auto_Docs_Example extends App { import argo.jdom.JsonNode import com.twitter.finagle.http.Method.Post import com.twitter.finagle.http.filter.Cors import com.twitter.finagle.http.filter.Cors.HttpFilter import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response, Status} import com.twitter.finagle.{Http, Service} import com.twitter.util.Await.ready import com.twitter.util.Future import io.fintrospect.ContentTypes.APPLICATION_JSON import io.fintrospect.formats.Argo.JsonFormat._ import io.fintrospect.formats.Argo.ResponseBuilder._ import io.fintrospect.parameters.{Body, Header, Path, Query} import io.fintrospect.renderers.ModuleRenderer import io.fintrospect.renderers.swagger2dot0.{ApiInfo, Swagger2dot0Json} import io.fintrospect.{ApiKey, Module, RouteModule, RouteSpec, ServerRoute} def buildResponse(id: Int, sent: JsonNode) = obj("id" -> number(id), "sent" -> sent) val exampleBody: JsonNode = array(obj("lastName" -> string("Jane")), obj("name" -> string("Jim"))) val exampleResponse: JsonNode = buildResponse(222, exampleBody) val sentDocument: Body[JsonNode] = Body.json("family description", exampleBody) def svc(id: Int): Service[Request, Response] = Service.mk[Request, Response] { req => Ok(buildResponse(id, sentDocument <-- req)) } val securityFilter: Service[String, Boolean] = Service.mk[String, Boolean] { r => Future(r == "secret") } val route: ServerRoute[Request, Response] = RouteSpec("a short summary", "a longer description") .taking(Query.required.string("firstName", "this is your firstname")) .taking(Header.optional.localDate("birthdate", "format yyyy-mm-dd")) .producing(APPLICATION_JSON) .consuming(APPLICATION_JSON) .returning(Status.Ok -> "Valid request accepted", exampleResponse) .body(sentDocument) .at(Post) / Path.int("id", "custom identifier for this request") bindTo svc val docsRenderer: ModuleRenderer = Swagger2dot0Json( ApiInfo("My App", "1.0", "This is an extended description of the API's functions") ) val module: Module = RouteModule(Root, docsRenderer) .withDescriptionPath(moduleRoot => moduleRoot / "swagger.json") .securedBy(ApiKey(Query.required.string("token"), securityFilter)) .withRoute(route) ready(Http.serve(":9999", new HttpFilter(Cors.UnsafePermissivePolicy).andThen(module.toService))) } // curl -v http://localhost:9999/swagger.json
Example 56
Source File: Custom_Response_Format_Example.scala From fintrospect with Apache License 2.0 | 5 votes |
package cookbook.core // fintrospect-core object Custom_Response_Format_Example extends App { import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import com.twitter.io.Bufs import com.twitter.util.Await.ready import io.fintrospect.formats.{AbstractResponseBuilder, ResponseBuilder} import io.fintrospect.{ContentType, Module, RouteModule, RouteSpec, ServerRoute} object Csv { object ResponseBuilder extends AbstractResponseBuilder[List[String]] { override def HttpResponse(): ResponseBuilder[List[String]] = new ResponseBuilder( (i: List[String]) => Bufs.utf8Buf(i.mkString(",")), error => List("ERROR:" + error), throwable => List("ERROR:" + throwable.getMessage), ContentType("application/csv") ) } } import Csv.ResponseBuilder._ val service: Service[Request, Response] = Service.mk { _: Request => Ok(List("this", "is", "comma", "separated", "hello", "world")) } val route: ServerRoute[Request, Response] = RouteSpec().at(Get) bindTo service val module: Module = RouteModule(Root).withRoute(route) ready(Http.serve(":9999", module.toService)) } //curl -v http://localhost:9999
Example 57
Source File: Simple_HTML_Example.scala From fintrospect with Apache License 2.0 | 5 votes |
package cookbook.core // fintrospect-core object Simple_HTML_Example extends App { import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import com.twitter.util.Await.ready import io.fintrospect.formats.Html.ResponseBuilder._ import io.fintrospect.{Module, RouteModule, RouteSpec, ServerRoute} val serve: Service[Request, Response] = Service.mk[Request, Response] { req => { Ok( <html> <head> <title>The Title</title> </head> <body>Some content goes here</body> </html>.toString() ) } } val route: ServerRoute[Request, Response] = RouteSpec().at(Get) bindTo serve val module: Module = RouteModule(Root).withRoute(route) ready(Http.serve(":9999", module.toService)) } //curl -v http://localhost:9999/'
Example 58
Source File: Accepting_Multiple_Body_Types_Example.scala From fintrospect with Apache License 2.0 | 5 votes |
package cookbook.core // fintrospect-core object Accepting_Multiple_Body_Types_Example extends App { import argo.jdom.JsonNode import com.twitter.finagle.http.Method.Post import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import com.twitter.util.Await.ready import io.fintrospect.parameters.Body import io.fintrospect.util.MultiBodyType import io.fintrospect.{Module, RouteModule, RouteSpec, ServerRoute} import scala.xml.Elem val json: Body[JsonNode] = Body.json() val echoJson: Service[Request, Response] = Service.mk[Request, Response] { req => import io.fintrospect.formats.Argo.ResponseBuilder._ Ok(json <-- req) } val xml: Body[Elem] = Body.xml() val echoXml: Service[Request, Response] = Service.mk[Request, Response] { req => import io.fintrospect.formats.Xml.ResponseBuilder._ Ok(xml <-- req) } val route: ServerRoute[Request, Response] = RouteSpec("echo posted content in either JSON or XML") .at(Post) bindTo MultiBodyType(json -> echoJson, xml -> echoXml) val module: Module = RouteModule(Root).withRoute(route) ready(Http.serve(":9999", module.toService)) } //curl -v -XPOST -H"Content-Type: application/json" http://localhost:9999/ --data '{"name":"David"}' //curl -v -XPOST -H"Content-Type: application/xml" http://localhost:9999/ --data '<name>David</name>'
Example 59
Source File: Module_Filters_Example.scala From fintrospect with Apache License 2.0 | 5 votes |
package cookbook.core // fintrospect-core object Module_Filters_Example extends App { import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Filter, Http, Service} import com.twitter.util.Await.ready import io.fintrospect.formats.PlainText.ResponseBuilder._ import io.fintrospect.renderers.ModuleRenderer import io.fintrospect.{Module, RouteModule, RouteSpec, ServerRoute} val headers: Service[Request, Response] = Service.mk[Request, Response] { req => Ok(req.uri) } val route: ServerRoute[Request, Response] = RouteSpec().at(Get) bindTo headers val timingFilter = Filter.mk[Request, Response, Request, Response] { (req, next) => val start = System.currentTimeMillis() next(req).map { resp => { val time = System.currentTimeMillis() - start resp.headerMap("performance") = s"${resp.contentString} took $time ms" resp } } } val module: Module = RouteModule(Root, ModuleRenderer.Default, timingFilter).withRoute(route) ready(Http.serve(":9999", module.toService)) } //curl -v http://localhost:9999
Example 60
Source File: Extracting_Upstream_Responses.scala From fintrospect with Apache License 2.0 | 5 votes |
package cookbook.core // fintrospect-core object Extracting_Upstream_Responses extends App { import argo.jdom.JsonNode import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import com.twitter.util.Await.result import io.fintrospect.configuration.{Authority, Host, Port} import io.fintrospect.filters.RequestFilters.AddHost import io.fintrospect.filters.ResponseFilters import io.fintrospect.parameters.{Body, BodySpec, Path} import io.fintrospect.util.{Extracted, Extraction, ExtractionFailed} import io.fintrospect.{RouteClient, RouteSpec} case class Pokemon(id: Int, name: String, weight: Int) object Pokemon { def from(j: JsonNode) = Pokemon(j.getNumberValue("id").toInt, j.getStringValue("name"), j.getNumberValue("weight").toInt) } val authority: Authority = Host("pokeapi.co").toAuthority(Port._80) val http: Service[Request, Response] = AddHost(authority).andThen(Http.newService(authority.toString)) val id = Path.int("pokemonId") val spec: BodySpec[Pokemon] = BodySpec.json().map(Pokemon.from) val nameAndWeight: Body[Pokemon] = Body.of(spec) val client: RouteClient[Extraction[Option[Pokemon]]] = RouteSpec().at(Get) / "api" / "v2" / "pokemon" / id / "" bindToClient ResponseFilters.ExtractBody(nameAndWeight).andThen(http) def reportOnPokemon(pid: Int) = println( result(client(id --> pid)) match { case Extracted(Some(pokemon)) => s"i found a pokemon: $pokemon" case Extracted(None) => s"there is no pokemon with id $pid" case ExtractionFailed(errors) => s"problem extracting response $errors" } ) reportOnPokemon(1) reportOnPokemon(11) reportOnPokemon(9999) }
Example 61
Source File: Simple_JSON_Example.scala From fintrospect with Apache License 2.0 | 5 votes |
package cookbook.core // fintrospect-core object Simple_JSON_Example extends App { import java.time.ZonedDateTime import argo.jdom.JsonNode import com.twitter.finagle.http.Method.Post import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import com.twitter.util.Await.ready import io.fintrospect.formats.Argo.JsonFormat._ import io.fintrospect.formats.Argo.ResponseBuilder._ import io.fintrospect.parameters.Body import io.fintrospect.{Module, RouteModule, RouteSpec, ServerRoute} val json: Body[JsonNode] = Body.json() val echo: Service[Request, Response] = Service.mk[Request, Response] { req => val requestJson: JsonNode = json <-- req val responseJson: JsonNode = obj( "posted" -> requestJson, "time" -> string(ZonedDateTime.now().toString) ) Ok(responseJson) } val route: ServerRoute[Request, Response] = RouteSpec().body(json).at(Post) bindTo echo val module: Module = RouteModule(Root).withRoute(route) ready(Http.serve(":9999", module.toService)) } //curl -v -XPOST http://localhost:9999/ --data '{"name":"David"}'
Example 62
Source File: Combining_Modules_Example.scala From fintrospect with Apache License 2.0 | 5 votes |
package cookbook.core // fintrospect-core object Combining_Modules_Example extends App { import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import com.twitter.util.Await.ready import io.fintrospect.formats.PlainText.ResponseBuilder._ import io.fintrospect.{Module, RouteModule, RouteSpec, ServerRoute} val identify: Service[Request, Response] = Service.mk { req: Request => Ok(req.uri) } val route: ServerRoute[Request, Response] = RouteSpec().at(Get) bindTo identify val childModule: Module = RouteModule(Root / "child").withRoute(route) val rootModule: Module = RouteModule(Root).withRoute(route) ready(Http.serve(":9999", childModule.andThen(rootModule).toService)) } //curl -v http://localhost:9999/child //curl -v http://localhost:9999
Example 63
Source File: Streaming_Response_Example.scala From fintrospect with Apache License 2.0 | 5 votes |
package cookbook.core // fintrospect-core object Streaming_Response_Example extends App { import argo.jdom.JsonNode import com.twitter.concurrent.AsyncStream import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Http, Service} import com.twitter.util.Await.ready import com.twitter.util.Duration.fromSeconds import com.twitter.util.Future.sleep import com.twitter.util.JavaTimer import io.fintrospect.formats.Argo.JsonFormat._ import io.fintrospect.formats.Argo.ResponseBuilder._ import io.fintrospect.{Module, RouteModule, RouteSpec, ServerRoute} val timer = new JavaTimer() def ints(i: Int): AsyncStream[Int] = i +:: AsyncStream.fromFuture(sleep(fromSeconds(1))(timer)).flatMap(_ => ints(i + 1)) def jsonStream: AsyncStream[JsonNode] = ints(0).map(i => obj("number" -> number(i))) val count: Service[Request, Response] = Service.mk[Request, Response] { req => Ok(jsonStream) } val route: ServerRoute[Request, Response] = RouteSpec().at(Get) bindTo count val module: Module = RouteModule(Root).withRoute(route) ready(Http.serve(":9999", module.toService)) } //curl --raw http://localhost:9999/
Example 64
Source File: PlayTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.formats import com.twitter.finagle.Service import com.twitter.finagle.http.Request import com.twitter.io.{Buf, Bufs} import com.twitter.util.Future import io.fintrospect.formats.JsonFormat.InvalidJsonForDecoding import io.fintrospect.formats.Play.Auto._ import io.fintrospect.formats.Play.JsonFormat._ import io.fintrospect.formats.Play._ import io.fintrospect.parameters.{Body, BodySpec, Query} import play.api.libs.json._ object helpers { implicit val SAWrites = new Writes[StreetAddress] { override def writes(in: StreetAddress) = JsObject(Seq("address" -> JsString(in.address))) } implicit val SAReads = new Reads[StreetAddress] { override def reads(in: JsValue) = JsSuccess(StreetAddress( (in \ "address").as[String] )) } implicit val Writes = Json.writes[Letter] implicit val Reads = Json.reads[Letter] } class PlayAutoTest extends AutoSpec(Play.Auto) { import helpers._ describe("API") { it("can find implicits") { Play.Auto.InOut[Letter, Letter](Service.mk { in: Letter => Future(in) }) } } override def toBuf(l: Letter) = Bufs.utf8Buf(compact(Play.JsonFormat.encode(l)(Writes))) override def fromBuf(s: Buf): Letter = decode[Letter](parse(Bufs.asUtf8String(s)))(Reads) override def bodySpec: BodySpec[Letter] = Play.bodySpec[Letter]()(helpers.Reads, helpers.Writes) override def transform() = Play.Auto.tToJsValue[Letter](Writes) } class PlayJsonResponseBuilderTest extends JsonResponseBuilderSpec(Play) class PlayJsonFormatTest extends JsonFormatSpec(Play) { describe("Play.JsonFormat") { val aLetter = Letter(StreetAddress("my house"), StreetAddress("your house"), "hi there") it("roundtrips to JSON and back") { val encoded = Play.JsonFormat.encode(aLetter)(helpers.Writes) Play.JsonFormat.decode[Letter](encoded)(helpers.Reads) shouldBe aLetter } it("invalid extracted JSON throws up") { intercept[InvalidJsonForDecoding](Play.JsonFormat.decode[Letter](Play.JsonFormat.obj())(helpers.Reads)) } it("body spec decodes content") { (Body.of(bodySpec[Letter]()(helpers.Reads, helpers.Writes)) <-- Play.ResponseBuilder.Ok(encode(aLetter)(helpers.Writes)).build()) shouldBe aLetter } it("param spec decodes content") { val param = Query.required(parameterSpec[Letter]()(helpers.Reads, helpers.Writes), "name") (param <-- Request("?name=" + encode(aLetter)(helpers.Writes))) shouldBe aLetter } } }
Example 65
Source File: CirceTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.formats import com.twitter.finagle.Service import com.twitter.finagle.http.{Request, Status} import com.twitter.io.{Buf, Bufs} import com.twitter.util.Future import io.circe.generic.auto._ import io.fintrospect.formats.Circe.Auto._ import io.fintrospect.formats.Circe.JsonFormat._ import io.fintrospect.formats.Circe._ import io.fintrospect.formats.JsonFormat.InvalidJsonForDecoding import io.fintrospect.parameters.{Body, BodySpec, Query} class CirceJsonResponseBuilderTest extends JsonResponseBuilderSpec(Circe) class CirceAutoTest extends AutoSpec(Circe.Auto) { describe("API") { it("can find implicits") { Circe.Auto.InOut[Letter, Letter](Service.mk { in: Letter => Future(in) }) } } override def toBuf(l: Letter) = Bufs.utf8Buf(encode(l).noSpaces) override def fromBuf(s: Buf): Letter = decode[Letter](parse(Bufs.asUtf8String(s))) override def bodySpec: BodySpec[Letter] = Circe.bodySpec[Letter]() override def transform() = Circe.Auto.tToJson[Letter] } class CirceJsonFormatTest extends JsonFormatSpec(Circe) { import io.circe.generic.auto._ describe("Circe.JsonFormat") { val aLetter = Letter(StreetAddress("my house"), StreetAddress("your house"), "hi there") it("roundtrips to JSON and back") { val encoded = encode(aLetter) decode[Letter](encoded) shouldBe aLetter } it("patchbody modifies original object with a non-null value") { val original = LetterOpt(StreetAddress("my house"), StreetAddress("your house"), None) val modifier = encode(obj("message" -> string("hi there"))) val modifyLetter = patcher[LetterOpt](modifier) modifyLetter(original) shouldBe LetterOpt(StreetAddress("my house"), StreetAddress("your house"), Option("hi there")) } // wait for circe 0.6.X, where this bug will be fixed - https://github.com/travisbrown/circe/issues/304 ignore("patcher modifies original object with a null value") { val original = LetterOpt(StreetAddress("my house"), StreetAddress("your house"), Option("hi there")) val modifier = encode(obj()) val modifyLetter = patcher[LetterOpt](modifier) modifyLetter(original) shouldBe LetterOpt(StreetAddress("my house"), StreetAddress("your house"), None) } it("invalid extracted JSON throws up") { intercept[InvalidJsonForDecoding](decode[Letter](Circe.JsonFormat.obj())) } it("body spec decodes content") { (Body.of(bodySpec[Letter]()) <-- Circe.ResponseBuilder.Ok(encode(aLetter)).build()) shouldBe aLetter } it("patch body can be used to modify an existing case class object") { val letterWithNoMessage = LetterOpt(StreetAddress("my house"), StreetAddress("your house"), None) val modifiedMessage = encode(obj("message" -> string("hi there"))) val modifiedLetterWithMessage = LetterOpt(StreetAddress("my house"), StreetAddress("your house"), Some("hi there")) val patch = patchBody[LetterOpt]("path to body", modifiedLetterWithMessage) <-- Circe.ResponseBuilder.Ok(modifiedMessage).build() patch(letterWithNoMessage) shouldBe modifiedLetterWithMessage } it("response spec has correct code") { Circe.responseSpec[Letter](Status.Ok -> "ok", aLetter).status shouldBe Status.Ok } it("param spec decodes content") { val param = Query.required(parameterSpec[Letter](), "name") (param <-- Request("?name=" + encode(aLetter))) shouldBe aLetter } } override val expectedJson: String = """{"string":"hello","object":{"field1":"aString"},"int":10,"long":2,"double":1.2,"decimal":1.2,"bigInt":12344,"bool":true,"null":null,"array":["world",true]}""" }
Example 66
Source File: Auto.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.formats import com.twitter.finagle.http.{Request, Response, Status} import com.twitter.finagle.{Filter, Service} import io.fintrospect.parameters.{Body, Mandatory} import io.fintrospect.util.{Extracted, ExtractionFailed} class Auto[R](responseBuilder: AbstractResponseBuilder[R]) { type SvcBody[IN] = Body[IN] with Mandatory[Request, IN] import responseBuilder._ def OptionalOut[IN, OUT](svc: Service[IN, Option[OUT]], successStatus: Status = Status.Ok) (implicit transform: OUT => R): Service[IN, Response] = Filter.mk[IN, Response, IN, Option[OUT]] { (req, svc) => svc(req) .map( _.map(transform) .map(l => HttpResponse(successStatus).withContent(l)) .getOrElse(HttpResponse(Status.NotFound).withErrorMessage("No object available to unmarshal"))) .map(_.build()) }.andThen(svc) }
Example 67
Source File: ContractProxyModule.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect import com.twitter.finagle.Service import com.twitter.finagle.http.path.{Path, Root} import com.twitter.finagle.http.{Request, Response} import io.fintrospect.renderers.swagger2dot0.{ApiInfo, Swagger2dot0Json} import scala.reflect.runtime.universe.TypeTag import scala.reflect.runtime.{currentMirror, universe} object ContractProxyModule { def apply[T <: Contract](name: String, service: Service[Request, Response], contract: T, rootPath: Path = Root, description: String = null)(implicit tag: TypeTag[T]): RouteModule[Request, Response] = { val descriptionOption = Option(description).getOrElse(s"Proxy services for $name API") val routes = universe.typeOf[T].members .filter(_.isModule) .map(_.asModule) .map(currentMirror.reflectModule(_).instance) .filter(_.isInstanceOf[ContractEndpoint]) .map(_.asInstanceOf[ContractEndpoint].route) routes.foldLeft(RouteModule(rootPath, Swagger2dot0Json(ApiInfo(name, name, descriptionOption)))) { (spec, route) => spec.withRoute(route.bindToProxy(service)) } } }
Example 68
Source File: RouteClient.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect import com.twitter.finagle.http.{Method, Request} import com.twitter.finagle.{Filter, Service} import com.twitter.util.Future import com.twitter.util.Future.exception import io.fintrospect.parameters.{Binding, PathBinding, PathParameter} object RouteClient { private def identify[O](method: Method, pathParams: Seq[PathParameter[_]]) = Filter.mk[Request, O, Request, O] { (request, svc) => { request.headerMap(Headers.IDENTIFY_SVC_HEADER) = method + ":" + pathParams.map(_.toString()).mkString("/") svc(request) } } } def apply(userBindings: Iterable[Binding]*): Future[Rsp] = { val suppliedBindings = userBindings.flatten ++ providedBindings val userSuppliedParams = suppliedBindings.map(_.parameter).filter(_ != null) val missing = requiredParams.diff(userSuppliedParams) val unknown = userSuppliedParams.diff(allPossibleParams) if (missing.nonEmpty) exception(new BrokenContract(s"Client: Missing required params passed: [${missing.mkString(", ")}]")) else if (unknown.nonEmpty) exception(new BrokenContract(s"Client: Unknown params passed: [${unknown.mkString(", ")}]")) else service(buildRequest(suppliedBindings)) } private def buildRequest(suppliedBindings: Seq[Binding]): Request = suppliedBindings .sortBy(p => pathParams.indexOf(p.parameter)) .foldLeft(RequestBuilder(method)) { (requestBuild, next) => next(requestBuild) }.build() }
Example 69
Source File: StaticModule.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect import com.google.common.io.Resources.toByteArray import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.Status.Ok import com.twitter.finagle.http.path.{->, Path, Root} import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{Filter, Service} import com.twitter.io.Buf.ByteArray.Owned import io.fintrospect.ContentType.lookup import io.fintrospect.Module.ServiceBinding import io.fintrospect.formats.ResponseBuilder.HttpResponse object StaticModule { def apply(basePath: Path, resourceLoader: ResourceLoader = ResourceLoader.Classpath(), moduleFilter: Filter[Request, Response, Request, Response] = Filter.identity) = { new StaticModule(basePath, resourceLoader, moduleFilter) } } class StaticModule private(basePath: Path, resourceLoader: ResourceLoader, moduleFilter: Filter[Request, Response, Request, Response]) extends Module { override protected[fintrospect] def serviceBinding: ServiceBinding = { case Get -> path if exists(path) => moduleFilter.andThen(Service.mk[Request, Response] { _ => HttpResponse(lookup(convertPath(path))).withCode(Ok).withContent(Owned(toByteArray(resourceLoader.load(convertPath(path))))) }) } private def exists(path: Path) = if (path.startsWith(basePath)) resourceLoader.load(convertPath(path)) != null else false private def convertPath(path: Path) = { val newPath = if (basePath == Root) path.toString else path.toString.replace(basePath.toString, "") val resolved = if (newPath == "") "/index.html" else newPath resolved.replaceFirst("/", "") } }
Example 70
Source File: MultiBodyType.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.util import com.twitter.finagle.Service import com.twitter.finagle.http.{Request, Response} import com.twitter.util.Future import io.fintrospect.ContentType import io.fintrospect.formats.Argo.ResponseBuilder._ import io.fintrospect.parameters.Body import io.fintrospect.renderers.ModuleRenderer import io.fintrospect.renderers.simplejson.SimpleJson object MultiBodyType { type SupportedContentType = (Body[_], Service[Request, Response]) def apply(services: SupportedContentType*)(implicit moduleRenderer: ModuleRenderer = SimpleJson()): Service[Request, Response] = { val supportedContentTypes = Map(services.map(bs => ContentType(bs._1.contentType.value.toLowerCase) -> bs): _*) def validateAndRespond(request: Request, body: SupportedContentType) = body._1.extract(request) match { case ExtractionFailed(invalid) => Future(moduleRenderer.badRequest(invalid)) case _ => body._2(request) } def handle(request: Request, contentType: ContentType): Future[Response] = supportedContentTypes.get(contentType) .map(pair => validateAndRespond(request, pair)) .getOrElse(UnsupportedMediaType(contentType.value)) Service.mk { request: Request => (ContentType.header <-- request) .map(value => ContentType(value.toLowerCase())) .map(contentType => handle(request, contentType)) .getOrElse(UnsupportedMediaType("missing Content-Type header")) } } }
Example 71
Source File: HeapDump.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.util import java.io.File import java.lang.management.ManagementFactory.getPlatformMXBeans import java.time.Clock import java.time.ZonedDateTime.now import java.time.format.DateTimeFormatter.ISO_DATE_TIME import com.sun.management.HotSpotDiagnosticMXBean import com.twitter.finagle.Service import com.twitter.finagle.http.{Request, Response} import com.twitter.io.Readers import com.twitter.util.Future import io.fintrospect.ContentType import io.fintrospect.formats.ResponseBuilder.HttpResponse class HeapDump(processIdentifier: String = "", clock: Clock = Clock.systemUTC()) extends Service[Request, Response] { override def apply(request: Request): Future[Response] = { val dumpFileName = s"heapdump-$processIdentifier-${now(clock).format(ISO_DATE_TIME)}" val dumpFile = File.createTempFile(dumpFileName, ".hprof") dumpFile.delete() getPlatformMXBeans(classOf[HotSpotDiagnosticMXBean]).get(0).dumpHeap(dumpFile.getAbsolutePath, true) val response = HttpResponse(ContentType("application/x-heap-dump")) .withHeaders("Content-disposition" -> ("inline; filename=\"" + dumpFileName + ".hprof\"")) .withContent(Readers.newFileReader(dumpFile, 1024)).build() Future(response).ensure(dumpFile.delete()) } }
Example 72
Source File: SecurityTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect import com.twitter.finagle.Service import com.twitter.finagle.http.{Request, Response, Status} import com.twitter.util.Await.result import com.twitter.util.Future import io.fintrospect.formats.PlainText.ResponseBuilder._ import io.fintrospect.parameters.Query import io.fintrospect.util.HttpRequestResponseUtil.statusAndContentFrom import org.scalatest.{FunSpec, Matchers} class SecurityTest extends FunSpec with Matchers { describe("ApiKey") { val paramName = "name" val param = Query.required.int(paramName) val next = Service.mk[Request, Response](r => Ok("hello")) it("valid API key is granted access and result carried through") { val (status, content) = result(ApiKey(param, Service.const(Future(true))).filter(Request(paramName -> "1"), next) .map(statusAndContentFrom)) status should be(Status.Ok) content should be("hello") } it("missing API key is unauthorized") { val (status, content) = result(ApiKey(param, Service.const(Future(true))).filter(Request(), next) .map(statusAndContentFrom)) status should be(Status.Unauthorized) content should be("") } it("bad API key is unauthorized") { val (status, content) = result(ApiKey(param, Service.const(Future(true))).filter(Request(paramName -> "notAnInt"), next) .map(statusAndContentFrom)) status should be(Status.Unauthorized) content should be("") } it("unknown API key is unauthorized") { val (status, content) = result(ApiKey(param, Service.const(Future(false))).filter(Request(paramName -> "1"), next) .map(statusAndContentFrom)) status should be(Status.Unauthorized) content should be("") } it("failed API key lookup is rethrown") { val e = new RuntimeException("boom") val caught = intercept[RuntimeException](result(ApiKey(param, Service.const(Future.exception(e))).filter(Request(paramName -> "1"), next))) caught should be(e) } } }
Example 73
Source File: ModuleTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect import com.twitter.finagle.Service import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.path.Path import com.twitter.finagle.http.{Method, Request, Response, Status} import com.twitter.util.Await.result import io.fintrospect.util.Echo import io.fintrospect.util.HttpRequestResponseUtil.statusAndContentFrom import org.scalatest.{FunSpec, Matchers} class ModuleTest extends FunSpec with Matchers { describe("Module") { it("when it matches it responds as expected") { val response = statusAndContentFrom(result(routingWhichMatches((Get, Path("/someUrl")))(Request("/someUrl?field=hello")))) response._1 shouldBe Status.Ok response._2 should include("/someUrl?field=hello") } it("no match responds with default 404") { val response = result(routingWhichMatches((Get, Path("/someUrl")))(Request("/notMyService"))) response.status shouldBe Status.NotFound } } private def routingWhichMatches(methodAndPath: (Method, Path)): Service[Request, Response] = { Module.toService(new PartialFunction[(Method, Path), Service[Request, Response]] { override def isDefinedAt(x: (Method, Path)): Boolean = x === methodAndPath override def apply(v1: (Method, Path)): Service[Request, Response] = Echo() }) } }
Example 74
Source File: ContractProxyModuleTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect import com.twitter.finagle.Service import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.Request import com.twitter.util.Await import io.fintrospect.formats.PlainText.ResponseBuilder._ import io.fintrospect.parameters.Query import org.scalatest.{FunSpec, Matchers} object TestContract extends Contract { object Endpoint extends ContractEndpoint { val query = Query.required.string("query") override val route = RouteSpec().taking(query).at(Get) / "hello" } } class ContractProxyModuleTest extends FunSpec with Matchers { describe("ContractProxyModule") { it("cretes service which proxies requests to the underlying service") { val svc = Service.mk { req: Request => Ok(TestContract.Endpoint.query <-- req) } Await.result(ContractProxyModule("remote", svc, TestContract).toService(Request("/hello?query=value"))).contentString shouldBe "value" } } }
Example 75
Source File: RenderViewTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.templating import com.twitter.finagle.Service import com.twitter.finagle.http.{Request, Status} import com.twitter.io.Bufs import com.twitter.util.Await.result import io.fintrospect.formats.Html import io.fintrospect.templating.View.Redirect import org.scalatest.{FunSpec, Matchers} class RenderViewTest extends FunSpec with Matchers { describe("RenderView") { val renderView = new RenderView(Html.ResponseBuilder, new TemplateRenderer { override def toBuf(view: View) = Bufs.utf8Buf(view.template) }) it("creates a standard View") { val response = result(renderView(Request(), Service.const(OnClasspath(Nil)))) response.status shouldBe Status.Ok response.contentString shouldBe "io/fintrospect/templating/OnClasspath" } it("creates a standard View with an overridden status") { val response = result(renderView(Request(), Service.const(OnClasspath(Nil, Status.NotFound)))) response.status shouldBe Status.NotFound response.contentString shouldBe "io/fintrospect/templating/OnClasspath" } it("creates redirect when passed a RenderView.Redirect") { val response = result(renderView(Request(), Service.const(Redirect("newLocation", Status.BadGateway)))) response.status shouldBe Status.BadGateway response.headerMap("Location") shouldBe "newLocation" } } }
Example 76
Source File: ArgoJsonModuleRendererTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.renderers import com.twitter.finagle.Service import com.twitter.finagle.http.Method.{Get, Post} import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Request, Status} import com.twitter.util.{Await, Future} import io.fintrospect.ContentTypes.{APPLICATION_ATOM_XML, APPLICATION_JSON, APPLICATION_SVG_XML} import io.fintrospect._ import io.fintrospect.formats.Argo import io.fintrospect.formats.Argo.JsonFormat.{number, obj, parse} import io.fintrospect.parameters._ import io.fintrospect.util.HttpRequestResponseUtil.statusAndContentFrom import io.fintrospect.util.{Echo, ExtractionError} import org.scalatest.{FunSpec, Matchers} import scala.io.Source abstract class ArgoJsonModuleRendererTest() extends FunSpec with Matchers { def name: String = this.getClass.getSimpleName def renderer: ModuleRenderer describe(name) { it("renders as expected") { val customBody = Body.json("the body of the message", obj("anObject" -> obj("notAStringField" -> number(123)))) val module = RouteModule(Root / "basepath", renderer) .securedBy(ApiKey(Header.required.string("the_api_key"), Service.const(Future(true)))) .withRoute( RouteSpec("summary of this route", "some rambling description of what this thing actually does") .producing(APPLICATION_JSON) .taking(Header.optional.string("header", "description of the header")) .returning(ResponseSpec.json(Status.Ok -> "peachy", obj("anAnotherObject" -> obj("aNumberField" -> number(123))))) .returning(ResponseSpec.json(Status.Accepted -> "peachy", obj("anAnotherObject" -> obj("aNumberField" -> number(123))))) .returning(Status.Forbidden -> "no way jose") .taggedWith("tag3") .taggedWith("tag1") .at(Get) / "echo" / Path.string("message") bindTo ((s: String) => Echo(s))) .withRoute( RouteSpec("a post endpoint") .consuming(APPLICATION_ATOM_XML, APPLICATION_SVG_XML) .producing(APPLICATION_JSON) .returning(ResponseSpec.json(Status.Forbidden -> "no way jose", obj("aString" -> Argo.JsonFormat.string("a message of some kind")))) .taking(Query.required.int("query")) .body(customBody) .taggedWith("tag1") .taggedWith(TagInfo("tag2", "description of tag"), TagInfo("tag2", "description of tag")) .at(Post) / "echo" / Path.string("message") bindTo ((s: String) => Echo(s))) .withRoute( RouteSpec("a friendly endpoint") .taking(Query.required.boolean("query", "description of the query")) .body(Body.form(FormField.required.int("form", "description of the form"))) .at(Get) / "welcome" / Path.string("firstName") / "bertrand" / Path.string("secondName") bindTo ((x: String, y: String, z: String) => Echo(x, y, z))) val expected = parse(Source.fromInputStream(this.getClass.getResourceAsStream(s"$name.json")).mkString) val actual = Await.result(module.toService(Request("/basepath"))).contentString // println(Argo.JsonFormat.pretty(parse(actual))) parse(actual) shouldBe expected } it("can build 400") { val response = statusAndContentFrom(renderer.badRequest(Seq(ExtractionError(Query.required.string("bob"), "missing")))) response._1 shouldBe Status.BadRequest parse(response._2).getStringValue("message") shouldBe "Missing/invalid parameters" } it("can build 404") { val response = statusAndContentFrom(renderer.notFound(Request())) response._1 shouldBe Status.NotFound parse(response._2).getStringValue("message") shouldBe "No route found on this path. Have you used the correct HTTP verb?" } } }
Example 77
Source File: SiteMapModuleRendererTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.renderers import java.net.URL import com.twitter.finagle.Service import com.twitter.finagle.http.Method._ import com.twitter.finagle.http.Status.{BadRequest, NotFound, Ok} import com.twitter.finagle.http.path.Root import com.twitter.finagle.http.{Method, Request, Response} import com.twitter.util.Future import io.fintrospect.util.HttpRequestResponseUtil.statusAndContentFrom import io.fintrospect.{NoSecurity, RouteSpec, ServerRoute} import org.scalatest.{FunSpec, Matchers} class SiteMapModuleRendererTest extends FunSpec with Matchers { it("renders 400") { new SiteMapModuleRenderer(new URL("http://fintrospect.io")).badRequest(Nil).status shouldBe BadRequest } it("renders 404") { new SiteMapModuleRenderer(new URL("http://fintrospect.io")).notFound(Request()).status shouldBe NotFound } it("should describe only GET endpoints of module as a sitemap") { val rsp = new SiteMapModuleRenderer(new URL("http://fintrospect.io")).description(Root / "bob", NoSecurity, Seq( endpointFor(Get), endpointFor(Post), endpointFor(Delete), endpointFor(Put), endpointFor(Options), endpointFor(Connect), endpointFor(Head), endpointFor(Trace) )) val (status, content) = statusAndContentFrom(rsp) status shouldBe Ok content shouldBe <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc> http://fintrospect.io/bob/GET </loc> </url> </urlset>.toString() } private def endpointFor(method: Method): ServerRoute[Request, Response] = { RouteSpec().at(method) / method.toString() bindTo Service.mk[Request, Response]((r) => Future(Response())) } }
Example 78
Source File: StrictContentTypeNegotiationTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.util import com.twitter.finagle.Service import com.twitter.finagle.http.Status.{NotAcceptable, Ok} import com.twitter.finagle.http.{Request, Response} import com.twitter.util.Await.result import com.twitter.util.Future import io.fintrospect.ContentType import io.fintrospect.ContentTypes.{APPLICATION_ATOM_XML, APPLICATION_JSON, TEXT_HTML} import io.fintrospect.formats.ResponseBuilder import org.scalatest.{FunSpec, Matchers} class StrictContentTypeNegotiationTest extends FunSpec with Matchers { describe("StrictContentTypeNegotiation") { it("on no match, return 406") { val r = result(StrictContentTypeNegotiation(serviceForType(APPLICATION_ATOM_XML))(requestWithAcceptHeaders(APPLICATION_JSON.value))) r.status shouldBe NotAcceptable } it("when there are no accept header set, just chooses the first type") { val r = result(StrictContentTypeNegotiation(serviceForType(APPLICATION_ATOM_XML), serviceForType(APPLICATION_JSON))(requestWithAcceptHeaders())) r.status shouldBe Ok r.headerMap("Content-Type") should startWith(APPLICATION_ATOM_XML.value) } it("when there is a wildcard set, just chooses the first type") { val r = result(StrictContentTypeNegotiation(serviceForType(APPLICATION_ATOM_XML), serviceForType(APPLICATION_JSON))(requestWithAcceptHeaders("**;q=0.5"))) r.status shouldBe Ok r.headerMap("Content-Type") should startWith(TEXT_HTML.value) } } private def serviceForType(contentType: ContentType): (ContentType, Service[Request, Response]) = contentType -> Service.mk[Request, Response] { r => Future(ResponseBuilder.HttpResponse(contentType).build()) } private def requestWithAcceptHeaders(headers: String*): Request = { val request = Request() headers.foreach(value => request.headerMap.add("Accept", value)) request } }
Example 79
Source File: MultiBodyTypeTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.util import com.twitter.finagle.Service import com.twitter.finagle.http.Status.Ok import com.twitter.finagle.http.{Request, Response, Status} import com.twitter.util.Await.result import com.twitter.util.Future import io.fintrospect.ContentType import io.fintrospect.ContentTypes.APPLICATION_JSON import io.fintrospect.parameters.Body import org.scalatest.{FunSpec, Matchers} class MultiBodyTypeTest extends FunSpec with Matchers { val xmlBody = Body.xml() val xmlAccepting = MultiBodyType(xmlBody -> Service.mk { req: Request => Future(Response(Ok)) }) describe("MultiBodyType") { it("on no match, reject with 415") { val r = result(xmlAccepting(requestFromContentType(APPLICATION_JSON))) r.status shouldBe Status.UnsupportedMediaType } it("when there are no content-type header set, reject with 415") { val r = result(xmlAccepting(requestFromContentType())) r.status shouldBe Status.UnsupportedMediaType } it("when there is an exact (case insensitive) match on a content type, use that service") { val r = Request() r.headerMap("Content-Type") = "application/xml" r.contentString = "<xml/>" val resp = result(xmlAccepting(r)) resp.status shouldBe Ok } } def requestFromContentType(headers: ContentType*): Request = { val request = Request() headers.foreach(value => request.headerMap.add("Content-Type", value.value)) request } }
Example 80
Source File: OverridableHttpServiceTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.testing import com.twitter.finagle.Service import com.twitter.finagle.http.Status.{Accepted, Conflict} import com.twitter.finagle.http.{Request, Response, Status} import com.twitter.util.{Await, Future} import org.scalatest.{FunSpec, Matchers} class OverridableHttpServiceTest extends FunSpec with Matchers { val originalStatus = Conflict val overridableHttpService = new OverridableHttpService[Request](Service.mk { r: Request => Future(Response(originalStatus)) }) it("will serve routes that are passed to it") { statusShouldBe(originalStatus) } it("can override status") { overridableHttpService.respondWith(Accepted) statusShouldBe(Accepted) } private def statusShouldBe(expected: Status): Unit = { Await.result(overridableHttpService.service(Request())).status shouldBe expected } }
Example 81
Source File: TestHttpServerTest.scala From fintrospect with Apache License 2.0 | 5 votes |
package io.fintrospect.testing import com.twitter.finagle.http.Method.Get import com.twitter.finagle.http.Status.{Accepted, Conflict} import com.twitter.finagle.http.{Request, Response, Status} import com.twitter.finagle.{Http, Service} import com.twitter.util.{Await, Future} import io.fintrospect.RouteSpec import org.scalatest.{BeforeAndAfterEach, FunSpec, Matchers} class TestHttpServerTest extends FunSpec with Matchers with BeforeAndAfterEach { val originalStatus = Conflict private val server = new TestHttpServer(9888, RouteSpec().at(Get) bindTo Service.mk { r: Request => Future(Response(originalStatus)) }) override def beforeEach() = { Await.result(server.start()) } override def afterEach() = { Await.result(server.stop()) } it("will serve routes that are passed to it") { statusShouldBe(originalStatus) } it("can override status") { server.respondWith(Accepted) statusShouldBe(Accepted) } private def statusShouldBe(expected: Status): Unit = { Await.result(Http.newService("localhost:9888", "")(Request())).status shouldBe expected } }
Example 82
Source File: App.scala From finagle-metrics with MIT License | 5 votes |
import com.codahale.metrics.ConsoleReporter import com.twitter.finagle.{ Http, Service } import com.twitter.finagle.metrics.MetricsStatsReceiver import com.twitter.finagle.http.{ Request, Response, Status } import com.twitter.io.Charsets import com.twitter.server.TwitterServer import com.twitter.util.{ Await, Future } import java.util.concurrent.TimeUnit object App extends TwitterServer { val service = new Service[Request, Response] { def apply(request: Request) = { val response = Response(request.version, Status.Ok) response.contentString = "hello" Future.value(response) } } val reporter = ConsoleReporter .forRegistry(MetricsStatsReceiver.metrics) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build def main() = { val server = Http.serve(":8080", service) reporter.start(5, TimeUnit.SECONDS) onExit { server.close() } Await.ready(server) } }
Example 83
Source File: ProcessReportHandler.scala From finagle-microservice-sample with Apache License 2.0 | 5 votes |
import com.twitter.finagle.Service import com.twitter.finagle.http.Response import com.twitter.util.Future import org.jboss.netty.handler.codec.http.HttpResponseStatus import reports.ReportProcessor class ProcessReportHandler(reportProcessor: ReportProcessor) extends Service[AuthorizedRequest, Response] { val processReportUrl = "/report/([0-9]+)/process".r override def apply(req: AuthorizedRequest): Future[Response] = req.request.path match { case processReportUrl(processId) => reportProcessor.processReport(processId.toInt) map { _ => val response = Response(req.request.getProtocolVersion(), HttpResponseStatus.OK) response.setContentTypeJson() response.setContentString( s""" { "processId": $processId, "processed": true } """) response } rescue { case _ => Future.value(Response(req.request.getProtocolVersion(), HttpResponseStatus.INTERNAL_SERVER_ERROR)) } case _ => Future.value(Response(req.request.getProtocolVersion(), HttpResponseStatus.NOT_FOUND)) } }
Example 84
Source File: AuthenticationFilter.scala From finagle-microservice-sample with Apache License 2.0 | 5 votes |
import com.twitter.finagle.{Service, Filter} import com.twitter.finagle.http.{Response, Request} import com.twitter.util.Future import data.UserData import org.jboss.netty.handler.codec.http.HttpHeaders.Names import org.jboss.netty.handler.codec.http.HttpResponseStatus class AuthenticationFilter(loginService: LoginService) extends Filter[Request, Response, AuthorizedRequest, Response] { override def apply(request: Request, continue: Service[AuthorizedRequest, Response]): Future[Response] = { if(request.headers().contains(Names.AUTHORIZATION)) { //for simplicity, we assume the Authorization request header is in the format "username:password" request.headers().get(Names.AUTHORIZATION).split(":") match { case Array(username, password) => if(loginService.login(username, password)) { val authorizedRequest = AuthorizedRequest(request, UserData(username, List("guest"))) continue(authorizedRequest) //continue to the next service/filter } else unauthorized(request) case _ => unauthorized(request) } } else unauthorized(request) } def unauthorized(request: Request): Future[Response] = Future.value(Response(request.getProtocolVersion(), HttpResponseStatus.UNAUTHORIZED)) }
Example 85
Source File: FinagleImpl.scala From c4proto with Apache License 2.0 | 5 votes |
package ee.cone.c4gate import com.twitter.finagle.{Http, Service} import com.twitter.finagle.http import com.twitter.io.Buf import com.twitter.util.{Future, Promise, Return, Throw, Try => TTry} import ee.cone.c4actor.{Executable, Execution} import ee.cone.c4gate.HttpProtocol.{N_Header, S_HttpResponse} import ee.cone.c4proto.ToByteString import scala.concurrent.ExecutionContext import scala.util.{Failure, Success, Try => STry} class FinagleService(handler: FHttpHandler)(implicit ec: ExecutionContext) extends Service[http.Request, http.Response] { def apply(req: http.Request): Future[http.Response] = { val promise = Promise[http.Response]() val future: concurrent.Future[S_HttpResponse] = handler.handle(encode(req)) future.onComplete(res => promise.update(decodeTry(res).map(decode))) promise } def encode(req: http.Request): FHttpRequest = { val method = req.method.name val path = req.path val headerMap = req.headerMap val headers = headerMap.keys.toList.sorted .flatMap(k=>headerMap.getAll(k).map(v=>N_Header(k,v))) val body = ToByteString(Buf.ByteArray.Owned.extract(req.content)) FHttpRequest(method,path,headers,body) } def decode(response: S_HttpResponse): http.Response = { val finResponse = http.Response(http.Status(Math.toIntExact(response.status))) response.headers.foreach(h=>finResponse.headerMap.add(h.key,h.value)) finResponse.write(Buf.ByteArray.Owned(response.body.toByteArray)) finResponse } def decodeTry[T](res: STry[T]): TTry[T] = res match { case Success(v) => Return(v) case Failure(e) => Throw(e) } } class FinagleHttpServer(port: Int, handler: FHttpHandler, execution: Execution) extends Executable { def run(): Unit = Http.serve(s":$port", new FinagleService(handler)(ExecutionContext.fromExecutor(execution.newExecutorService("finagle-",None)))) }
Example 86
Source File: HelloWorld.scala From finch-101 with Apache License 2.0 | 5 votes |
package i.f.workshop.finagle import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.{ListeningServer, Http, Service} import com.twitter.io.Buf import com.twitter.util.{Await, Future} object HelloWorld extends App { val service: Service[Request, Response] = new Service[Request, Response] { def apply(req: Request): Future[Response] = { val rep: Response = Response() rep.content = Buf.Utf8("Hello, World!") Future.value(rep) } } val server: ListeningServer = Http.server.serve(":8081", service) Await.ready(server) }
Example 87
Source File: StackParams.scala From finch-101 with Apache License 2.0 | 5 votes |
package i.f.workshop.finagle import com.twitter.finagle.param import com.twitter.finagle.http.{Response, Request} import com.twitter.finagle.service.TimeoutFilter import com.twitter.finagle.transport.Transport import com.twitter.finagle.{Http, Service} import com.twitter.util._ import com.twitter.conversions.time._ object StackParams extends App { implicit val timer: Timer = new JavaTimer() val service: Service[Request, Response] = new Service[Request, Response] { def apply(req: Request): Future[Response] = Future.sleep(5.seconds).map(_ => Response()) } val monitor: Monitor = new Monitor { def handle(exc: Throwable): Boolean = { println(exc) false } } Await.ready(Http.server .configured(TimeoutFilter.Param(1.seconds)) .configured(Transport.Verbose(true)) .configured(param.Monitor(monitor)) .serve(":8081", service) ) }
Example 88
Source File: MesosMasterClient.scala From cosmos with Apache License 2.0 | 5 votes |
package com.mesosphere.cosmos import com.mesosphere.cosmos.http.RequestSession import io.lemonlabs.uri.Uri import io.lemonlabs.uri.dsl._ import com.twitter.finagle.Service import com.twitter.finagle.http.Request import com.twitter.finagle.http.Response import com.twitter.util.Future import io.lemonlabs.uri.QueryString import org.jboss.netty.handler.codec.http.HttpMethod class MesosMasterClient( mesosUri: Uri, client: Service[Request, Response] ) extends ServiceClient(mesosUri) { def tearDownFramework( frameworkId: String )( implicit session: RequestSession ): Future[thirdparty.mesos.master.model.MesosFrameworkTearDownResponse] = { val formData = QueryString.fromPairs("frameworkId" -> frameworkId).toString() val encodedString = formData.toString.substring(1) val uri = "master" / "teardown" client(postForm(uri, encodedString)) .map(validateResponseStatus(HttpMethod.POST, uri, _)) .map { _ => thirdparty.mesos.master.model.MesosFrameworkTearDownResponse() } } def getFrameworks( name: String )( implicit session: RequestSession ): Future[List[thirdparty.mesos.master.model.Framework]] = { val uri = "master" / "frameworks" val request = get(uri) client(request).flatMap( decodeTo[thirdparty.mesos.master.model.MasterState](HttpMethod.GET, uri, _) ).map { state => state.frameworks.filter(_.name == name) } } }
Example 89
Source File: TimedMulticastService.scala From diffy with GNU Affero General Public License v3.0 | 5 votes |
package ai.diffy.proxy import com.twitter.finagle.Service import com.twitter.util.{Future, Try} class TimedMulticastService[-A, +B](services: Seq[Service[A, B]]) extends Service[A, Seq[(Try[B], Long, Long)]] { def apply(request: A): Future[Seq[(Try[B], Long, Long)]] = services.foldLeft[Future[Seq[(Try[B], Long, Long)]]](Future.Nil){ case (acc, service) => acc flatMap { responseTriesWithTiming => val start = System.currentTimeMillis() val nextResponse: Future[Try[B]] = service(request).liftToTry nextResponse map { responseTry: Try[B] => { val end = System.currentTimeMillis() responseTriesWithTiming ++ Seq((responseTry, start, end)) }} } } }
Example 90
Source File: SequentialMulticastService.scala From diffy with GNU Affero General Public License v3.0 | 5 votes |
package ai.diffy.proxy import com.twitter.finagle.Service import com.twitter.util.{Future, Try} class SequentialMulticastService[-A, +B]( services: Seq[Service[A, B]]) extends Service[A, Seq[Try[B]]] { def apply(request: A): Future[Seq[Try[B]]] = services.foldLeft[Future[Seq[Try[B]]]](Future.Nil){ case (acc, service) => acc flatMap { responseTries => val nextResponse = service(request).liftToTry nextResponse map { responseTry => responseTries ++ Seq(responseTry) } } } }
Example 91
Source File: ClientService.scala From diffy with GNU Affero General Public License v3.0 | 5 votes |
package ai.diffy.proxy import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.thrift.ThriftClientRequest import com.twitter.finagle.{Addr, Name, Service} import com.twitter.util.{Time, Var} trait ClientService[Req, Rep] { val client: Service[Req, Rep] } case class ThriftService( override val client: Service[ThriftClientRequest, Array[Byte]], path: Name) extends ClientService[ThriftClientRequest, Array[Byte]] { var members: Int = 0 var serversetValid = false var changedAt: Option[Time] = None var resetAt: Option[Time] = None var changeCount: Int = 0 val boundServerset: Option[Var[Addr]] = path match { case Name.Bound(addr) => serversetValid = true Some(addr) case _ => serversetValid = false None } boundServerset foreach { _.changes.respond { case Addr.Bound(addrs, _) => serversetValid = true sizeChange(addrs.size) case Addr.Failed(_) | Addr.Neg => serversetValid = false sizeChange(0) case Addr.Pending => () } } private[this] def sizeChange(size: Int) { changeCount += 1 if (changeCount > 1) { changedAt = Some(Time.now) if (members == 0) { resetAt = Some(Time.now) } } members = size } } case class HttpService( override val client: Service[Request, Response]) extends ClientService[Request, Response]
Example 92
Source File: SequentialMulticastServiceSpec.scala From diffy with GNU Affero General Public License v3.0 | 5 votes |
package ai.diffy.proxy import ai.diffy.ParentSpec import com.twitter.finagle.Service import com.twitter.util._ import org.junit.runner.RunWith import org.mockito.Mockito._ import org.scalatest.junit.JUnitRunner @RunWith(classOf[JUnitRunner]) class SequentialMulticastServiceSpec extends ParentSpec { describe("SequentialMulticastService"){ val first, second = mock[Service[String, String]] val multicastHandler = new SequentialMulticastService(Seq(first, second)) it("must not access second until first is done"){ val firstResponse, secondResponse = new Promise[String] when(first("anyString")) thenReturn firstResponse when(second("anyString")) thenReturn secondResponse val result = multicastHandler("anyString") verify(first)("anyString") verifyZeroInteractions(second) firstResponse.setValue("first") verify(second)("anyString") secondResponse.setValue("second") Await.result(result) must be(Seq(Try("first"), Try("second"))) } it("should call all services") { val request = "anyString" val services = Seq.fill(100)(mock[Service[String, Int]]) val responses = Seq.fill(100)(new Promise[Int]) val svcResp = services zip responses svcResp foreach { case (service, response) => when(service(request)) thenReturn response } val sequentialMulticast = new SequentialMulticastService(services) val result = sequentialMulticast("anyString") def verifySequentialInteraction(s: Seq[((Service[String,Int], Promise[Int]), Int)]): Unit = s match { case Nil => case Seq(((svc, resp), index), tail@_*) => { verify(svc)(request) tail foreach { case ((subsequent, _), _) => verifyZeroInteractions(subsequent) } resp.setValue(index) verifySequentialInteraction(tail) } } verifySequentialInteraction(svcResp.zipWithIndex) Await.result(result) must be((0 until 100).toSeq map {i => Try(i)}) } } }
Example 93
Source File: FinchTemplateApi.scala From finch-template with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.redbubble.finchtemplate import com.redbubble.finchtemplate.api.v1 import com.redbubble.finchtemplate.api.v1.FinchTemplateErrorHandler.apiErrorHandler import com.redbubble.finchtemplate.api.v1.{FinchTemplateErrorHandler, ResponseEncoders} import com.redbubble.finchtemplate.util.config.Config._ import com.redbubble.finchtemplate.util.config.{Development, Environment, Test} import com.redbubble.finchtemplate.util.metrics.Metrics._ import com.redbubble.hawk.HawkAuthenticateRequestFilter import com.redbubble.util.http.filter.{ExceptionFilter, HttpBasicAuthFilter, RequestLoggingFilter, RoutingMetricsFilter} import com.twitter.finagle.Service import com.twitter.finagle.http.{Request, Response} import io.finch.Application object ApiAuthFilter extends HawkAuthenticateRequestFilter(apiAuthenticationCredentials, whitelistedAuthPaths, serverMetrics) object BasicAuthFilter extends HttpBasicAuthFilter(s"$systemName Security", basicAuthCredentials, basicAuthPaths, serverMetrics) object UnhandledExceptionsFilter extends ExceptionFilter(ResponseEncoders.throwableEncode, FinchTemplateErrorHandler, serverMetrics) object RouteMetricsFilter extends RoutingMetricsFilter(serverMetrics) object FinchTemplateApi extends ResponseEncoders { private val api = v1.api def apiService: Service[Request, Response] = filters andThen api.handle(apiErrorHandler).toServiceAs[Application.Json] private def filters = { val baseFilters = RequestLoggingFilter andThen UnhandledExceptionsFilter andThen RouteMetricsFilter Environment.env match { case Development => baseFilters case Test => baseFilters case _ => baseFilters andThen ApiAuthFilter andThen BasicAuthFilter } } }
Example 94
Source File: EnvRouting.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.finagle.envRouting import cats.syntax.semigroup._ import com.twitter import com.twitter.finagle.http.{Request, Response, Status} import com.twitter.finagle.{Service, http} import com.twitter.util.{Future, Promise} import monix.eval.Task import monix.execution.Scheduler import ru.tinkoff.tschema.finagle.Rejection.Recover import ru.tinkoff.tschema.finagle._ import ru.tinkoff.tschema.finagle.envRouting.EnvRouting.EnvHttp import ru.tinkoff.tschema.utils.SubString import tofu.env.Env final case class EnvRouting[+R]( request: http.Request, path: CharSequence, matched: Int, embedded: R ) object EnvRouting extends EnvInstanceDecl { type EnvHttp[R, +A] = Env[EnvRouting[R], A] implicit def taskRouted[R] : RoutedPlus[EnvHttp[R, *]] with ConvertService[EnvHttp[R, *]] with LiftHttp[EnvHttp[R, *], Env[R, *]] = envRoutedAny.asInstanceOf[EnvRoutedConvert[R]] implicit def envRunnable[R](implicit recover: Recover[EnvHttp[R, *]] = Recover.default[EnvHttp[R, *]] ): RunHttp[EnvHttp[R, *], Env[R, *]] = response => { val handled = response.onErrorRecoverWith { case Rejected(rej) => recover(rej) } Env(r => Task.deferAction(implicit sched => Task.delay(execResponse(r, handled, _)))) } private[this] def execResponse[R](r: R, envResponse: EnvHttp[R, Response], request: Request)(implicit sc: Scheduler ): Future[Response] = { val promise = Promise[Response] val routing = EnvRouting(request, SubString(request.path), 0, r) val cancelable = envResponse.run(routing).runAsync { case Right(res) => promise.setValue(res) case Left(ex) => val resp = Response(Status.InternalServerError) val message = Option(ex.getLocalizedMessage).getOrElse(ex.toString) resp.setContentString(message) promise.setValue(resp) } promise.setInterruptHandler { case _ => cancelable.cancel() } promise } } private[finagle] class EnvInstanceDecl { protected trait EnvRoutedConvert[R] extends RoutedPlus[EnvHttp[R, *]] with ConvertService[EnvHttp[R, *]] with LiftHttp[EnvHttp[R, *], Env[R, *]] { private type F[a] = EnvHttp[R, a] implicit private[this] val self: RoutedPlus[F] = this def matched: F[Int] = Env.fromFunc(_.matched) def withMatched[A](m: Int, fa: F[A]): F[A] = fa.local(_.copy(matched = m)) def path: F[CharSequence] = Env.fromFunc(_.path) def request: F[http.Request] = Env.fromFunc(_.request) def reject[A](rejection: Rejection): F[A] = Routed.unmatchedPath[F].flatMap(path => throwRej(rejection withPath path.toString)) def combineK[A](x: F[A], y: F[A]): F[A] = catchRej(x)(xrs => catchRej(y)(yrs => throwRej(xrs |+| yrs))) def convertService[A](svc: Service[http.Request, A]): F[A] = Env { r => Task.cancelable { cb => val fut = svc(r.request).respond { case twitter.util.Return(a) => cb.onSuccess(a) case twitter.util.Throw(ex) => cb.onError(ex) } Task(fut.raise(new InterruptedException)) } } def apply[A](fa: Env[R, A]): EnvHttp[R, A] = fa.localP(_.embedded) @inline private[this] def catchRej[A](z: F[A])(f: Rejection => F[A]): F[A] = z.onErrorRecoverWith { case Rejected(xrs) => f(xrs) } @inline private[this] def throwRej[A](map: Rejection): F[A] = Env.raiseError(envRouting.Rejected(map)) } protected object envRoutedAny extends EnvRoutedConvert[Any] }
Example 95
Source File: TaskRouting.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.finagle.envRouting import cats.syntax.semigroup._ import com.twitter import com.twitter.finagle.http.{Request, Response, Status} import com.twitter.finagle.{Service, http} import com.twitter.util.{Future, Promise} import monix.eval.Task import monix.execution.Scheduler import ru.tinkoff.tschema.finagle.Rejection.Recover import ru.tinkoff.tschema.finagle._ import ru.tinkoff.tschema.finagle.envRouting.TaskRouting.TaskHttp import ru.tinkoff.tschema.utils.SubString import tofu.env.Env final case class TaskRouting( request: http.Request, path: CharSequence, matched: Int ) object TaskRouting extends TaskInstanceDecl { type TaskHttp[+A] = Env[TaskRouting, A] implicit val taskRouted: RoutedPlus[TaskHttp] with ConvertService[TaskHttp] with LiftHttp[TaskHttp, Task] = new TaskRoutedConvert implicit def envRunnable(implicit recover: Recover[TaskHttp] = Recover.default[TaskHttp] ): RunHttp[TaskHttp, Task] = response => Task.deferAction(implicit sched => Task.delay(execResponse(response, _))) private[this] def execResponse( envResponse: TaskHttp[Response], request: Request )(implicit sc: Scheduler, recover: Recover[TaskHttp]): Future[Response] = { val promise = Promise[Response] val routing = TaskRouting(request, SubString(request.path), 0) val cancelable = envResponse.onErrorRecoverWith { case Rejected(rej) => recover(rej) }.run(routing).runAsync { case Right(res) => promise.setValue(res) case Left(ex) => val resp = Response(Status.InternalServerError) resp.setContentString(ex.getMessage) promise.setValue(resp) } promise.setInterruptHandler { case _ => cancelable.cancel() } promise } } private[finagle] class TaskInstanceDecl { protected class TaskRoutedConvert extends RoutedPlus[TaskHttp] with ConvertService[TaskHttp] with LiftHttp[TaskHttp, Task] { private type F[a] = TaskHttp[a] implicit private[this] val self: RoutedPlus[F] = this def matched: F[Int] = Env.fromFunc(_.matched) def withMatched[A](m: Int, fa: F[A]): F[A] = fa.local(_.copy(matched = m)) def path: F[CharSequence] = Env.fromFunc(_.path) def request: F[http.Request] = Env.fromFunc(_.request) def reject[A](rejection: Rejection): F[A] = Routed.unmatchedPath[F].flatMap(path => throwRej(rejection withPath path.toString)) def combineK[A](x: F[A], y: F[A]): F[A] = catchRej(x)(xrs => catchRej(y)(yrs => throwRej(xrs |+| yrs))) def convertService[A](svc: Service[http.Request, A]): F[A] = Env { r => Task.cancelable { cb => val fut = svc(r.request).respond { case twitter.util.Return(a) => cb.onSuccess(a) case twitter.util.Throw(ex) => cb.onError(ex) } Task(fut.raise(new InterruptedException)) } } def apply[A](fa: Task[A]): TaskHttp[A] = Env.fromTask(fa) @inline private[this] def catchRej[A](z: F[A])(f: Rejection => F[A]): F[A] = z.onErrorRecoverWith { case Rejected(xrs) => f(xrs) } @inline private[this] def throwRej[A](map: Rejection): F[A] = Env.raiseError(envRouting.Rejected(map)) } }
Example 96
Source File: ZIOConvertService.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.finagle.zioRouting package impl import com.twitter import com.twitter.finagle.Service import com.twitter.finagle.http.Request import ru.tinkoff.tschema.finagle.ConvertService import zio.{UIO, ZIO} private[finagle] class ZIOConvertService[R, E] extends ConvertService[ZIOHttp[R, E, *]] { def convertService[A](svc: Service[Request, A]): ZIOHttp[R, E, A] = ZIO.accessM { r => ZIO.effectAsyncInterrupt[ZioRouting[R], Fail[E], A] { cb => val fut = svc(r.request).respond { case twitter.util.Return(a) => cb(ZIO.succeed(a)) case twitter.util.Throw(ex) => cb(ZIO.die(ex)) } Left(UIO(fut.raise(new InterruptedException))) } } }
Example 97
Source File: ZiosConvertService.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.finagle.zioRouting package impl import com.twitter import com.twitter.finagle.Service import com.twitter.finagle.http.Request import ru.tinkoff.tschema.finagle.ConvertService import zio.{UIO, ZIO} private[finagle] class ZiosConvertService[R, E] extends ConvertService[ZIOH[R, E, *]] { def convertService[A](svc: Service[Request, A]): ZIOH[R, E, A] = ZIO.accessM { r => ZIO.effectAsyncInterrupt[R with HasRouting, Fail[E], A] { cb => val fut = svc(r.get.request).respond { case twitter.util.Return(a) => cb(ZIO.succeed(a)) case twitter.util.Throw(ex) => cb(ZIO.die(ex)) } Left(UIO(fut.raise(new InterruptedException))) } } }
Example 98
Source File: AppService.scala From peregrine with Apache License 2.0 | 5 votes |
package io.peregrine import com.twitter.finagle.Service import com.twitter.finagle.http.{Request => FinagleRequest, Response => FinagleResponse} import com.twitter.util.{Await, Future} class AppService(controllers: ControllerCollection) extends Service[FinagleRequest, FinagleResponse] { def render: ResponseBuilder = new ResponseBuilder def apply(rawRequest: FinagleRequest): Future[FinagleResponse] = { val adaptedRequest = RequestAdapter(rawRequest) try { attemptRequest(rawRequest).handle { case t: Throwable => Await.result( ErrorHandler(adaptedRequest, t, controllers) ) } } catch { case e: Exception => ErrorHandler(adaptedRequest, e, controllers) } } def attemptRequest(rawRequest: FinagleRequest): Future[FinagleResponse] = { val adaptedRequest = RequestAdapter(rawRequest) controllers.dispatch(rawRequest) match { case Some(response) => response.asInstanceOf[Future[FinagleResponse]] case None => ResponseAdapter(adaptedRequest, controllers.notFoundHandler(adaptedRequest)) } } }
Example 99
Source File: AssetsFilter.scala From peregrine with Apache License 2.0 | 5 votes |
package io.peregrine import com.twitter.finagle.http.{Request => FinagleRequest, Response => FinagleResponse} import com.twitter.finagle.{Service, SimpleFilter} import com.twitter.util._ class AssetsFilter extends SimpleFilter[FinagleRequest, FinagleResponse] with LoggingFilterHelper { val logger = PeregrineLogger.logger() def apply(req: FinagleRequest, service: Service[FinagleRequest, FinagleResponse]): Future[FinagleResponse] = { if (req.path.startsWith("/__peregrine__/")) { return if (config.debugAssets()){ applyLogging(req, request => Future(render.internal(req.path.replace("/__peregrine__", "__peregrine__"), 200).build)) } else { Future(render.internal(req.path.replace("/__peregrine__", "__peregrine__"), 200).build) } } if (req.path.startsWith(config.assetsPathPrefix())) { if (config.debugAssets()) { applyLogging(req, request => applyAssets(request)) } else { applyAssets(req) } } else { service(req) } } private[this] def applyAssets(req: FinagleRequest) = { val path = req.path.replace(config.assetsPathPrefix(), "") Try(render.static(path).build) match { case Return(resp) => Future(resp) case Throw(t) => Future(render.notFound.build) } } protected def render = new ResponseBuilder() }
Example 100
Source File: CsrfFilter.scala From peregrine with Apache License 2.0 | 5 votes |
package io.peregrine import com.twitter.finagle.http.{Request => FinagleRequest, Response => FinagleResponse} import com.twitter.finagle.{Service, SimpleFilter} import com.twitter.util.{Future,Await} import org.jboss.netty.handler.codec.http.HttpMethod class CsrfFilter extends SimpleFilter[FinagleRequest, FinagleResponse] with Sessions { def apply(req: FinagleRequest, service: Service[FinagleRequest, FinagleResponse]): Future[FinagleResponse] = { // we bypass on assets requests if (req.path.startsWith(config.assetsPathPrefix())) { service(req) } else { _applyCsrfProtection(req, service) } } private def _applyCsrfProtection(req: FinagleRequest, service: Service[FinagleRequest, FinagleResponse]) = { if (req.method == HttpMethod.GET) { for { _ <- _addCsrfToken(req) res <- service(req) } yield res } else { for { csrfToken <- _addCsrfToken(req) authToken <- Future(req.cookies.getOrElse("_authenticity_token", buildVoidCookie).value) paramToken <- Future(req.params.getOrElse("_csrf_token", "")) res <- if (csrfToken == paramToken && csrfToken == authToken) service(req) else Future(new ResponseBuilder().status(403).body("CSRF failed").build) } yield res } } private def _addCsrfToken(req: FinagleRequest) = { for { session <- session(new Request(req)) csrfToken <- session.getOrElseUpdate[String]("_csrf_token", generateToken) _ <- Future(req.response.addCookie(buildCsrfCookie(csrfToken))) } yield csrfToken } protected def generateToken = IdGenerator.hexString(32) private def buildVoidCookie = new CookieBuilder().name("_authenticity_token").value("").build() private def buildCsrfCookie(value: String) = { new CookieBuilder().name("_authenticity_token") .value(value) .httpOnly(httpOnly = true) // enables cookies for secure session if cert and key are provided .secure(!config.certificatePath().isEmpty && !config.keyPath().isEmpty) .build() } }
Example 101
Source File: LoggingFilter.scala From peregrine with Apache License 2.0 | 5 votes |
package io.peregrine import com.twitter.finagle.http.{Request => FinagleRequest, Response => FinagleResponse} import com.twitter.finagle.{Service, SimpleFilter} import com.twitter.logging.Logger import com.twitter.util._ import com.twitter.conversions.time._ class LoggingFilter extends SimpleFilter[FinagleRequest, FinagleResponse] with LoggingFilterHelper { def apply(request: FinagleRequest, service: Service[FinagleRequest, FinagleResponse]): Future[FinagleResponse] = { applyLogging(request, req => service(req)) } } trait LoggingFilterHelper extends LoggerColors { private val logger: Logger = PeregrineLogger.logger() private[peregrine] def applyLogging(request: FinagleRequest, func: FinagleRequest => Future[FinagleResponse]): Future[FinagleResponse] = { val elapsed = Stopwatch.start() func(request) map { response => val duration = elapsed().inMicroseconds/1000.0 val mColor = methodColor(response.statusCode) logger.info("[%s%s] %s%s %s\"%s\" %s%d %sin %s%.3fms%s", ANSI_RESET, request.remoteHost, ANSI_PURPLE, request.method, ANSI_BLUE, request.uri, mColor, response.statusCode, ANSI_RESET, ANSI_GREEN, duration, ANSI_RESET ) response } } private[this] def methodColor(statusCode: Int) = statusCode match { case code if code >= 200 && code < 300 => ANSI_GREEN case code if code >= 400 && code < 500 => ANSI_YELLOW case code if code >= 500 && code < 600 => ANSI_RED case _ => ANSI_RESET } }