play.api.http.Writeable Scala Examples

The following examples show how to use play.api.http.Writeable. 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: instagram_api_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
package instagram.api.yaml

import de.zalando.play.controllers._
import org.scalacheck._
import org.scalacheck.Arbitrary._
import org.scalacheck.Prop._
import org.scalacheck.Test._
import org.specs2.mutable._
import play.api.test.Helpers._
import play.api.test._
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc._

import org.junit.runner.RunWith
import org.specs2.runner.JUnitRunner
import java.net.URLEncoder
import com.fasterxml.jackson.databind.ObjectMapper

import play.api.http.Writeable
import play.api.libs.Files.TemporaryFile
import play.api.test.Helpers.{status => requestStatusCode_}
import play.api.test.Helpers.{contentAsString => requestContentAsString_}
import play.api.test.Helpers.{contentType => requestContentType_}

import scala.math.BigInt
import scala.math.BigDecimal

import Generators._

    @RunWith(classOf[JUnitRunner])
    class Instagram_api_yamlSpec extends Specification {
        def toPath[T](value: T)(implicit binder: PathBindable[T]): String = Option(binder.unbind("", value)).getOrElse("")
        def toQuery[T](key: String, value: T)(implicit binder: QueryStringBindable[T]): String = Option(binder.unbind(key, value)).getOrElse("")
        def toHeader[T](value: T)(implicit binder: PathBindable[T]): String = Option(binder.unbind("", value)).getOrElse("")

      def checkResult(props: Prop) =
        Test.check(Test.Parameters.default, props).status match {
          case Failed(args, labels) =>
            val failureMsg = labels.mkString("\n") + " given args: " + args.map(_.arg).mkString("'", "', '","'")
            failure(failureMsg)
          case Proved(_) | Exhausted | Passed => success
          case PropException(_, e, labels) =>
            val error = if (labels.isEmpty) e.getLocalizedMessage() else labels.mkString("\n")
            failure(error)
        }

      private def parserConstructor(mimeType: String) = PlayBodyParsing.jacksonMapper(mimeType)

      def parseResponseContent[T](mapper: ObjectMapper, content: String, mimeType: Option[String], expectedType: Class[T]) =
        mapper.readValue(content, expectedType)

} 
Example 2
Source File: security_api_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package security.api.yaml

import de.zalando.play.controllers._
import org.scalacheck._
import org.scalacheck.Arbitrary._
import org.scalacheck.Prop._
import org.scalacheck.Test._
import org.specs2.mutable._
import org.specs2.execute._
import play.api.test.Helpers._
import play.api.test._
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc._

import org.junit.runner.RunWith
import java.net.URLEncoder
import com.fasterxml.jackson.databind.ObjectMapper

import play.api.http.Writeable
import play.api.libs.Files.TemporaryFile
import play.api.test.Helpers.{status => requestStatusCode_}
import play.api.test.Helpers.{contentAsString => requestContentAsString_}
import play.api.test.Helpers.{contentType => requestContentType_}

import org.scalatest.{OptionValues, WordSpec}
import org.scalatestplus.play.{OneAppPerTest, WsScalaTestClient}

import Generators._

import de.zalando.play.controllers.ArrayWrapper

//noinspection ScalaStyle
class Security_api_yamlSpec extends WordSpec with OptionValues with WsScalaTestClient with OneAppPerTest  {
    def toPath[T](value: T)(implicit binder: PathBindable[T]): String = Option(binder.unbind("", value)).getOrElse("")
    def toQuery[T](key: String, value: T)(implicit binder: QueryStringBindable[T]): String = Option(binder.unbind(key, value)).getOrElse("")
    def toHeader[T](value: T)(implicit binder: QueryStringBindable[T]): String = Option(binder.unbind("", value)).getOrElse("")

