play.api.http.ContentTypes Scala Examples

The following examples show how to use play.api.http.ContentTypes. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: Components.scala    From gbf-raidfinder   with MIT License 6 votes vote down vote up
package walfie.gbf.raidfinder.server

import akka.actor.ActorSystem
import akka.stream.Materializer
import com.trueaccord.scalapb.json.JsonFormat
import monix.execution.Scheduler
import play.api.BuiltInComponents
import play.api.http.{ContentTypes, DefaultHttpErrorHandler}
import play.api.libs.json.Json
import play.api.Mode.Mode
import play.api.mvc._
import play.api.routing.Router
import play.api.routing.sird._
import play.core.server._
import play.filters.cors.{CORSConfig, CORSFilter}
import play.filters.gzip.GzipFilterComponents
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.Future
import walfie.gbf.raidfinder.protocol.{RaidBossesResponse, BinaryProtobuf}
import walfie.gbf.raidfinder.RaidFinder
import walfie.gbf.raidfinder.server.controller._
import walfie.gbf.raidfinder.server.syntax.ProtocolConverters.RaidBossDomainOps

class Components(
  raidFinder:                 RaidFinder[BinaryProtobuf],
  translator:                 BossNameTranslator,
  port:                       Int,
  mode:                       Mode,
  websocketKeepAliveInterval: FiniteDuration,
  metricsCollector:           MetricsCollector
) extends NettyServerComponents
  with BuiltInComponents with GzipFilterComponents with Controller {

  override lazy val serverConfig = ServerConfig(port = Some(port), mode = mode)

  private val corsFilter = new CORSFilter(corsConfig = CORSConfig().withAnyOriginAllowed)
  override lazy val httpFilters = List(gzipFilter, corsFilter)

  lazy val websocketController = new WebsocketController(
    raidFinder, translator, websocketKeepAliveInterval, metricsCollector
  )(actorSystem, materializer, Scheduler.Implicits.global)

  // The charset isn't necessary, but without it, Chrome displays Japanese incorrectly
  // if you try to view the JSON directly.
  // https://bugs.chromium.org/p/chromium/issues/detail?id=438464
  private val ContentTypeJsonWithUtf8 = "application/json; charset=utf-8"

  lazy val router = Router.from {
    case GET(p"/") =>
      controllers.Assets.at(path = "/public", "index.html")

    case GET(p"/api/bosses.json" ? q_s"name=$names") =>
      val bosses = if (names.nonEmpty) {
        val knownBossesMap = raidFinder.getKnownBosses
        names.collect(knownBossesMap)
      } else raidFinder.getKnownBosses.values

      val responseProtobuf = RaidBossesResponse(
        raidBosses = bosses.map(_.toProtocol(translator)).toSeq
      )
      val responseJson = JsonFormat.toJsonString(responseProtobuf)
      Action(Ok(responseJson).as(ContentTypeJsonWithUtf8))

    case GET(p"/api/metrics.json") =>
      val activeUsers = metricsCollector.getActiveWebSocketCount()
      val json = Json.obj("activeUsers" -> activeUsers)
      Action(Ok(json))

    case GET(p"/ws/raids" ? q_o"keepAlive=${ bool(keepAlive) }") =>
      websocketController.raids(keepAlive = keepAlive.getOrElse(false))

    case GET(p"/$file*") =>
      controllers.Assets.at(path = "/public", file = file)
  }

  override lazy val httpErrorHandler = new ErrorHandler

  override def serverStopHook = () => Future.successful {
    actorSystem.terminate()
  }
} 
Example 2
Source File: HealthControllerSpec.scala    From smui   with Apache License 2.0 5 votes vote down vote up
package controllers

import org.scalatest.mockito.MockitoSugar
import org.scalatestplus.play._
import play.api.http.ContentTypes
import play.api.mvc.Result
import play.api.test.Helpers._
import play.api.test.{FakeRequest, Helpers}

import scala.concurrent.Future


class HealthControllerSpec extends PlaySpec with MockitoSugar {

  "The HealthController" must {
    "provide an health status json" in {
      val stubControllerComponents = Helpers.stubControllerComponents()
      val controller = new HealthController(stubControllerComponents)
      val result: Future[Result] = controller.health.apply(FakeRequest())
      val bodyText: String = contentAsString(result)
      contentType(result) mustBe Some(ContentTypes.JSON)
      (contentAsJson(result) \ "name").asOpt[String] mustBe Some("search-management-ui")
    }
  }
} 
Example 3
Source File: JsonEntitiesFromCodecs.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package endpoints4s.play.client

