本文整理汇总了Scala中play.api.http.MimeTypes类的典型用法代码示例。如果您正苦于以下问题:Scala MimeTypes类的具体用法?Scala MimeTypes怎么用?Scala MimeTypes使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MimeTypes类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: myPublicAddress
//设置package包名称以及导入依赖的类
package org.zalando.hutmann.spec
import org.scalatest.concurrent.PatienceConfiguration.Interval
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.{ Seconds, Span }
import org.scalatestplus.play.{ PlaySpec, PortNumber, WsScalaTestClient }
import play.api.Application
import play.api.http.{ HeaderNames, MimeTypes }
import play.api.libs.ws.{ WSClient, WSResponse }
trait PlayUnitSpec extends PlaySpec with ScalaFutures with WsScalaTestClient {
def myPublicAddress(): String
implicit val portNumber: PortNumber
def callWs(testPaymentGatewayURL: String)(implicit app: Application): WSResponse = {
implicit val wSClient = app.injector.instanceOf[WSClient]
val callbackURL = s"http://${myPublicAddress()}/callback"
whenReady(
wsUrl(testPaymentGatewayURL)
.withQueryStringParameters("callbackURL" -> callbackURL)
.withHttpHeaders(HeaderNames.ACCEPT -> MimeTypes.TEXT)
.get(),
Interval(Span(10, Seconds))
) { result =>
result
}
}
}
示例2: getToken
//设置package包名称以及导入依赖的类
package services.impl
import java.util.UUID
import com.typesafe.config.Config
import play.api.http.{ HeaderNames, MimeTypes }
import play.api.libs.ws.WSClient
import play.api.mvc.Results
import scala.concurrent.{ ExecutionContext, Future }
def getToken(code: String): Future[String] = {
val tokenResponse = ws.url("https://github.com/login/oauth/access_token").
withQueryString(
"client_id" -> githubClientId,
"client_secret" -> githubClientSecret,
"code" -> code
).
withHeaders(HeaderNames.ACCEPT -> MimeTypes.JSON).
post(Results.EmptyContent())
tokenResponse.flatMap { response =>
(response.json \ "access_token").asOpt[String].fold(Future.failed[String](
new IllegalStateException("Sod off!")
)) { accessToken =>
Future.successful(accessToken)
}
}
}
}
示例3: Http
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.agentinvitations.support
import play.api.Play.current
import play.api.http.{HeaderNames, MimeTypes}
import play.api.libs.ws.{WS, WSRequest, WSResponse}
import play.api.mvc.Results
import uk.gov.hmrc.play.http.ws.WSHttpResponse
import uk.gov.hmrc.play.http.{HeaderCarrier, HttpResponse}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
object Http {
def get(url: String)(implicit hc: HeaderCarrier): HttpResponse = perform(url) { request =>
request.get()
}
def post(url: String, body: String, headers: Seq[(String, String)] = Seq.empty)
(implicit hc: HeaderCarrier): HttpResponse = perform(url) { request =>
request.withHeaders(headers: _*).post(body)
}
def postEmpty(url: String)(implicit hc: HeaderCarrier): HttpResponse = perform(url) { request =>
import play.api.http.Writeable._
request.post(Results.EmptyContent())
}
def putEmpty(url: String)(implicit hc: HeaderCarrier): HttpResponse = perform(url) { request =>
import play.api.http.Writeable._
request.put(Results.EmptyContent())
}
def delete(url: String)(implicit hc: HeaderCarrier): HttpResponse = perform(url) { request =>
request.delete()
}
private def perform(url: String)(fun: WSRequest => Future[WSResponse])(implicit hc: HeaderCarrier): WSHttpResponse =
await(fun(WS.url(url).withHeaders(hc.headers: _*).withRequestTimeout(20000 milliseconds)).map(new WSHttpResponse(_)))
private def await[A](future: Future[A]) = Await.result(future, Duration(10, SECONDS))
}
class Resource(path: String, port: Int) {
private def url() = s"http://localhost:$port$path"
def get()(implicit hc: HeaderCarrier = HeaderCarrier()) = Http.get(url)(hc)
def postAsJson(body: String)(implicit hc: HeaderCarrier = HeaderCarrier()) =
Http.post(url, body, Seq(HeaderNames.CONTENT_TYPE -> MimeTypes.JSON))(hc)
def postEmpty()(implicit hc: HeaderCarrier = HeaderCarrier()) =
Http.postEmpty(url)(hc)
def putEmpty()(implicit hc: HeaderCarrier = HeaderCarrier()) =
Http.putEmpty(url)(hc)
}
示例4: RouterComponents
//设置package包名称以及导入依赖的类
package com.svitovyda.router
import com.svitovyda.MyComponents
import org.webjars.RequireJS
import play.api.http.MimeTypes
import play.api.mvc._
import play.api.mvc.Results._
import play.api.routing._
import play.api.routing.sird._
import com.svitovyda.configuration.ConfigurationsComponents
import com.svitovyda.counter.CounterComponents
import scala.concurrent.ExecutionContext
class RouterComponents(
counter: CounterComponents,
configurations: ConfigurationsComponents
) {
implicit val context: ExecutionContext = MyComponents.actorSystem.dispatcher
lazy val router: Router = Router.from {
case GET(p"/setup.js") => Action {
Ok(RequireJS.getSetupJavaScript("/webjars/")).as(MimeTypes.JAVASCRIPT)
}
case GET(p"/assets/$file*") => controllers.Assets.at(path = "/public", file)
case GET(p"/webjars/$file*") => controllers.WebJarAssets.at(file)
case GET(p"/") => Action { Found("/assets/index.html") }
case GET(p"/serverInfo") => configurations.controller.serverInfo
case GET(p"/hello/$to") => Action.async {
counter.controller.add().map { c => Results.Ok(s"Hello $to, you are visitor #$c today") }
}
case GET(p"/counter") => counter.controller.get
case GET(p"/some") => configurations.controller.someBusiness
}
}
示例5: Home
//设置package包名称以及导入依赖的类
package controllers
import play.api.http.{MimeTypes, Writeable}
import play.api.mvc._
import scalatags.Text.all._
class Home extends Controller {
val msg = "Hello"
def indexTwirl = okAction(views.html.index(msg))
def indexTags = okAction {
TagHtml(
html(lang := "en")(
body(
h1(msg),
jsAssetAt("frontend-fastopt.js"),
jsAssetAt("frontend-launcher.js")
)
)
)
}
def jsAssetAt(file: String) = jsAsset(routes.Assets.at(file))
def jsAsset(file: Call) = script(src := file.toString, `type` := MimeTypes.JAVASCRIPT)
def okAction[C: Writeable](c: C) = Action(Ok(c))
}
示例6: Application
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import akka.stream.scaladsl.Flow
import akka.util.ByteString
import models.{Project, ProjectRepo}
import play.api.http.HttpEntity.Streamed
import play.api.http.MimeTypes
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.{JsSuccess, Json}
import play.api.mvc.WebSocket.MessageFlowTransformer
import play.api.mvc._
import scala.concurrent.duration._
class Application @Inject()(projectRepo: ProjectRepo) extends Controller {
implicit val mt: MessageFlowTransformer[Project, String] = {
MessageFlowTransformer.stringMessageFlowTransformer.map { s =>
Json.fromJson[Project](Json.parse(s)) match {
case JsSuccess(project, _) => project
}
}
}
def socket = WebSocket.accept[Project, String] { request =>
Flow[Project]
.groupedWithin(10, 10 millis)
.map(_.toList)
.mapAsyncUnordered(parallelism = 4)(projectRepo.insert)
.map(_.n.toString)
}
def createProject(name: String) = Action.async {
projectRepo.create(name)
.map(id => Ok(s"project $id created"))
}
def listProjects = Action {
val projects = projectRepo.all
.map(p => Json.toJson[List[Project]](p))
.map(js => ByteString(js.toString()))
Ok.sendEntity(Streamed(projects, None, Some(MimeTypes.JSON)))
}
def projects(name: String) = Action.async {
for {
Some(project) <- projectRepo.findByName(name)
} yield Ok(Json.toJson(project))
}
}
示例7: ItemsSpec
//设置package包名称以及导入依赖的类
package controllers
import play.api.http.MimeTypes
import play.api.libs.json.Json
import play.api.test.{FakeRequest, WithApplication, PlaySpecification}
class ItemsSpec extends PlaySpecification {
"Items controller" should {
"list items" in new WithApplication {
route(FakeRequest(controllers.routes.Items.list()).withHeaders(ACCEPT -> MimeTypes.JSON)) match {
case Some(response) => status(response) must equalTo(OK)
contentAsJson(response) must equalTo(Json.arr())
case None => failure
}
}
}
}
示例8: sendFile
//设置package包名称以及导入依赖的类
package services
import java.io.File
import java.nio.file.{Files, Path}
import akka.stream.scaladsl.FileIO
import play.api.http.{HeaderNames, HttpEntity, HttpProtocol, MimeTypes}
import play.api.mvc.{Request, ResponseHeader, Result, Results}
trait FileUploadingService {
def sendFile(name: String, filePath: Path)(implicit request: Request[_]): Result = {
val file = new File(filePath.toString)
if (file.exists()) {
val source = FileIO.fromPath(file.toPath)
val contentType = Option(Files.probeContentType(filePath)).getOrElse(MimeTypes.BINARY)
val headers = Seq(
HeaderNames.CONTENT_DISPOSITION -> s"attachment; filename=$name",
HeaderNames.CONTENT_TYPE -> contentType
)
request.version match {
case HttpProtocol.HTTP_1_0 =>
val size = file.length()
val httpEntity = HttpEntity.Streamed(source, Some(size), Some(contentType))
Result(
header = ResponseHeader(200, Map(HeaderNames.CONTENT_LENGTH -> size.toString) ++ headers.toMap),
body = httpEntity
)
case HttpProtocol.HTTP_1_1 =>
Results.Ok.chunked(source).withHeaders(headers: _*)
}
} else {
Results.NotFound
}
}
}
示例9: ExportImportResource
//设置package包名称以及导入依赖的类
package cjp.catalogue.resource
import cjp.catalogue.model.PersistedCatalogueProduct
import cjp.catalogue.service._
import cjp.catalogue.utils.Logging
import org.json4s.FieldSerializer
import org.json4s.FieldSerializer.ignore
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.write
import play.api.http.MimeTypes
import play.api.mvc.{Action, Controller}
class ExportImportResource(exportImportService: ExportImportService, catalogueImportValidator: CatalogueImportValidator) extends Controller with Logging {
val productSerializer = FieldSerializer[PersistedCatalogueProduct](
ignore("_id") orElse ignore("name") orElse ignore("version") orElse ignore("created") orElse ignore("lastModified")
)
implicit val formats = CjpFormats.formats + productSerializer
def export = Action {
Ok(write(exportImportService.export)).as(MimeTypes.JSON)
}
def importCatalogue = Action(parse.tolerantText(parse.UNLIMITED)) {
implicit request =>
try {
val catalogueExport: CatalogueData = Serialization.read[CatalogueData](request.body)
val importValidation = catalogueImportValidator.validate(catalogueExport)
if (importValidation.isValid) {
exportImportService.importCatalogue(catalogueExport)
NoContent
} else {
BadRequest(write(importValidation))
}
} catch {
case e => {
error("error importing catalogue", e)
InternalServerError(e.getMessage)
}
}
}
}
示例10: ProductResource
//设置package包名称以及导入依赖的类
package cjp.catalogue.resource
import cjp.catalogue.service.{AttributeService, ProductDto, ProductManagementService, ProductNotFoundException}
import play.api.http.MimeTypes
import play.api.mvc.{Action, Controller}
import org.joda.time.DateTime
import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.json4s.native.Serialization._
class ProductResource(productService: ProductManagementService, attributeService: AttributeService) extends Controller {
implicit val formats = CjpFormats.formats
def getLatest(name: String) = Action {
getVersion(productService.getCurrent(name))
}
def getDraft(name: String) = Action {
getVersion(productService.getDraft(name))
}
// TODO - respond with 400 if the effectiveAt does not parse as DateTime
def getEffectiveAt(name: String, effectiveAt: String) = Action {
getVersion(productService.getEffectiveAt(name, DateTime.parse(effectiveAt)))
}
private def getVersion(productOption: => Option[ProductDto]) =
productOption.fold(NotFound(""))(p =>
Ok(write(p))
.withHeaders(ACCESS_CONTROL_ALLOW_ORIGIN -> "*")
.as(MimeTypes.JSON))
}
示例11: EffectiveDateResource
//设置package包名称以及导入依赖的类
package cjp.catalogue.resource
import cjp.catalogue.repository.EffectiveDateRepository
import org.joda.time.DateTime
import org.json4s.native.Serialization._
import play.api.http.MimeTypes
import play.api.libs.json._
import play.api.mvc.{Action, AnyContent, Controller, Request}
class EffectiveDateResource(effectiveDateRepo: EffectiveDateRepository, enableTimemachine: Boolean) extends Controller {
implicit val formats = CjpFormats.formats
def getEffectiveDate = Action {
Ok(Json.toJson(EffectiveDate(DateTime.now))(EffectiveDate.effectiveDateWrites))
.withHeaders(ACCESS_CONTROL_ALLOW_ORIGIN -> "*")
.as(MimeTypes.JSON)
}
def setEffectiveDate = Action { implicit request =>
val date: String = getEffectiveDate(request)
val dateTime = DateTime.parse(date)
if (enableTimemachine) {
effectiveDateRepo.set(dateTime)
NoContent
.withHeaders(ACCESS_CONTROL_ALLOW_ORIGIN -> "*")
} else Forbidden
.withHeaders(ACCESS_CONTROL_ALLOW_ORIGIN -> "*")
}
def resetEffectiveDate = Action {
if (enableTimemachine) {
effectiveDateRepo.reset
NoContent
.withHeaders(ACCESS_CONTROL_ALLOW_ORIGIN -> "*")
} else Forbidden
.withHeaders(ACCESS_CONTROL_ALLOW_ORIGIN -> "*")
}
private def getEffectiveDate(request: Request[AnyContent]): String = {
val json: Option[JsValue] = request.body.asJson
json map {
case (value: JsValue) => (value \ "effectiveDate").as[String]
} getOrElse (throw new scala.IllegalArgumentException(s"could not parse request with body ${request.body.asText}"))
}
}
object EffectiveDate {
implicit val effectiveDateWrites = new Writes[EffectiveDate] {
def writes(date: EffectiveDate) = Json.obj("effectiveDate" -> s"${date.effectiveDate.toString()}")
}
implicit val effectiveDateTimeReads: Reads[DateTime] = (JsPath \ "effectiveDate").read[String].map(DateTime.parse)
}
case class EffectiveDate(effectiveDate:DateTime)
示例12: TnaService
//设置package包名称以及导入依赖的类
package services
import javax.inject.{Inject, Singleton}
import models._
import play.api.http.{HeaderNames, MimeTypes}
import play.api.libs.json.Json
import play.api.libs.ws.WSClient
import scala.concurrent.{ExecutionContext, Future}
@Singleton
case class TnaService @Inject()(ws: WSClient)(implicit executionContext: ExecutionContext) {
private val BASE = "http://discovery.nationalarchives.gov.uk/DiscoveryWebAPI"
def informationAsset(id: String): Future[InformationAsset] =
ws.url(s"$BASE/InformationAssets/$id")
.withHeaders(HeaderNames.ACCEPT -> MimeTypes.JSON)
.get().map(_.json.as[InformationAsset])
def children(id: String, page: Int = 1): Future[Seq[InformationAsset]] =
ws.url(s"$BASE/InformationAssets/$id/children/page/$page")
.withHeaders(HeaderNames.ACCEPT -> MimeTypes.JSON)
.get().map(_.json.as[Seq[InformationAsset]])
def records(query: String, page: Int): Future[Seq[Record]] =
ws.url(s"$BASE/searchrecords/page/$page/query=$query")
.withHeaders(HeaderNames.ACCEPT -> MimeTypes.JSON)
.get()
.map(_.json.as[SearchResult].records)
def fileAuthorities(query: String, page: Int): Future[Seq[FileAuthority]] =
ws.url(s"$BASE/searchfileauthority/page/$page/query=$query")
.withHeaders(HeaderNames.ACCEPT -> MimeTypes.JSON)
.get()
.map(_.json.as[SearchResult].fileAuthorities)
def archives(query: String, page: Int): Future[Seq[Archive]] =
ws.url(s"$BASE/searcharchives/page/$page/query=$query")
.withHeaders(HeaderNames.ACCEPT -> MimeTypes.JSON)
.get()
.map(_.json.as[SearchResult].archives)
}
示例13: 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)
)
}
}
示例14: AdminEndpointsTest
//设置package包名称以及导入依赖的类
package uk.co.telegraph.utils.server.routes
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.util.Timeout
import com.typesafe.config.{Config, ConfigFactory}
import org.scalatest._
import play.api.Configuration
import play.api.http.{MimeTypes, Status}
import play.api.test.FakeRequest
import play.api.test.Helpers.{GET, await, contentAsString, stubControllerComponents}
import uk.co.telegraph.utils.server.routes.AdminEndpointsTest._
import scala.concurrent.duration._
import scala.language.postfixOps
class AdminEndpointsTest
extends FreeSpec
with Matchers
with BeforeAndAfter
with BeforeAndAfterAll
{
val endpoint = new AdminEndpoints(Configuration(ConfigTest), stubControllerComponents())
implicit val TimeoutTest:Timeout = 3 seconds
"Given the admin endpoint," - {
"I should be able to get a JSON version of my config" in {
val request = FakeRequest(GET, "/admin")
val response = endpoint.getConfig.apply(request)
val content = contentAsString(response)
val result = await(response)
result.body.contentType shouldBe Some(MimeTypes.JSON)
result.header.status shouldBe Status.OK
content shouldBe """{"app":{"param1":"value1","param2":["value21","value22"],"param3":"30 seconds"}}"""
}
}
}
object AdminEndpointsTest{
val ConfigTest: Config = ConfigFactory.parseString(
"""
|app {
| param1: "value1"
| param2: [
| "value21"
| "value22"
| ]
| param3: 30 seconds
|}
""".stripMargin)
implicit val ActorSystemTest = ActorSystem("sample-system", ConfigTest)
implicit val MaterializerTest = ActorMaterializer()
}
示例15: ErrorHandler
//设置package包名称以及导入依赖的类
package au.com.agiledigital.rest.security
import javax.inject._
import au.com.agiledigital.rest.controllers.transport.{ MessageLevel, Message, JsonApiResponse }
import play.api._
import play.api.http.{ Writeable, DefaultHttpErrorHandler, MimeTypes }
import play.api.libs.json.{ JsValue, Json }
import play.api.mvc._
import play.api.routing.Router
import scala.concurrent.{ Future, ExecutionContext }
class ErrorHandler @Inject() (
env: Environment,
config: Configuration,
sourceMapper: OptionalSourceMapper,
router: Provider[Router]
)(implicit val ec: ExecutionContext) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {
override def onClientError(request: RequestHeader, statusCode: Int, message: String): Future[Result] = {
if (isJsonRequest(request)) {
super.onClientError(request, statusCode, message).map { result =>
val writeable: Writeable[JsValue] = implicitly[Writeable[JsValue]]
Result(result.header, writeable.toEntity(Json.toJson(JsonApiResponse[String](None, Message(message, MessageLevel.Error)))))
}
}
else {
super.onClientError(request, statusCode, message)
}
}
override protected def onDevServerError(request: RequestHeader, exception: UsefulException): Future[Result] = {
if (isJsonRequest(request)) {
Future.successful(
JsonApiResponse.internalServerErrorResponse(s"A server error occurred - [$exception].", exception)
)
}
else {
super.onDevServerError(request, exception)
}
}
override protected def onProdServerError(request: RequestHeader, exception: UsefulException) = {
if (isJsonRequest(request)) {
Future.successful(
JsonApiResponse.internalServerErrorResponse(s"A server error occurred [${exception.id}].")
)
}
else {
super.onProdServerError(request, exception)
}
}
private def isJsonRequest(request: RequestHeader): Boolean = request.accepts(MimeTypes.JSON)
}