  def checkResult(props: Prop): org.specs2.execute.Result =
    Test.check(Test.Parameters.default, props).status match {
      case Failed(args, labels) =>
        val failureMsg = labels.mkString("\n") + " given args: " + args.map(_.arg).mkString("'", "', '","'")
        org.specs2.execute.Failure(failureMsg)
      case Proved(_) | Exhausted | Passed => org.specs2.execute.Success()
      case PropException(_, e: IllegalStateException, _) => org.specs2.execute.Error(e.getMessage)
      case PropException(_, e, labels) =>
        val error = if (labels.isEmpty) e.getLocalizedMessage else labels.mkString("\n")
        org.specs2.execute.Failure(error)
    }

  private def parserConstructor(mimeType: String) = PlayBodyParsing.jacksonMapper(mimeType)

  def parseResponseContent[T](mapper: ObjectMapper, content: String, mimeType: Option[String], expectedType: Class[T]) =
    if (expectedType.getCanonicalName == "scala.runtime.Null$") null else mapper.readValue(content, expectedType)

} 
Example 3
Source File: instagram_api_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package instagram.api.yaml

import de.zalando.play.controllers._
import org.scalacheck._
import org.scalacheck.Arbitrary._
import org.scalacheck.Prop._
import org.scalacheck.Test._
import org.specs2.mutable._
import org.specs2.execute._
import play.api.test.Helpers._
import play.api.test._
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc._

import org.junit.runner.RunWith
import java.net.URLEncoder
import com.fasterxml.jackson.databind.ObjectMapper

import play.api.http.Writeable
import play.api.libs.Files.TemporaryFile
import play.api.test.Helpers.{status => requestStatusCode_}
import play.api.test.Helpers.{contentAsString => requestContentAsString_}
import play.api.test.Helpers.{contentType => requestContentType_}

import org.scalatest.{OptionValues, WordSpec}
import org.scalatestplus.play.{OneAppPerTest, WsScalaTestClient}

import Generators._

import scala.math.BigInt
import scala.math.BigDecimal

//noinspection ScalaStyle
class Instagram_api_yamlSpec extends WordSpec with OptionValues with WsScalaTestClient with OneAppPerTest  {
    def toPath[T](value: T)(implicit binder: PathBindable[T]): String = Option(binder.unbind("", value)).getOrElse("")
    def toQuery[T](key: String, value: T)(implicit binder: QueryStringBindable[T]): String = Option(binder.unbind(key, value)).getOrElse("")
    def toHeader[T](value: T)(implicit binder: QueryStringBindable[T]): String = Option(binder.unbind("", value)).getOrElse("")

  def checkResult(props: Prop): org.specs2.execute.Result =
    Test.check(Test.Parameters.default, props).status match {
      case Failed(args, labels) =>
        val failureMsg = labels.mkString("\n") + " given args: " + args.map(_.arg).mkString("'", "', '","'")
        org.specs2.execute.Failure(failureMsg)
      case Proved(_) | Exhausted | Passed => org.specs2.execute.Success()
      case PropException(_, e: IllegalStateException, _) => org.specs2.execute.Error(e.getMessage)
      case PropException(_, e, labels) =>
        val error = if (labels.isEmpty) e.getLocalizedMessage else labels.mkString("\n")
        org.specs2.execute.Failure(error)
    }

  private def parserConstructor(mimeType: String) = PlayBodyParsing.jacksonMapper(mimeType)

  def parseResponseContent[T](mapper: ObjectMapper, content: String, mimeType: Option[String], expectedType: Class[T]) =
    if (expectedType.getCanonicalName == "scala.runtime.Null$") null else mapper.readValue(content, expectedType)

} 
Example 4
Source File: writableHelperTest.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package de.zalando.play.controllers

import akka.util.ByteString
import de.zalando.play.controllers.ResponseWriters.choose
import org.specs2.mutable.Specification
import play.api.http.Writeable
import play.api.mvc.RequestHeader

