当前位置: 首页>>代码示例>>Scala>>正文


Scala ContentTypes类代码示例

本文整理汇总了Scala中play.api.http.ContentTypes的典型用法代码示例。如果您正苦于以下问题:Scala ContentTypes类的具体用法?Scala ContentTypes怎么用?Scala ContentTypes使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了ContentTypes类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: ScalaEventSourceController

//设置package包名称以及导入依赖的类
package controllers

import java.io.File

import play.Play
import java.nio.file.Paths
import javax.inject.{Inject, Singleton}

import play.api.http.ContentTypes
import play.api.libs.EventSource
import play.api.mvc._

@Singleton
class ScalaEventSourceController @Inject()(cc: ControllerComponents) extends AbstractController(cc) with ScalaTicker {

  def index() = Action {
    Ok(views.html.scalaeventsource())
  }

  def streamClock() = Action {
    Ok.chunked(stringSource via EventSource.flow).as(ContentTypes.EVENT_STREAM)
  }

  def upload = Action(parse.multipartFormData) { request =>
    request.body.file("picture").map { picture =>
      var basePath = "/app/public/upload/"

      var archivoTmp = new File(basePath)
      if(!archivoTmp.exists()) {
        basePath = Play.application().getFile("/public/upload/").getAbsolutePath() + File.separator;
      }

      val filename = picture.filename
      val contentType = picture.contentType
      picture.ref.moveTo(Paths.get(basePath + filename), replace = true)
      reiniciarSimulacion();
      Ok(views.html.scalaeventsource())
    }.getOrElse {
      Redirect(routes.ScalaEventSourceController.index).flashing(
        "error" -> "Missing file")
    }
  }

} 
开发者ID:juancamilogaviriaacosta,项目名称:proyecto-transmimetro-JuanGaviria-MauricioMontano,代码行数:45,代码来源:ScalaEventSourceController.scala

示例2: InventoryLogController

//设置package包名称以及导入依赖的类
package controllers

import java.io.File

import play.api.http.ContentTypes
import play.api.mvc.{Action, Controller}
import service.InventoryLogService
import util.JsonUtil

import scala.util.{Failure, Success, Try}

object InventoryLogController extends Controller {

  def create = Action {
    InventoryLogService.createSchema
    Ok("Schema Created")
  }

  def truncate = Action {
    InventoryLogService.truncateData
    Ok("Schema Truncated")
  }

  def upload = Action(parse.multipartFormData) { implicit request =>
    val files = request.body.files
    Try(files.map { file =>
      val tmpFile = file.ref.moveTo(new File(s"/tmp/${file.filename}"))
      InventoryLogService.populateSchema(tmpFile)
      tmpFile.delete
    }) match {
      case Success(_) => if(files.size <= 0) BadRequest("File Not uploaded!!") else Ok("File Uploaded")
      case Failure(x) => BadRequest(s"Upload Error!! ${x.getMessage}")
    }
  }

  def track = Action { request =>
    val trackRequest = request.body.asJson
    Try(trackRequest.map { json =>
      val objectId = (json \ "object_id").as[Int]
      val objectType = (json \ "object_type").as[String]
      val timestamp = (json \ "timestamp").as[Long]
      InventoryLogService.trackStatus(objectId, objectType, timestamp)
    }.getOrElse {
      BadRequest("Expecting application/json request body")
    }) match {
      case Success(x: Some[Any]) => Ok(JsonUtil.toJson(x.getOrElse(Map.empty))).as(ContentTypes.JSON)
      case Success(_) => Ok("No updates available")
      case Failure(_) => BadRequest("Expecting all input parameters")
    }
  }

  def details = Action {
    Ok(JsonUtil.toJson(InventoryLogService.trackDetails)).as(ContentTypes.JSON)
  }


} 
开发者ID:SarathChandran,项目名称:InventoryTracker,代码行数:58,代码来源:InventoryLogController.scala

示例3: TweetCometController

//设置package包名称以及导入依赖的类
package controllers

import javax.inject.Inject

import akka.stream.Materializer
import play.api.Configuration
import play.api.http.ContentTypes
import play.api.libs.Comet
import play.api.libs.json._
import play.api.mvc._
import repositories.TweetRepository
import services.{PersistenceService, TweetService}