import play.api.http.ContentTypes
import play.api.libs.ws.{BodyWritable, InMemoryBody}


trait JsonEntitiesFromCodecs
    extends EndpointsWithCustomErrors
    with endpoints4s.algebra.JsonEntitiesFromCodecs {

  def jsonRequest[A](implicit codec: JsonCodec[A]): RequestEntity[A] = { (a, wsRequest) =>
    val playCodec: play.api.mvc.Codec = implicitly[play.api.mvc.Codec]
    val writable = BodyWritable(
      (s: String) => InMemoryBody(playCodec.encode(s)),
      ContentTypes.JSON
    )
    wsRequest.withBody(stringCodec(codec).encode(a))(writable)
  }

  def jsonResponse[A](implicit codec: JsonCodec[A]): ResponseEntity[A] =
    wsResp =>
      stringCodec(codec)
        .decode(wsResp.body)
        .fold(Right(_), errors => Left(new Exception(errors.mkString(". "))))

} 
Example 4
Source File: ChunkedEntities.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package endpoints4s.play.server

import akka.stream.scaladsl.Source
import akka.util.ByteString
import endpoints4s.algebra
import play.api.http.{ContentTypes, HttpChunk, HttpEntity}
import play.api.libs.streams.Accumulator
import play.api.mvc.BodyParser


trait ChunkedJsonEntities
    extends ChunkedEntities
    with algebra.ChunkedJsonEntities
    with JsonEntitiesFromCodecs {

  def jsonChunksRequest[A](implicit
      codec: JsonCodec[A]
  ): RequestEntity[Chunks[A]] = {
    val decoder = stringCodec(codec)
    chunkedRequestEntity { byteString =>
      val string = byteString.utf8String
      decoder
        .decode(string)
        .toEither
        .left
        .map(errors => new Throwable(errors.mkString(". ")))
    }
  }

  def jsonChunksResponse[A](implicit
      codec: JsonCodec[A]
  ): ResponseEntity[Chunks[A]] = {
    val encoder = stringCodec(codec)
    chunkedResponseEntity(ContentTypes.JSON, a => ByteString(encoder.encode(a)))
  }

} 
Example 5
Source File: BuiltInErrors.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package endpoints4s.play.server

import endpoints4s.{Invalid, algebra}
import play.api.http.{ContentTypes, Writeable}


trait BuiltInErrors extends algebra.BuiltInErrors {
  this: EndpointsWithCustomErrors =>

  def clientErrorsResponseEntity: ResponseEntity[Invalid] =
    responseEntityFromWriteable({
      val playCodec = implicitly[play.api.mvc.Codec]
      Writeable(
        (invalid: Invalid) =>
          playCodec.encode(
            endpoints4s.ujson.codecs.invalidCodec.encode(invalid)
          ),
        Some(ContentTypes.JSON)
      )
    })

  def serverErrorResponseEntity: ResponseEntity[Throwable] =
    throwable => clientErrorsResponseEntity(Invalid(throwable.getMessage))

} 
Example 6
Source File: JsonEntities.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package endpoints4s.play.server

import akka.util.ByteString
import endpoints4s.{Codec, Decoder, Encoder, Invalid, algebra}
import play.api.mvc.RequestHeader
import play.api.http.{ContentTypes, Writeable}


trait JsonEntitiesFromEncodersAndDecoders
    extends algebra.JsonEntities
    with EndpointsWithCustomErrors {

  type JsonResponse[A] = Encoder[A, String]
  type JsonRequest[A] = Decoder[String, A]

  def jsonRequest[A](implicit decoder: JsonRequest[A]): RequestEntity[A] =
    JsonEntities.decodeRequest(this)(decoder)

  def jsonResponse[A](implicit encoder: JsonResponse[A]): ResponseEntity[A] =
    responseEntityFromWriteable(JsonEntities.encodeResponse(encoder))

}

private object JsonEntities {

  def decodeRequest[A](
      endpoints: EndpointsWithCustomErrors
  )(decoder: Decoder[String, A]): endpoints.RequestEntity[A] =
    (request: RequestHeader) => {
      if (request.contentType.exists(_.equalsIgnoreCase("application/json"))) {
        val decodeJson = (bs: ByteString) =>
          decoder
            .decode(bs.utf8String)
            .toEither
            .left
            .map(errs => endpoints.handleClientErrors(Invalid(errs)))

        val bodyParser =
          endpoints.playComponents.playBodyParsers.byteString
            .validate(decodeJson)(endpoints.playComponents.executionContext)
        Some(bodyParser)
      } else {
        None
      }
    }