import scala.concurrent.ExecutionContext.Implicits


    override val custom: Seq[(String, ParserWrapper[_])] = Seq(
      "text/plain" -> any
    )
  }

  "WrappedBodyParsers" should {
    "find something" in {
      WrappedBodyParsers.anyParser[Any] must_== Nil
    }
    "not find anything for wrong type" in {
      binaryString.anyParser[String] must_== Nil
    }
    "find something for correct type" in {
      binaryString.anyParser[BinaryString].size must_== 1
    }
    "find something for every type if target is 'Any'" in {
      catchAll.anyParser[String].size must_== 1
      catchAll.anyParser[BinaryString].size must_== 1
    }
  }
}

object TestEnvironment {
  import Implicits.global
  val transformSeq: Seq[Any] => ByteString = a => ByteString.fromString(a.toString)
  val transformStr: String => ByteString = ByteString.fromString

  val seqText: WriteableWrapper[Seq[Any]] = Writeable(transformSeq, Some("text/plain"))

  val stringText: WriteableWrapper[String] = Writeable(transformStr, Some("text/plain"))

  val reg = Seq(seqText, stringText)
} 
Example 5
Source File: writeableHelper.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package de.zalando.play.controllers

import akka.util.ByteString
import play.api.http.Writeable
import play.api.libs.json._
import play.api.mvc.Results.{ Redirect, Status }
import play.api.mvc.{ AnyContentAsMultipartFormData, RequestHeader, Results }

import scala.language.implicitConversions

case class WriteableWrapper[T](w: Writeable[T], m: Manifest[T])

object WriteableWrapper {
  implicit def writeable2wrapper[T](w: Writeable[T])(implicit m: Manifest[T]): WriteableWrapper[T] =
    WriteableWrapper(w, m)
  implicit val anyContentAsMultipartFormWritable: Writeable[AnyContentAsMultipartFormData] = {
    MultipartFormDataWritable.singleton.map(_.mdf)
  }
}


object ResponseWriters extends ResponseWritersBase

trait ResponseWritersBase {

  type ContentType = String

  def custom: Seq[WriteableWrapper[_]] = Seq.empty

  case class choose[T](mimeType: ContentType) {
    def apply[R <: Any](registry: Seq[WriteableWrapper[_]] = custom)(implicit m: Manifest[R]): Option[Writeable[R]] =
      registry filter {
        _.w.contentType.exists(_ == mimeType)
      } find { p =>
        m.runtimeClass.isAssignableFrom(p.m.runtimeClass)
      } map {
        _.asInstanceOf[WriteableWrapper[R]]
      } map (_.w)
  }

  implicit val jsonTranslatedParsingErrorWrites = Json.writes[TranslatedParsingError]

  implicit val jsonTranslatedParsingErrorsContainerWrites = Json.writes[TranslatedParsingErrorsContainer]
}

object WrappedBodyParsers extends WrappedBodyParsersBase

trait WrappedBodyParsersBase {
  implicit def parser2parserWrapper[T](p: Parser[T])(implicit m: Manifest[T]): ParserWrapper[T] = ParserWrapper(p, m)
  type Parser[T] = ByteString => T
  case class ParserWrapper[T](p: Parser[T], m: Manifest[T])
  val custom: Seq[(String, ParserWrapper[_])] = Seq.empty
  def anyParser[T](implicit manifest: Manifest[T]): Seq[(String, Parser[T])] =
    custom.filter(_._2.m.runtimeClass.isAssignableFrom(manifest.runtimeClass)).map { e =>
      e.copy(_2 = e._2.asInstanceOf[ParserWrapper[T]].p)
    }
  def optionParser[T](implicit manifest: Manifest[T]): Seq[(String, Parser[Option[T]])] = anyParser[Option[T]]
}

trait ResultWrapper[ResultT] {
  val emptyByteString = akka.util.CompactByteString.empty
  def statusCode: Int
  def result: ResultT
  def toResultWithWriter(implicit writer: Writeable[ResultT]): play.api.mvc.Result =
    if (statusCode / 100 == 3)
      Redirect(result.toString, statusCode)
    else
      Status(statusCode)(result)