class TweetCometController @Inject()(materializer: Materializer,
                                     config: Configuration,
                                     tweetRepository: TweetRepository,
                                     tweetService: TweetService,
                                     persistenceService: PersistenceService) extends Controller {

  private lazy val searchTerms = config.getStringSeq("tweet.tags").getOrElse(Seq(""))

  def tweetComet = Action {
    implicit val mat = materializer
    def content = tweetService
      .createSearchSource(searchTerms)
      .map { s => Option(s.getText).getOrElse("") }
      .via(persistenceService.stringPersister(tweetRepository.insert))
      .map { s => JsString(s) }
      .via(Comet.json("parent.cometMessage"))
    Ok.chunked(content).as(ContentTypes.HTML)
  }
} 
开发者ID:snackCake,项目名称:TweetStreamChallenge,代码行数:34,代码来源:TweetCometController.scala

示例4: scalaTagsContentType

//设置package包名称以及导入依赖的类
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))
  }
} 
开发者ID:zalando-incubator,项目名称:OAuth2-mock-play,代码行数:17,代码来源:package.scala

示例5: RouteService

//设置package包名称以及导入依赖的类
package services

import javax.inject.Inject

import models.{Route, Vehicle}
import play.api.libs.ws.{WSClient, WSResponse}
import play.api.http.HeaderNames
import play.api.http.ContentTypes

import scala.concurrent.{ExecutionContext, Future}

class RouteService @Inject() (ws: WSClient) {
  private val BASE_URL = "http://m.cdsvyatka.com/tratata.php"
  private val ROUTE_PARAM_NAME = "marsh"
  private val REFERER = "http://m.cdsvyatka.com/mobile_map.php"


  private def parseResponse(res: WSResponse): Seq[Vehicle] = {
    res.json.validate[Map[String, Vehicle]].fold(_ => Seq.empty, _.values.toSeq)
  }

  def routeVehicles(route: Route)(implicit ec: ExecutionContext): Future[Seq[Vehicle]] = {
    ws.url(BASE_URL)
      .withQueryString(ROUTE_PARAM_NAME -> route.id.toString)
      .withHeaders(HeaderNames.ACCEPT -> ContentTypes.JSON, HeaderNames.REFERER -> REFERER)
      .get()
      .map(parseResponse)
  }
} 
开发者ID:watchbus,项目名称:play-watchbus,代码行数:30,代码来源:RouteService.scala

示例6: HubController

//设置package包名称以及导入依赖的类
package controllers

import javax.inject.{Inject, Singleton}

import akka.stream.Materializer
import akka.stream.scaladsl.{BroadcastHub, Keep, MergeHub, Source}
import models.Message
import play.api.http.ContentTypes
import play.api.libs.EventSource
import play.api.mvc._

@Singleton
class HubController @Inject() (implicit val mat: Materializer) extends Controller {

  private[this] val (sink, source) =
    MergeHub.source[String](perProducerBufferSize = 16)
      .toMat(BroadcastHub.sink(bufferSize = 256))(Keep.both)
      .run()

  def index = Action {
    Ok(views.html.hub())
  }

  def receiveMessage = Action(BodyParsers.parse.json[Message]) { request =>
    Source.single(request.body.toString).runWith(sink)
    Ok
  }

  def sse = Action {
    Ok.chunked(source via EventSource.flow).as(ContentTypes.EVENT_STREAM)
  }

} 
开发者ID:septeni-original,项目名称:play-scala-sse-example,代码行数:34,代码来源:HubController.scala

示例7: MessengerService

//设置package包名称以及导入依赖的类
package services

import javax.inject.{ Inject, Singleton }

import models.Messages._
import models.{ Messages, User }
import play.api.Configuration
import play.api.http.ContentTypes
import play.api.libs.json.{ JsValue, Json }
import play.api.libs.ws.{ WSClient, WSResponse }
import play.api.http.HeaderNames._

import scala.concurrent.{ ExecutionContext, Future }

@Singleton
class MessengerService @Inject() (config: Configuration, ws: WSClient)(implicit executionContext: ExecutionContext) {

  def reply(f: Future[JsValue]): Future[WSResponse] = f.flatMap { json =>
    post(json).flatMap { response =>
      if (success(response)) Future(response)
      else replyWithError(json, response.json)
    }
  }

  private def replyWithError(body: JsValue, error: JsValue): Future[WSResponse] = {
    val sender = (body \ "recipient").as[User]
    val err = (error \ "error").as[models.Error]
    val errorMessage = Messages.oops(sender, err.message)
    post(Json.toJson(errorMessage))
  }

  private def post(body: JsValue): Future[WSResponse] = ws.url(config.getString("facebook.messages.url")
    .getOrElse("https://graph.facebook.com/v2.6/me/messages"))
    .withQueryString("access_token" -> config.getString("facebook.messages.token").getOrElse(""))
    .withHeaders(CONTENT_TYPE -> ContentTypes.JSON)
    .withRequestFilter(play.api.libs.ws.ahc.AhcCurlRequestLogger())
    .withRequestFilter(AhcResponseLogger(body = true))
    .post(body)

