本文整理汇总了Scala中play.api.http.Writeable类的典型用法代码示例。如果您正苦于以下问题:Scala Writeable类的具体用法?Scala Writeable怎么用?Scala Writeable使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Writeable类的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: 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))
}
}
示例2: MultipartFormDataWritable
//设置package包名称以及导入依赖的类
package helpers
import java.nio.file.{Files, Paths}
import play.api.http.{HeaderNames, Writeable}
import play.api.libs.Files.TemporaryFile
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc.{AnyContentAsMultipartFormData, Codec, MultipartFormData}
//Check -> http://tech.fongmun.com/post/125479939452/test-multipartformdata-in-play
object MultipartFormDataWritable {
val boundary = "--------ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
def formatDataParts(data: Map[String, Seq[String]]) = {
val dataParts = data.flatMap {
case (key, values) =>
values.map { value =>
val name = s""""$key""""
s"--$boundary\r\n${HeaderNames.CONTENT_DISPOSITION}: form-data; name=$name\r\n\r\n$value\r\n"
}
}.mkString("")
Codec.utf_8.encode(dataParts)
}
def filePartHeader(file: FilePart[TemporaryFile]) = {
val name = s""""${file.key}""""
val filename = s""""${file.filename}""""
val contentType = file.contentType.map { ct =>
s"${HeaderNames.CONTENT_TYPE}: $ct\r\n"
}.getOrElse("")
Codec.utf_8.encode(s"--$boundary\r\n${HeaderNames.CONTENT_DISPOSITION}: form-data; name=$name; filename=$filename\r\n$contentType\r\n")
}
val singleton = Writeable[MultipartFormData[TemporaryFile]](
transform = { form: MultipartFormData[TemporaryFile] =>
formatDataParts(form.dataParts) ++
form.files.flatMap { file =>
val fileBytes = Files.readAllBytes(Paths.get(file.ref.file.getAbsolutePath))
filePartHeader(file) ++ fileBytes ++ Codec.utf_8.encode("\r\n")
} ++
Codec.utf_8.encode(s"--$boundary--")
},
contentType = Some(s"multipart/form-data; boundary=$boundary")
)
implicit val anyContentAsMultipartFormWritable: Writeable[AnyContentAsMultipartFormData] = {
MultipartFormDataWritable.singleton.map(_.mdf)
}
}
示例3: MultipartFormDataWritable
//设置package包名称以及导入依赖的类
package de.zalando.play.controllers
import java.nio.file.{ Files, Paths }
import akka.util.ByteString
import play.api.http.{ HeaderNames, Writeable }
import play.api.libs.Files.TemporaryFile
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc.{ Codec, MultipartFormData }
object MultipartFormDataWritable {
val boundary = "--------ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
def formatDataParts(data: Map[String, Seq[String]]): ByteString = {
val dataParts = data.flatMap {
case (key, values) =>
values.map { value =>
val name = s""""$key""""
s"--$boundary\r\n${HeaderNames.CONTENT_DISPOSITION}: form-data; name=$name\r\n\r\n$value\r\n"
}
}.mkString("")
val bytes: ByteString = Codec.utf_8.encode(dataParts)
bytes
}
def filePartHeader(file: FilePart[TemporaryFile]): ByteString = {
val name = s""""${file.key}""""
val filename = s""""${file.filename}""""
val contentType = file.contentType.map { ct =>
s"${HeaderNames.CONTENT_TYPE}: $ct\r\n"
}.getOrElse("")
Codec.utf_8.encode(s"--$boundary\r\n${HeaderNames.CONTENT_DISPOSITION}: form-data; name=$name; filename=$filename\r\n$contentType\r\n")
}
val singleton = Writeable[MultipartFormData[TemporaryFile]](
transform = { form: MultipartFormData[TemporaryFile] =>
formatDataParts(form.dataParts) ++
form.files.flatMap { file =>
val fileBytes = Files.readAllBytes(Paths.get(file.ref.file.getAbsolutePath))
filePartHeader(file) ++ fileBytes ++ Codec.utf_8.encode("\r\n")
} ++
Codec.utf_8.encode(s"--$boundary--")
},
contentType = Some(s"multipart/form-data; boundary=$boundary")
)
}
示例4: 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))
}
示例5: ShortestPathControllerSpec
//设置package包名称以及导入依赖的类
package shortestPath
import scala.annotation.implicitNotFound
import scala.concurrent.Future
import play.api.http.Writeable
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.mvc.AnyContentAsEmpty
import play.api.mvc.Headers
import play.api.mvc.Result
import play.api.mvc.Results
import play.api.test.FakeRequest
import play.api.test.PlaySpecification
class ShortestPathControllerSpec extends PlaySpecification with Results {
"End point is working#index" should {
lazy val app = new GuiceApplicationBuilder().build
val basicHeaders = Headers(
"type" -> "application/json")
def routeGET(uri: String) = getRoute(GET, uri, AnyContentAsEmpty)
def getRoute[A](method: String, uri: String, body: A)(implicit w: Writeable[A]) = route(app, FakeRequest(method, uri, basicHeaders, body)).get
def codeMustMatch(code: Int, result: Future[Result]) = {
status(result) must equalTo(code)
}
s"End point is available" in {
val source = "source_user"
val destination = "destination_user"
val result = routeGET("/shortestPath/source_user/destination_user")
codeMustMatch(200, result)
contentAsString(result) must contain("hops")
}
}
}
示例6: TestComponents
//设置package包名称以及导入依赖的类
package tests
import com.malliina.play.http.{PlayUtils, Proxies}
import play.api.ApplicationLoader.Context
import play.api.http.{HeaderNames, Writeable}
import play.api.libs.json.Json
import play.api.mvc._
import play.api.routing.Router
import play.api.test.FakeRequest
import play.api.{BuiltInComponentsFromContext, Configuration}
class TestComponents(ctx: Context) extends BuiltInComponentsFromContext(ctx) {
import play.api.routing.sird._
override lazy val configuration: Configuration = ctx.initialConfiguration ++ Configuration(
"play.http.forwarded.version" -> "x-forwarded",
"play.http.forwarded.trustedProxies" -> List("0.0.0.0/0", "::/0")
)
override def router: Router = Router.from {
case GET(p"/") => securityCheck(_.secure)
case GET(p"/mod") => securityCheck(Proxies.isSecure)
}
def securityCheck(isSecure: RequestHeader => Boolean) = Action { req =>
Results.Ok(Json.obj(
"secure" -> isSecure(req),
"headers" -> PlayUtils.headersString(req))
)
}
}
class SiloTest extends AppSuite(new TestComponents(_)) {
import play.api.test.Helpers._
test("play says secure is false despite https in trusted proxy") {
assert(!makeReq("/"))
}
test("Proxies.isSecure says https") {
assert(makeReq("/mod"))
}
def makeReq(url: String) = {
val reqHeaders = Headers(
HeaderNames.X_FORWARDED_PROTO -> "https",
HeaderNames.X_FORWARDED_FOR -> "10.0.0.1"
)
val res = makeRequest(FakeRequest(GET, url, reqHeaders, AnyContentAsEmpty))
assert(res.header.status === 200)
val json = contentAsJson(fut(res))
(json \ "secure").as[Boolean]
}
def makeRequest[T: Writeable](req: Request[T]): Result =
await(route(app, req).get)
}
示例7: TestAppSuite
//设置package包名称以及导入依赖的类
package tests
import com.malliina.app.AppComponents
import com.malliina.oauth.GoogleOAuthCredentials
import play.api.http.Writeable
import play.api.mvc.Request
import play.api.test.FakeRequest
import play.api.test.Helpers._
abstract class TestAppSuite extends AppSuite(ctx => new AppComponents(
ctx,
GoogleOAuthCredentials("id", "secret", "scope"),
TestPics)
)
class AppTests extends TestAppSuite {
test("can make request") {
val result = makeRequest(FakeRequest(GET, "/"))
assert(result.header.status === 303)
}
test("can upload file") {
val result = makeRequest(FakeRequest(POST, "/pics").withBody("boom"))
assert(result.header.status === 303)
}
def makeRequest[T: Writeable](req: Request[T]) =
await(route(app, req).get)
}
示例8: PlayIntegration
//设置package包名称以及导入依赖的类
package de.lenabrueder.rfc7807
import de.lenabrueder.rfc7807.Problem.UrlConfiguration
import play.api.http.Writeable
import play.api.libs.json.{JsValue, Json}
import play.api.mvc.Result
object PlayIntegration extends LowPriorityProblemImplicits {
implicit class ResultAsProblem[T <: Result](val result: T) {
def withProblem(problem: Problem)(implicit writeable: Writeable[JsValue]): Result =
Result(
result.header,
writeable.toEntity(Json.toJson(problem.copy(status = problem.status orElse Some(result.header.status))))
).as("application/problem+json")
def withProblem(ex: Throwable): Result =
withProblem(Problematic.fromException(ex))
def withProblem(problematic: Problematic): Result =
withProblem(problematic.asProblem)
def withProblem(problem: String)(implicit urlConfiguration: UrlConfiguration): Result =
withProblem(Problem(urlConfiguration.url(result.header.status.toString), problem))
def asProblem(implicit urlConfiguration: UrlConfiguration): Result =
withProblem(result.header.reasonPhrase getOrElse "unknown")
}
}
示例9: Credentials
//设置package包名称以及导入依赖的类
package uk.gov.homeoffice.mercury
import akka.http.scaladsl.model.MediaTypes._
import akka.util.{ByteString, CompactByteString}
import play.api.http.Writeable
import play.api.libs.json.Json
import uk.gov.homeoffice.mercury.MediaTypes.Implicits._
case class Credentials(userName: String, password: String)
object Credentials {
val credentialsToByteString: Credentials => ByteString = { c =>
val credentials = Json.obj(
"username" -> c.userName,
"password" -> c.password
)
CompactByteString(Json.stringify(credentials).getBytes)
}
implicit val credentialsWriteable: Writeable[Credentials] = Writeable(credentialsToByteString, Some(`application/json`))
}
示例10: setUpResponse
//设置package包名称以及导入依赖的类
package utils
import logging.{WSMethods, WSRequestWrapper}
import org.mockito.ArgumentCaptor
import org.mockito.Matchers.{eq => mockitoEq, _}
import org.mockito.Mockito._
import play.api.http.{ContentTypeOf, Writeable}
import play.api.libs.ws.WSResponse
import scala.concurrent.Future
trait WsClient extends Mocking {
val wsClient = mock[WSMethods]
val mockRequestHolder = mock[WSRequestWrapper]
val mockResponse = mock[WSResponse]
private val bodyCaptor = ArgumentCaptor.forClass(classOf[String])
def setUpResponse(url: String, statusCode: Int, responseBody: String = "") = {
setUpRequestHolder(url)
setUpResponseHolder(statusCode, responseBody)
}
def setUpException(url: String) = {
setUpRequestHolder(url)
when(mockRequestHolder.post(any[String])(any[Writeable[String]], any[ContentTypeOf[String]])).thenReturn(Future.successful(mockResponse))
when(mockResponse.status).thenThrow(new RuntimeException("Boom"))
}
def requestBody() = {
verify(mockRequestHolder, timeout(500)).post(bodyCaptor.capture())(any[Writeable[String]], any[ContentTypeOf[String]])
bodyCaptor.getValue
}
private def setUpRequestHolder(url: String) = {
when(mockRequestHolder.withHeaders(any[(String, String)])).thenReturn(mockRequestHolder)
when(mockRequestHolder.withQueryString(any[(String, String)])).thenReturn(mockRequestHolder)
when(wsClient.url(mockitoEq(url))).thenReturn(mockRequestHolder)
}
private def setUpResponseHolder(statusCode: Int, responseBody: String) = {
when(mockResponse.status).thenReturn(statusCode)
when(mockResponse.body).thenReturn(responseBody)
when(mockRequestHolder.post(any[String])(any[Writeable[String]], any[ContentTypeOf[String]])).thenReturn(Future.successful(mockResponse))
}
}
示例11: RestController
//设置package包名称以及导入依赖的类
package dcos.metronome.api
import com.eclipsesource.schema.SchemaValidator
import com.wix.accord.{ Validator, Success, Failure }
import mesosphere.marathon.api.v2.Validation
import play.api.http.{ ContentTypes, ContentTypeOf, Writeable }
import play.api.libs.json._
import play.api.mvc._
class RestController extends Controller {
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](Some(ContentTypes.JSON))
Writeable(t => codec.encode(Json.stringify(w.writes(t))))
}
object validate extends BodyParsers {
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)
}
}
}
}
}
示例12: 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)
}