  def writer: String => Option[Writeable[ResultT]]
  def toResult(mimeType: String): Option[play.api.mvc.Result] =
    if (statusCode / 100 == 3)
      Option(Redirect(result.toString, statusCode))
    else
      writer(mimeType).map(Status(statusCode)(result)(_))

} 
Example 6
Source File: MultipartFormDataWritable.scala    From api-first-hand   with MIT License 5 votes vote down vote up
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")
  )
} 
Example 7
Source File: YamlContent.scala    From metronome   with Apache License 2.0 5 votes vote down vote up
package dcos.metronome
package api

import net.jcazevedo.moultingyaml.{YamlValue, _}
import play.api.http.{ContentTypeOf, MimeTypes, Writeable}
import play.api.mvc.{Accepting, BodyParser, Codec, AbstractController}

import scala.concurrent.Future

trait YamlContent { self: AbstractController =>

  import scala.concurrent.ExecutionContext.Implicits.global

  val AcceptJson = Accepting(MimeTypes.JSON)
  val AcceptYaml = Accepting("application/x-yaml")

  implicit val YamlContentType = ContentTypeOf[YamlValue](Some("application/x-yaml"))

  implicit def writeableOfYamlValue(implicit codec: Codec): Writeable[YamlValue] = {
    Writeable(yaml => codec.encode(yaml.prettyPrint))
  }

  def parseYaml: BodyParser[YamlValue] =
    parse.when(
      _.contentType.exists(m => m.equalsIgnoreCase("text/yaml") || m.equalsIgnoreCase("application/x-yaml")),
      parse.tolerantText.map(_.parseYaml),
      _ => Future.successful(BadRequest("Expecting text/yaml or application/x-yaml body"))
    )
} 
Example 8
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)
        }
      }
    }
  }
} 
Example 9
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 10
Source File: security_api_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
package security.api.yaml

import de.zalando.play.controllers._
import org.scalacheck._
import org.scalacheck.Arbitrary._
import org.scalacheck.Prop._
import org.scalacheck.Test._
import org.specs2.mutable._
import play.api.test.Helpers._
import play.api.test._
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc._

import org.junit.runner.RunWith
import org.specs2.runner.JUnitRunner
import java.net.URLEncoder
import com.fasterxml.jackson.databind.ObjectMapper

import play.api.http.Writeable
import play.api.libs.Files.TemporaryFile
import play.api.test.Helpers.{status => requestStatusCode_}
import play.api.test.Helpers.{contentAsString => requestContentAsString_}
import play.api.test.Helpers.{contentType => requestContentType_}

import de.zalando.play.controllers.ArrayWrapper

import Generators._

    @RunWith(classOf[JUnitRunner])
    class Security_api_yamlSpec extends Specification {
        def toPath[T](value: T)(implicit binder: PathBindable[T]): String = Option(binder.unbind("", value)).getOrElse("")
        def toQuery[T](key: String, value: T)(implicit binder: QueryStringBindable[T]): String = Option(binder.unbind(key, value)).getOrElse("")
        def toHeader[T](value: T)(implicit binder: PathBindable[T]): String = Option(binder.unbind("", value)).getOrElse("")

      def checkResult(props: Prop) =
        Test.check(Test.Parameters.default, props).status match {
          case Failed(args, labels) =>
            val failureMsg = labels.mkString("\n") + " given args: " + args.map(_.arg).mkString("'", "', '","'")
            failure(failureMsg)
          case Proved(_) | Exhausted | Passed => success
          case PropException(_, e, labels) =>
            val error = if (labels.isEmpty) e.getLocalizedMessage() else labels.mkString("\n")
            failure(error)
        }

      private def parserConstructor(mimeType: String) = PlayBodyParsing.jacksonMapper(mimeType)

      def parseResponseContent[T](mapper: ObjectMapper, content: String, mimeType: Option[String], expectedType: Class[T]) =
        mapper.readValue(content, expectedType)

} 
Example 11
Source File: SemanticRepositorySpecs.scala    From daf-semantics   with Apache License 2.0 5 votes vote down vote up
package specs