  private def success(response: WSResponse): Boolean = response.status >= 200 && response.status < 300
} 
开发者ID:marcospereira,项目名称:reddit-bot,代码行数:42,代码来源:MessengerService.scala

示例8: translateImageServiceAndDatabaseError

//设置package包名称以及导入依赖的类
package controllers

import io.circe.Encoder
import play.api.http.ContentTypes
import play.api.mvc.Result
import uk.ac.ncl.openlab.intake24.services.fooddb.images.{DatabaseErrorWrapper, ImageServiceErrorWrapper, ImageServiceOrDatabaseError}

trait ImageOrDatabaseServiceErrorHandler extends DatabaseErrorHandler with ImageServiceErrorHandler {

  def translateImageServiceAndDatabaseError[T](result: Either[ImageServiceOrDatabaseError, T]): Either[Result, T] = result match {
    case Right(result) => Right(result)
    case Left(DatabaseErrorWrapper(error)) => Left(translateDatabaseError(error))
    case Left(ImageServiceErrorWrapper(error)) => Left(translateImageServiceError(error))
  }

  def translateImageServiceAndDatabaseResult[T](result: Either[ImageServiceOrDatabaseError, T])(implicit writer: Encoder[T]) = result match {
    case Right(result) => Ok(toJsonString(result)).as(ContentTypes.JSON)
    case Left(DatabaseErrorWrapper(error)) => translateDatabaseError(error)
    case Left(ImageServiceErrorWrapper(error)) => translateImageServiceError(error)
  }
} 
开发者ID:digitalinteraction,项目名称:intake24,代码行数:22,代码来源:ImageOrDatabaseServiceErrorHandler.scala

示例9: genericErrorBody

//设置package包名称以及导入依赖的类
package controllers

import io.circe.Encoder
import io.circe.generic.auto._
import parsers.JsonUtils
import play.api.Logger
import play.api.http.ContentTypes
import play.api.mvc.{Result, Results}
import uk.ac.ncl.openlab.intake24.api.shared.ErrorDescription
import uk.ac.ncl.openlab.intake24.services.fooddb.images._

trait ImageServiceErrorHandler extends Results with JsonUtils {

  private def genericErrorBody(e: Throwable) = toJsonString(ErrorDescription(e.getClass.getSimpleName, e.getMessage))

  private def logException(e: Throwable) = Logger.error("Image service exception", e)

  def translateImageServiceError(error: ImageServiceError): Result = error match {
    case IOError(e) => {
      logException(e)
      InternalServerError(genericErrorBody(e))
    }
    case ImageProcessorError(e) => {
      logException(e)
      InternalServerError(genericErrorBody(e))
    }
    case ImageStorageError(e) => {
      logException(e)
      InternalServerError(genericErrorBody(e))
    }
    case FileTypeNotAllowed(e) => {
      logException(e)
      BadRequest(genericErrorBody(e))
    }
  }

  def translateImageServiceResult[T](result: Either[ImageServiceError, T])(implicit enc: Encoder[T]): Result = result match {
    case Right(result) => Ok(toJsonString(result)).as(ContentTypes.JSON)
    case Left(error) => translateImageServiceError(error)
  }
} 
开发者ID:digitalinteraction,项目名称:intake24,代码行数:42,代码来源:ImageServiceErrorHandler.scala

示例10: handleDatabaseError

//设置package包名称以及导入依赖的类
package controllers

import io.circe.Encoder
import org.slf4j.LoggerFactory
import play.api.http.ContentTypes
import play.api.mvc.{Result, Results}
import uk.ac.ncl.openlab.intake24.api.shared.ErrorDescription
import uk.ac.ncl.openlab.intake24.errors._
import io.circe.generic.auto._
import parsers.JsonUtils

trait DatabaseErrorHandler extends Results with JsonUtils {

  private val logger = LoggerFactory.getLogger(classOf[DatabaseErrorHandler])

  private def handleDatabaseError(e: Throwable): Result = {

    def logCause(e: Throwable): Unit =
      if (e != null) {
        logger.error("Caused by", e)
        logCause(e.getCause)
      }

    logger.error("DatabaseError", e)
    logCause(e.getCause)

    InternalServerError(toJsonString(ErrorDescription("DatabaseError", "Unexpected database error: " + e.getMessage()))).as(ContentTypes.JSON)
  }