  def encodeResponse[A](encoder: Encoder[A, String]): Writeable[A] =
    Writeable(a => ByteString(encoder.encode(a)), Some(ContentTypes.JSON))

} 
Example 7
Source File: package.scala    From OAuth2-mock-play   with MIT License 5 votes vote down vote up
import play.api.http.{ContentTypeOf, ContentTypes, Writeable}
import play.api.mvc.Codec

package object controllers {
  // Allows us to automatically render a Result of type [[scalatags.Text.Frag]]

  implicit def scalaTagsContentType(
      implicit codec: Codec): ContentTypeOf[scalatags.Text.Frag] = {
    ContentTypeOf[scalatags.Text.Frag](Some(ContentTypes.HTML))
  }

  implicit def scalaTagsWritable(
      implicit codec: Codec): Writeable[scalatags.Text.Frag] = {
    Writeable(frag => codec.encode(frag.render))
  }
} 
Example 8
Source File: BaseApi.scala    From asura   with MIT License 5 votes vote down vote up
package asura.play.api

import akka.util.ByteString
import asura.common.model.ApiRes
import asura.common.util.JsonUtils
import org.pac4j.core.profile.{CommonProfile, ProfileManager}
import org.pac4j.jwt.credentials.authenticator.JwtAuthenticator
import org.pac4j.play.PlayWebContext
import org.pac4j.play.scala.Security
import play.api.http.{ContentTypes, HttpEntity}
import play.api.mvc._

import scala.collection.JavaConverters.asScalaBuffer
import scala.concurrent.{ExecutionContext, Future}

trait BaseApi extends Security[CommonProfile] {

  import BaseApi._

  def getWsProfile(auth: JwtAuthenticator)(implicit request: RequestHeader): CommonProfile = {
    val token = request.getQueryString("token")
    if (token.nonEmpty) {
      auth.validateToken(token.get)
    } else {
      null
    }
  }

  def getProfiles()(implicit request: RequestHeader): List[CommonProfile] = {
    val webContext = new PlayWebContext(request, playSessionStore)
    val profileManager = new ProfileManager[CommonProfile](webContext)
    val profiles = profileManager.getAll(true)
    asScalaBuffer(profiles).toList
  }

  def getProfileId()(implicit request: RequestHeader): String = {
    getProfiles().head.getId
  }

  implicit class JsonToClass(req: Request[ByteString]) {
    def bodyAs[T <: AnyRef](c: Class[T]): T = JsonUtils.parse[T](req.body.decodeString("UTF-8"), c)
  }

  
  val responseNoCacheHeaders = Seq(
    ("Cache-Control", "no-cache"), ("X-Accel-Buffering", "no")
  )
  val DEFAULT_SOURCE_BUFFER_SIZE = 100
} 
Example 9
Source File: CiApi.scala    From asura   with MIT License 5 votes vote down vote up
package asura.app.api.ci

import akka.actor.ActorSystem
import akka.stream.scaladsl.Source
import akka.stream.{Materializer, OverflowStrategy}
import asura.common.actor.SenderMessage
import asura.core.ci.{CiManager, CiTriggerEventMessage}
import asura.core.job.actor.JobCiActor
import asura.play.api.BaseApi
import javax.inject.{Inject, Singleton}
import org.pac4j.play.scala.SecurityComponents
import play.api.http.ContentTypes
import play.api.libs.EventSource
import play.api.libs.streams.ActorFlow
import play.api.mvc.{Codec, WebSocket}

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class CiApi @Inject()(
                       implicit val system: ActorSystem,
                       implicit val exec: ExecutionContext,
                       implicit val mat: Materializer,
                       val controllerComponents: SecurityComponents
                     ) extends BaseApi {

  implicit val codec = Codec.utf_8

  def home() = Action {
    Ok("CI")
  }

  def trigger() = Action(parse.byteString).async { implicit req =>
    val msg = req.bodyAs(classOf[CiTriggerEventMessage])
    CiManager.eventSource(msg)
    Future.successful(Ok("OK"))
  }

  def jobWS(id: String) = WebSocket.accept[String, String] { implicit req =>
    ActorFlow.actorRef(out => JobCiActor.props(id, out))
  }

  def jobSSE(id: String) = Action {
    val ciActor = system.actorOf(JobCiActor.props(id))
    val source = Source.actorRef[String](BaseApi.DEFAULT_SOURCE_BUFFER_SIZE, OverflowStrategy.dropHead)
      .mapMaterializedValue(ref => ciActor ! SenderMessage(ref))
    Ok.chunked(source via EventSource.flow)
      .as(ContentTypes.EVENT_STREAM)
      .withHeaders(BaseApi.responseNoCacheHeaders: _*)
  }
} 
Example 10
Source File: ApplicationController.scala    From metronome   with Apache License 2.0 5 votes vote down vote up
package dcos.metronome
package api.v1.controllers