import org.junit.runner.RunWith

import scala.concurrent.{ Await, Future }
import scala.concurrent.duration.Duration

import play.api.test._
import play.api.http.Status
import play.api.Application
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.ws.WSResponse
import play.api.libs.ws.ahc.AhcWSClient
import org.specs2.runner.JUnitRunner
import org.specs2.mutable.Specification
import play.api.libs.json.Json
//import it.almawave.linkeddata.kb.utils.ConfigHelper

import scala.collection.JavaConversions._
import scala.collection.JavaConverters._
import play.twirl.api.Content
import play.api.test.Helpers._
import play.api.libs.json.JsObject
import java.io.File
import play.api.http.Writeable
import akka.stream.scaladsl.Source
import play.api.mvc.MultipartFormData
import play.api.libs.Files.TemporaryFile
import java.nio.file.Files
import org.asynchttpclient.AsyncHttpClient
import play.api.libs.ws.WS
import akka.util.ByteString
import play.api.mvc.MultipartFormData.DataPart
import play.api.mvc.MultipartFormData.FilePart
import akka.stream.scaladsl.FileIO
import play.api.libs.ws.WSClient

/*
 * TODO: REWRITE
 */
@RunWith(classOf[JUnitRunner])
class SemanticRepositorySpecs extends Specification {

  def application: Application = GuiceApplicationBuilder().build()

  "The semantic repository" should {

    "call kb/v1/contexts to obtain a list of contexts" in {
      new WithServer(app = application, port = 9999) {
        WsTestClient.withClient { implicit client =>

          val response: WSResponse = Await.result[WSResponse](
            client.url(s"http://localhost:${port}/kb/v1/contexts").execute,
            Duration.Inf)

          response.status must be equalTo Status.OK
          response.json.as[Seq[JsObject]].size must be equals 0
          // response.json.as[Seq[JsObject]].size must be greaterThan 0 // if pre-loaded ontologies!

        }
      }
    }

    "call kb/v1/contexts ensuring all contexts have triples" in {
      new WithServer(app = application, port = 9999) {
        WsTestClient.withClient { implicit client =>

          val response: WSResponse = Await.result[WSResponse](
            client.url(s"http://localhost:${port}/kb/v1/contexts").execute,
            Duration.Inf)

          val json_list = response.json.as[Seq[JsObject]]
          forall(json_list)((_) must not beNull)
          forall(json_list)(_.keys must contain("context", "triples"))
          forall(json_list)(item => (item \ "triples").get.as[Int] > 0)

        }
      }
    }

  }

} 
Example 12
Source File: simple_petstore_api_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
package simple_petstore_api_yaml

import play.api.http.Writeable
import play.api.libs.iteratee.Execution.Implicits.trampoline
import play.api.mvc.RequestHeader
import de.zalando.play.controllers._
import WriteableWrapper.writeable2wrapper

import de.zalando.play.controllers.ArrayWrapper




    override val custom: Seq[WriteableWrapper[_]] = Seq(
        writable_text_xml_PetsGetResponses200_esc, 
        writable_text_html_PetsGetResponses200_esc, 
        writable_application_xml_PetsGetResponses200_esc, 
        writable_application_xml_ErrorModel_esc, 
        writable_text_html_ErrorModel_esc, 
        writable_text_xml_ErrorModel_esc, 
        writable_application_xml_Pet_esc, 
        writable_text_html_Pet_esc, 
        writable_text_xml_Pet_esc
    )
} 
Example 13
Source File: writableHelperTest.scala    From play-swagger   with MIT License 5 votes vote down vote up
package de.zalando.play.controllers