  def translateDatabaseError(error: AnyError): Result = error match {
    case DuplicateCode(e) => BadRequest(toJsonString(ErrorDescription("DuplicateCode", e.getMessage))).as(ContentTypes.JSON)
    case VersionConflict(_) => Conflict(toJsonString(ErrorDescription("VersionConflict", "Object has been concurrently edited by someone else, try again using the new base version"))).as(ContentTypes.JSON)
    case TableNotFound(e) => NotFound(toJsonString(ErrorDescription("RecordNotFound", "Food composition table not found: " + e.getMessage))).as(ContentTypes.JSON)
    case RecordNotFound(e) => NotFound(toJsonString(ErrorDescription("RecordNotFound", "Object does not exist: " + e.getMessage))).as(ContentTypes.JSON)
    case StillReferenced(e) => BadRequest(toJsonString(ErrorDescription("StillReferenced", e.getMessage))).as(ContentTypes.JSON)
    case UndefinedLocale(_) => BadRequest(toJsonString(ErrorDescription("UndefinedLocale", "Locale is not defined, check the locale code"))).as(ContentTypes.JSON)
    case ParentRecordNotFound(e) => BadRequest(toJsonString(ErrorDescription("ParentRecordNotFound", "An object referenced by this object does not exist: " + e.getMessage))).as(ContentTypes.JSON)
    case IllegalParent(_) => BadRequest(toJsonString(ErrorDescription("IllegalParent", "The object references an illegal parent object"))).as(ContentTypes.JSON)
    case ConstraintViolation(name, _) => BadRequest(toJsonString(ErrorDescription("ConstraintViolation", s"Database constraint not met: $name")))
    case UnexpectedDatabaseError(exception) => handleDatabaseError(exception)
  }

  def translateDatabaseResult[T](result: Either[AnyError, T])(implicit enc: Encoder[T]) = result match {
    case Right(()) => Ok
    case Right(result) => Ok(toJsonString(result)).as(ContentTypes.JSON)
    case Left(error) => translateDatabaseError(error)
  }
} 
开发者ID:digitalinteraction,项目名称:intake24,代码行数:49,代码来源:DatabaseErrorHandler.scala

示例11: Intake24ErrorHandler

//设置package包名称以及导入依赖的类
package errorhandler

import javax.inject._

import io.circe.generic.auto._
import parsers.JsonUtils
import play.api._
import play.api.http.{ContentTypes, DefaultHttpErrorHandler}
import play.api.mvc.Results._
import play.api.mvc._
import play.api.routing.Router
import uk.ac.ncl.openlab.intake24.api.shared.ErrorDescription

import scala.concurrent._

@Singleton
class Intake24ErrorHandler @Inject()(
                                      env: Environment,
                                      config: Configuration,
                                      sourceMapper: OptionalSourceMapper,
                                      router: Provider[Router]
                                    ) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) with JsonUtils {

  override def onBadRequest(request: RequestHeader, message: String): Future[Result] =
    Future.successful {
      BadRequest(toJsonString(ErrorDescription("BadRequest", message))).as(ContentTypes.JSON)
    }

} 
开发者ID:digitalinteraction,项目名称:intake24,代码行数:30,代码来源:Intake24ErrorHandler.scala

示例12: GameController

//设置package包名称以及导入依赖的类
package controllers

import javax.inject._

import akka.stream.scaladsl.{Flow, Source}
import models.Game
import play.api.http.ContentTypes
import play.api.libs.EventSource.Event
import play.api.mvc._
import views.Game2String

@Singleton
class GameController @Inject()(default: Game) extends Controller {

  def boards(game: Option[Game]): Action[AnyContent] = {
    Action {
      game map { game =>
        Ok(views.html.boards(game))
      } getOrElse {
        Redirect(routes.GameController.boards(Some(default)))
      }
    }
  }

  def stream(game: Game): Action[AnyContent] = {
    Action {
      val view = Game2String(game) _ andThen (_ substring 1) andThen Event[String]
      val events = Source fromIterator (() => game.iterator) map view
      Ok chunked (events via Flow[Event]) as ContentTypes.EVENT_STREAM
    }
  }
} 
开发者ID:christian-schlichtherle,项目名称:play-scala-game-of-life,代码行数:33,代码来源:GameController.scala

示例13: Tweet

//设置package包名称以及导入依赖的类
package io.digitalstream.webfx

import java.util.concurrent.atomic.AtomicLong
import javax.inject.{Inject, Singleton}

import akka.util.ByteString
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import play.api.http.Status.OK
import play.api.http.{ContentTypes, HttpEntity}
import play.api.mvc._