import dcos.metronome.api.{ErrorDetail, RestController}
import dcos.metronome.api.v1.models.{errorFormat, LeaderInfoWrites, MetronomeInfoWrites}
import mesosphere.marathon.MetricsModule
import mesosphere.marathon.core.election.ElectionService
import mesosphere.marathon.raml.MetricsConversion._
import mesosphere.marathon.raml.Raml
import play.api.http.ContentTypes
import play.api.libs.json.Json
import play.api.mvc.ControllerComponents

class ApplicationController(cc: ControllerComponents, metricsModule: MetricsModule, electionService: ElectionService)
    extends RestController(cc) {

  def ping = Action { Ok("pong") }

  def info =
    Action {
      Ok(MetronomeInfoWrites.writes(MetronomeInfoBuilder.metronomeInfo))
    }

  def leader =
    Action {
      electionService.leaderHostPort match {
        case None => NotFound(errorFormat.writes(ErrorDetail("There is no leader")))
        case Some(leader) => Ok(LeaderInfoWrites.writes(LeaderInfo(leader)))
      }
    }

  def showMetrics =
    Action {
      val metricsJsonString = metricsModule.snapshot() match {
        case Left(_) =>
          // Kamon snapshot
          throw new IllegalArgumentException(
            "Only Dropwizard format is supported, cannot render metrics from Kamon snapshot. Make sure your metrics are configured correctly."
          )
        case Right(dropwizardRegistry) => Json.stringify(Json.toJson(Raml.toRaml(dropwizardRegistry)))
      }
      Ok(metricsJsonString).as(ContentTypes.JSON)
    }
} 
Example 11
Source File: RestController.scala    From metronome   with Apache License 2.0 5 votes vote down vote up
package dcos.metronome
package api

import com.eclipsesource.schema.SchemaValidator
import com.wix.accord.{Failure, Success, Validator}
import mesosphere.marathon.api.v2.Validation
import play.api.http.{ContentTypeOf, ContentTypes, Writeable}
import play.api.libs.json._
import play.api.mvc._

class RestController(cc: ControllerComponents) extends AbstractController(cc) {

  import dcos.metronome.api.v1.models.JsErrorWrites

  implicit def jsonWritable[T <: Any](implicit w: Writes[T], codec: Codec, request: RequestHeader): Writeable[T] = {
    implicit val contentType: ContentTypeOf[T] = ContentTypeOf[T](Some(ContentTypes.JSON))
    Writeable(t => codec.encode(Json.stringify(w.writes(t))))
  }

  object validate {

    val schemaValidator = SchemaValidator()

    def json[A](implicit reader: Reads[A], schema: JsonSchema[A], validator: Validator[A]): BodyParser[A] = {
      jsonWith[A](identity)
    }

    def jsonWith[A](
        fn: A => A
    )(implicit reader: Reads[A], schema: JsonSchema[A], validator: Validator[A]): BodyParser[A] = {
      BodyParser("json reader and validator") { request =>
        import play.api.libs.iteratee.Execution.Implicits.trampoline

        def validateObject(a: A): Either[Result, A] =
          validator(a) match {
            case Success => Right(a)
            case f: Failure => Left(UnprocessableEntity(Validation.failureWrites.writes(f)))
          }

        def readObject(jsValue: JsValue): Either[Result, A] = {
          jsValue.validate(reader) match {
            case JsSuccess(value, _) => validateObject(fn(value))
            case error: JsError => Left(UnprocessableEntity(Json.toJson(error)))
          }
        }

        def schemaValidate(jsValue: JsValue): Either[Result, A] = {
          schemaValidator.validate(schema.schemaType, jsValue) match {
            case JsSuccess(value, _) => readObject(value)
            case error: JsError => Left(UnprocessableEntity(Json.toJson(error)))
          }
        }

        parse.json(request).map {
          case Left(simpleResult) => Left(simpleResult)
          case Right(jsValue) => schemaValidate(jsValue)
        }
      }
    }
  }
}