import de.zalando.play.controllers.ResponseWriters.choose
import org.specs2.mutable.Specification
import play.api.http.Writeable
import play.api.mvc.RequestHeader
import scala.concurrent.ExecutionContext.Implicits


    override val custom: Seq[(String, ParserWrapper[_])] = Seq(
      "text/plain" -> any
    )
  }

  "WrappedBodyParsers" should {
    "find something" in {
      WrappedBodyParsers.anyParser[Any] must_== Nil
    }
    "not find anything for wrong type" in {
      binaryString.anyParser[String] must_== Nil
    }
    "find something for correct type" in {
      binaryString.anyParser[BinaryString].size must_== 1
    }
    "find something for every type if target is 'Any'" in {
      catchAll.anyParser[String].size must_== 1
      catchAll.anyParser[BinaryString].size must_== 1
    }
  }
}

object TestEnvironment {
  import Implicits.global
  val transformSeq: Seq[Any] => Array[Byte] = a => a.toString.getBytes("UTF-8")
  val transformStr: String => Array[Byte] = a => a.getBytes("UTF-8")

  val seqText: WriteableWrapper[Seq[Any]] = Writeable(transformSeq, Some("text/plain"))

  val stringText: WriteableWrapper[String] = Writeable(transformStr, Some("text/plain"))

  val reg = Seq(seqText, stringText)
} 
Example 14
Source File: writeableHelper.scala    From play-swagger   with MIT License 5 votes vote down vote up
package de.zalando.play.controllers

import play.api.http.Writeable
import play.api.mvc.{AnyContentAsMultipartFormData, RequestHeader}
import scala.language.implicitConversions
import play.api.mvc.{RequestHeader, Result, Results}
import play.api.http._
import Results.{Status, Redirect}

case class WriteableWrapper[T](w: Writeable[T], m: Manifest[T])

object WriteableWrapper {
  implicit def writeable2wrapper[T](w: Writeable[T])(implicit m: Manifest[T]) =
    WriteableWrapper(w, m)
  implicit val anyContentAsMultipartFormWritable: Writeable[AnyContentAsMultipartFormData] = {
    MultipartFormDataWritable.singleton.map(_.mdf)
  }
}


object ResponseWriters extends ResponseWritersBase

trait ResponseWritersBase {

  type ContentType = String

  def custom: Seq[WriteableWrapper[_]] = Seq.empty

  case class choose[T](mimeType: ContentType) {
    def apply[R <: Any](registry: Seq[WriteableWrapper[_]] = custom)(implicit m: Manifest[R]): Option[Writeable[R]] =
      registry filter {
        _.w.contentType.exists(_ == mimeType)
      } find { p =>
        m.runtimeClass.isAssignableFrom(p.m.runtimeClass)
      } map  {
        _.asInstanceOf[WriteableWrapper[R]]
      } map(_.w)
  }

}

object WrappedBodyParsers extends WrappedBodyParsersBase

trait WrappedBodyParsersBase {
  implicit def parser2parserWrapper[T](p: Parser[T])(implicit m: Manifest[T]): ParserWrapper[T] = ParserWrapper(p, m)
  type Parser[T] = (RequestHeader, Array[Byte]) => T
  case class ParserWrapper[T](p: Parser[T], m: Manifest[T])
  val custom: Seq[(String, ParserWrapper[_])] = Seq.empty
  def anyParser[T](implicit manifest: Manifest[T]): Seq[(String, Parser[T])] =
    custom.filter(_._2.m.runtimeClass.isAssignableFrom(manifest.runtimeClass)).map { e =>
      e.copy(_2 = e._2.asInstanceOf[ParserWrapper[T]].p) }
  def optionParser[T](implicit manifest: Manifest[T]): Seq[(String, Parser[Option[T]])] = anyParser[Option[T]]
}