import scala.concurrent.ExecutionContext

case class Tweet(id: Long, author: String, content: String)

@Singleton
class TweetService @Inject()() {
  val counter = new AtomicLong(1000000L)

  def list(): List[Tweet] = {
    List(
      Tweet(counter.getAndIncrement(), "author1", "Hello, World!")
    )
  }
}

@Singleton
class TweetApi @Inject()(tweetService: TweetService)
                        (implicit ec: ExecutionContext)
  extends Controller with JsonResults {

  def list() = Action { req =>
    JsonOk(tweetService.list())
  }
}

trait JsonResults {

  val mapper = new ObjectMapper()
    .registerModule(DefaultScalaModule)

  class JsonStatus(status: Int)
    extends Result(header = ResponseHeader(status), body = HttpEntity.NoEntity) {

    def apply[C](content: AnyRef): Result = {
      val header = ResponseHeader(status)
      val json = mapper.writeValueAsBytes(content)
      val body = HttpEntity.Strict(ByteString(json), Some(ContentTypes.JSON))
      Result(header, body)
    }
  }

  val JsonOk = new JsonStatus(OK)
} 
开发者ID:digitalstreamio,项目名称:webfx-bench,代码行数:56,代码来源:Boot.scala

示例14: HealthEndpoints

//设置package包名称以及导入依赖的类
package uk.co.telegraph.utils.server.routes

import javax.inject.Inject

import akka.actor.ActorSystem
import com.google.inject.Singleton
import io.swagger.annotations.{ApiOperation, ApiParam, ApiResponse, ApiResponses}
import org.json4s.jackson.Serialization._
import play.api.http.{ContentTypes, MimeTypes}
import play.api.mvc._
import uk.co.telegraph.utils.client.monitor.Monitor
import uk.co.telegraph.utils.server.models.HealthDto

@Singleton
class HealthEndpoints @Inject()(monitor:Monitor, cc:ControllerComponents)(implicit system:ActorSystem)
  extends AbstractController(cc)
{
  import system.dispatcher

  private lazy val endpointConfig = system.settings.config.getConfig("app")
  private lazy val appVersion = endpointConfig.getString("version")
  private lazy val appName    = endpointConfig.getString("name")

  def internalHealth: Action[AnyContent] = Action{
    Ok("""{"status":"OK"}""" ).as(MimeTypes.JSON)
  }

  @ApiOperation(value = "Indicate the health value of the service and the services that it connects to")
  @ApiResponses(Array(
    new ApiResponse (code = 200, message = "a Json object containing the healthcheck of the service"),
    new ApiResponse (code = 500, message = "a Json object containing the healthcheck of the service")))
  def externalHealth
  (
    @ApiParam(value = "Determine if we will receive cached data for the clients or it will do a new query to them", defaultValue  = "true", allowableValues = "true, false")  cached:Boolean = true
  ): Action[AnyContent] = Action.async{ _ =>
    import HealthDto.Serializer
    monitor.queryHealth(!cached)
      .map( res => Ok( write(HealthDto(
          name = appName,
          version = appVersion,
          cached = res.cached,
          clients = res.clients)
        ))
        .as(ContentTypes.JSON)
      )
  }
} 
开发者ID:telegraph,项目名称:tmg-utils,代码行数:48,代码来源:HealthEndpoints.scala

示例15: ApplicationController

//设置package包名称以及导入依赖的类
package dcos.metronome.api.v1.controllers

import java.io.StringWriter
import java.util.concurrent.TimeUnit

import com.codahale.metrics.json.MetricsModule
import com.fasterxml.jackson.databind.ObjectMapper
import dcos.metronome.api.RestController
import dcos.metronome.behavior.Metrics
import mesosphere.marathon.io.IO
import play.api.http.ContentTypes
import play.api.mvc.Action

class ApplicationController(metrics: Metrics) extends RestController {

  private[this] val metricsMapper = new ObjectMapper().registerModule(
    new MetricsModule(TimeUnit.SECONDS, TimeUnit.SECONDS, false)
  )

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

  def showMetrics = Action {
    val metricsJsonString = IO.using(new StringWriter()) { writer =>
      metricsMapper.writer().writeValue(writer, metrics.metricRegistry)
      writer.getBuffer.toString
    }
    Ok(metricsJsonString).as(ContentTypes.JSON)
  }
} 
开发者ID:dcos,项目名称:metronome,代码行数:30,代码来源:ApplicationController.scala


注:本文中的play.api.http.ContentTypes类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。