trait ResultWrapper[ResultT] {
  def statusCode: Int
  def result: ResultT
  def writer: String => Option[Writeable[ResultT]]
  def toResult(mimeType: String): Option[play.api.mvc.Result] =
    if (statusCode / 100 == 3)
      Option(Redirect(result.toString, statusCode))
    else
      writer(mimeType).map(Status(statusCode)(result)(_))
} 
Example 15
Source File: MultipartFormDataWritable.scala    From play-swagger   with MIT License 5 votes vote down vote up
package de.zalando.play.controllers

import java.nio.file.{Files, Paths}

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 {
  import scala.concurrent.ExecutionContext.Implicits.global

  val boundary = "--------ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"

  def formatDataParts(data: Map[String, Seq[String]]): Array[Byte] = {
    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]): Array[Byte] = {
    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")
  )
} 
Example 16
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 17
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 18
Source File: JsonEntities.scala    From endpoints4s   with MIT License 5 votes vote down vote up
package endpoints4s.play.server.circe

import endpoints4s.{Invalid, algebra}
import endpoints4s.play.server.EndpointsWithCustomErrors
import io.circe.{
  DecodingFailure,
  Json,
  ParsingFailure,
  parser,
  Decoder => CirceDecoder,
  Encoder => CirceEncoder
}
import Util.circeJsonWriteable
import cats.Show
import play.api.http.Writeable


  type JsonResponse[A] = CirceEncoder[A]

  def jsonRequest[A: CirceDecoder]: RequestEntity[A] =
    headers => {
      if (headers.contentType.exists(_.equalsIgnoreCase("application/json"))) {
        Some(playComponents.playBodyParsers.tolerantText.validate { text =>
          parser
            .parse(text)
            .left
            .map(Show[ParsingFailure].show)
            .flatMap { json =>
              CirceDecoder[A]
                .decodeJson(json)
                .left
                .map(Show[DecodingFailure].show)
            }
            .left
            .map(error => handleClientErrors(Invalid(error)))
        })
      } else {
        None
      }
    }

  def jsonResponse[A: CirceEncoder]: ResponseEntity[A] =
    responseEntityFromWriteable(
      implicitly[Writeable[Json]].map(CirceEncoder[A].apply(_))
    )

} 
Example 19
Source File: OpenTsdbWSMock.scala    From prometheus-opentsdb-exporter   with Apache License 2.0 5 votes vote down vote up
package tools

import scala.concurrent.duration.Duration
import scala.concurrent.Future

import play.api.http.{HeaderNames, Writeable}
import play.api.libs.ws._
import play.api.libs.json._
import play.api.http.Status._

import org.specs2.mock.Mockito


abstract class OpenTsdbWSMock extends Mockito with WSClient {
  private val request = mock[WSRequest]
  private val response = mock[WSResponse]

  private var metrics: List[String] = List.empty

  private val urls:collection.mutable.Buffer[String] = new collection.mutable.ArrayBuffer[String]()

  request.withRequestTimeout(any[Duration]) returns request
  request.withFollowRedirects(any[Boolean]) returns request

  response.status returns OK
  response.header(HeaderNames.CONTENT_TYPE) returns Some("application/json;charset=UTF-8")
  response.json answers { _ => this.synchronized {
    val payload = responsePayload(metrics.head)
    metrics = metrics.tail
    payload
  }}

  request.post(anyString)(any[Writeable[String]]) answers { args => this.synchronized {
    val payload = args.asInstanceOf[Array[Object]](0).asInstanceOf[JsValue]
    val metric = (payload \ "queries") (0) \ "metric" match {
      case JsDefined(m) => m.toString.replace("\"", "")
      case _ => ""
    }

    metrics = metrics ++ List(metric)

    Future.successful(response)
  }}

  def url(url: String): WSRequest = {
    urls += url
    request
  }

  def underlying[T]: T = this.asInstanceOf[T]

  protected def responsePayload: Map[String, JsValue]

  override def close(): Unit = ()
}