scala.math.BigInt Scala Examples

The following examples show how to use scala.math.BigInt. 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.extractor.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package instagram.api.yaml

import scala.concurrent.Future
import play.api.mvc._
import de.zalando.play.controllers.SwaggerSecurityExtractors._
import scala.math.BigInt
import scala.math.BigDecimal

object SecurityExtractorsExecutionContext {
    // this ExecutionContext might be overridden if default configuration is not suitable for some reason
    implicit val ec = de.zalando.play.controllers.Contexts.tokenChecking
}

trait SecurityExtractors {
    def oauth_Extractor[User >: Any](scopes: String*): RequestHeader => Future[Option[User]] =
        header => oAuth(scopes)("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")(header) { (token: play.api.libs.json.JsValue) =>
            ???
    }
    def key_Extractor[User >: Any](): RequestHeader => Future[Option[User]] =
        header => queryApiKey("access_token")(header) { (apiKey: String) =>
            ???
    }
    implicit val unauthorizedContentWriter = ???
    def unauthorizedContent(req: RequestHeader) = Results.Unauthorized(???)
} 
Example 2
Source File: CodecSpec.scala    From libisabelle   with Apache License 2.0 5 votes vote down vote up
package info.hupel.isabelle.tests

import scala.math.BigInt

import org.specs2.{ScalaCheck, Specification}
import org.specs2.specification.core.Env

import org.scalacheck._
import org.scalacheck.Prop.forAll

import info.hupel.isabelle._
import info.hupel.isabelle.api.XML

class CodecSpec(val specs2Env: Env) extends Specification with BasicSetup with ScalaCheck { def is = s2"""

  Round-trip property of Codecs

  Values can be converted
    of type Unit                      ${propCodec[Unit]}
    of type Boolean                   ${propCodec[Boolean]}
    of type BigInt                    ${propCodec[BigInt]}
    of type String                    ${propCodec[String]}
    of type (BigInt, BigInt)          ${propCodec[(BigInt, BigInt)]}
    of type (String, Unit)            ${propCodec[(String, Unit)]}
    of type List[Unit]                ${propCodec[List[Unit]]}
    of type List[BigInt]              ${propCodec[List[BigInt]]}
    of type List[String]              ${propCodec[List[String]]}
    of type List[List[String]]        ${propCodec[List[List[String]]]}
    of type List[(BigInt, BigInt)]    ${propCodec[List[(BigInt, BigInt)]]}
    of type (BigInt, List[BigInt])    ${propCodec[(BigInt, List[BigInt])]}
    of type Option[BigInt]            ${propCodec[Option[BigInt]]}
    of type Option[List[BigInt]]      ${propCodec[Option[List[BigInt]]]}
    of type List[Option[BigInt]]      ${propCodec[List[Option[BigInt]]]}
    of type Either[String, BigInt]    ${propCodec[Either[String, BigInt]]}
  """

  def propCodec[A : Codec : Arbitrary] = properties(new Properties("props") {
    property("encode/decode") = forAll { (a: A) =>
      Codec[A].decode(Codec[A].encode(a)) must beRight(a)
    }

    property("YXML") = forAll { (a: A) =>
      val encoded = Codec[A].encode(a)
      XML.fromYXML(encoded.toYXML) must be_===(encoded)
    }
  })

} 
Example 3
Source File: LibisabelleSpec.scala    From libisabelle   with Apache License 2.0 5 votes vote down vote up
package info.hupel.isabelle.tests

import java.nio.file.Paths

import scala.concurrent._
import scala.math.BigInt

import org.specs2.Specification
import org.specs2.specification.core.Env

import info.hupel.isabelle._
import info.hupel.isabelle.pure._

class PreloadedLibisabelleSpec(specs2Env: Env) extends LibisabelleSpec(specs2Env, "preloaded")
class UnloadedLibisabelleSpec(specs2Env: Env) extends LibisabelleSpec(specs2Env, "unloaded") {
  override def session = "Pure"
}

abstract class LibisabelleSpec(val specs2Env: Env, flavour: String) extends Specification
  with FullSetup
  with IsabelleMatchers { def is = s2"""

  Basic protocol interaction ($flavour)

  An Isabelle session
    can be started             ${system must exist.awaitFor(duration)}
    supports term parsing      ${parseCheck must beSuccess(Option.empty[String]).awaitFor(duration)}
    can parse terms            ${parsed must beSome.awaitFor(duration)}
    can't parse wrong terms    ${parseFailed must beNone.awaitFor(duration)}
    handles missing operations ${missingOperation must beFailure(contain("unknown command")).awaitFor(duration)}
    can load theories          ${loaded must beSuccess(()).awaitFor(duration)}
    handles operation errors   ${operationError must beFailure(contain("Invalid time")).awaitFor(duration)}
    handles load errors        ${loadedFailing must beFailure(be =~ """.*((Failed to finish proof)|(EXCURSION_FAIL)).*""".r).awaitFor(duration)}
    can cancel requests        ${cancelled.failed must beAnInstanceOf[CancellationException].awaitFor(duration)}"""


  // Pure operations

  val thy = Theory.get("Pure")
  val ctxt = Context.initGlobal(thy)

  val parseCheck = system.flatMap(sys => Term.parse(ctxt)("TERM x").check(sys, "Protocol_Pure"))

  val parsed = system.flatMap(_.run(Expr.fromString[Prop](ctxt, "TERM x"), "Protocol_Pure"))
  val parseFailed = system.flatMap(_.run(Expr.fromString[Prop](ctxt, "TERM"), "Protocol_Pure"))


  val AbsentOperation = Operation.implicitly[Unit, Unit]("absent_operation")

  val missingOperation = system.flatMap(_.invoke(AbsentOperation)(()))


  // Loading auxiliary files

  def load(name: String) = {
    val thy = resources.findTheory(Paths.get(s"tests/$name.thy")).get
    for {
      s <- system
      e <- isabelleEnv
      res <- s.invoke(Operation.UseThys)(List(e.isabellePath(thy)))
    }
    yield res
  }

  val loaded = load("Sleepy")
  val loadedFailing = load("Failing")

  val Sleepy = Operation.implicitly[BigInt, Unit]("sleepy")

  val operationError =
    for {
      s <- system
      _ <- loaded
      res <- s.invoke(Sleepy)(-1)
    }
    yield res

  val cancelled =
    for {
      s <- system
      _ <- loaded
      res <- { val future = s.invoke(Sleepy)(1); future.cancel(); future }
    }
    yield ()

} 
Example 4
Source File: package.scala    From libisabelle   with Apache License 2.0 5 votes vote down vote up
package info.hupel.isabelle

import scala.math.BigInt

import cats.instances.option._
import cats.instances.list._
import cats.syntax.traverse._

import info.hupel.isabelle.pure._

package hol {
  private class ListTypeable[T : Typeable] extends Typeable[List[T]] {
    def typ: Typ = Type("List.list", List(Typeable.typ[T]))
  }

  private[isabelle] trait LowPriorityImplicits {
    implicit def listTypeable[T : Typeable]: Typeable[List[T]] = new ListTypeable[T]
  }
}

package object hol extends LowPriorityImplicits {

  private val MkInt = Operation.implicitly[BigInt, Term]("mk_int")
  private val MkList = Operation.implicitly[(Typ, List[Term]), Term]("mk_list")

  private val DestInt = Operation.implicitly[Term, Option[BigInt]]("dest_int")
  private val DestList = Operation.implicitly[Term, Option[List[Term]]]("dest_list")

  implicit def bigIntTypeable: Embeddable[BigInt] = new Embeddable[BigInt] {
    def typ = HOLogic.intT
    def embed(t: BigInt) =
      Program.operation(MkInt, t)
    def unembed(t: Term) =
      Program.operation(DestInt, t)
  }

  implicit def boolTypeable: Embeddable[Boolean] = new Embeddable[Boolean] {
    def typ = HOLogic.boolT
    def embed(t: Boolean) = Program.pure {
      t match {
        case true => HOLogic.True
        case false => HOLogic.False
      }
    }
    def unembed(t: Term) = Program.pure {
      t match {
        case HOLogic.True => Some(true)
        case HOLogic.False => Some(false)
        case _ => None
      }
    }
  }

  implicit def listEmbeddable[T : Embeddable]: Embeddable[List[T]] = new ListTypeable[T] with Embeddable[List[T]] {
    def embed(ts: List[T]) =
      ts.traverse(Embeddable[T].embed) flatMap { ts =>
        Program.operation(MkList, ((Typeable.typ[T], ts)))
      }

    def unembed(t: Term) =
      Program.operation(DestList, t) flatMap {
        case None => Program.pure(None)
        case Some(ts) => ts.traverse(Embeddable[T].unembed).map(_.sequence)
      }
  }

  implicit class BoolExprOps(t: Expr[Boolean]) {
    def ∧(u: Expr[Boolean]): Expr[Boolean] =
      Expr(HOLogic.conj $ t.term $ u.term)

    def &(u: Expr[Boolean]): Expr[Boolean] = t ∧ u

    def ∨(u: Expr[Boolean]): Expr[Boolean] =
      Expr(HOLogic.disj $ t.term $ u.term)

    def |(u: Expr[Boolean]): Expr[Boolean] = t ∨ u

    def →(u: Expr[Boolean]): Expr[Boolean] =
      Expr(HOLogic.imp $ t.term $ u.term)

    def -->(u: Expr[Boolean]): Expr[Boolean] = t → u
  }

  implicit class HOLExprOps[A](t: Expr[A]) {
    def ≡(u: Expr[A])(implicit A: Typeable[A]): Expr[Boolean] =
      Expr(HOLogic.equ(A.typ) $ t.term $ u.term)
  }

} 
Example 5
Source File: Instruction.scala    From libisabelle   with Apache License 2.0 5 votes vote down vote up
package info.hupel.isabelle

import scala.concurrent._
import scala.math.BigInt

import monix.execution.CancelableFuture

import info.hupel.isabelle.ml.{Expr, Opaque}

sealed trait Instruction[A] {
  def run(sys: System, thyName: String)(implicit ec: ExecutionContext): CancelableFuture[ProverResult[A]]
}

object Instruction {

  private[isabelle] case class Ex[A](expr: Expr[A])(implicit A: Codec[A]) extends Instruction[A] {
    def run(sys: System, thyName: String)(implicit ec: ExecutionContext) =
      expr.eval(sys, thyName)
  }

  private[isabelle] case class OpaqueEx[A, Repr](expr: Expr[A], conv: Expr[A => Repr])(implicit A: Opaque[A], Repr: Codec[Repr]) extends Instruction[(BigInt, Repr)] {
    def run(sys: System, thyName: String)(implicit ec: ExecutionContext): CancelableFuture[ProverResult[(BigInt, Repr)]] =
      expr.opaqueEval(sys, thyName, conv)
  }

  private[isabelle] case class Op[I, O](operation: Operation[I, O], input: I) extends Instruction[O] {
    def run(sys: System, thyName: String)(implicit ec: ExecutionContext) =
      sys.invoke(operation)(input)
  }

} 
Example 6
Source File: Expr.scala    From libisabelle   with Apache License 2.0 5 votes vote down vote up
package info.hupel.isabelle.ml

import scala.concurrent.ExecutionContext
import scala.math.BigInt

import monix.execution.CancelableFuture

import cats.free.Free

import info.hupel.isabelle._
import info.hupel.isabelle.api.XML

sealed abstract class Expr[A] {

  private[isabelle] def eval(sys: System, thyName: String)(implicit A: Codec[A], ec: ExecutionContext): CancelableFuture[ProverResult[A]] =
    sys.invoke(Expr.Eval)((A.mlType, this, thyName)).map(_.map(A.decodeOrThrow))

  private[isabelle] def opaqueEval[Repr](sys: System, thyName: String, conv: ml.Expr[A => Repr])(implicit A: Opaque[A], Repr: Codec[Repr], ec: ExecutionContext): CancelableFuture[ProverResult[(BigInt, Repr)]] =
    sys.invoke(Expr.EvalOpaque)(((A.table, Repr.mlType, conv), this, thyName)).map(_.map { case (id, tree) =>
      (id, Repr.decodeOrThrow(tree))
    })

  def toProg(implicit A: Codec[A]): Program[A] =
    Program.expr(this)

  def rawPeek[Repr : Codec](conv: Expr[A => Repr])(implicit A: Opaque[A]): Program[(Ref[A], Repr)] =
    for {
      tuple <- Free.liftF[Instruction, (BigInt, Repr)](Instruction.OpaqueEx(this, conv))
      (id, repr) = tuple
    } yield (Ref(id), repr)

  def peek[Repr : Codec, C](conv: Expr[A => Repr])(f: (Repr, Expr[A]) => Program[C])(implicit A: Opaque[A]): Program[C] = {
    for {
      tuple <- rawPeek(conv)
      (ref, repr) = tuple
      res <- f(repr, ref.read)
      _ <- ref.delete.toProg
    } yield res
  }

  def check(sys: System, thyName: String)(implicit A: Codec[A], ec: ExecutionContext): CancelableFuture[ProverResult[Option[String]]] = {
    val _ = ec
    sys.invoke(Expr.Check)((Codec[A].mlType, this, thyName))
  }

  def coerce[B]: Expr[B] = Expr.Coerce(this)

}

object Expr {

  implicit class ExprFunOps[B, C](fun: Expr[B => C]) {
    def apply(arg: Expr[B]): Expr[C] =
      App(fun, arg)
    def apply(b: B)(implicit B: Codec[B]): Expr[C] =
      apply(value(b))
    def liftTry: Expr[B => Option[C]] =
      uncheckedLiteral[(B => C) => B => Option[C]]("try")(fun)
    def andThen[D](fun2: Expr[C => D]): Expr[B => D] =
      uncheckedLiteral[(B => C) => (C => D) => B => D]("(fn f => fn g => g o f)")(fun)(fun2)
  }

  private case class Lit[A](text: String) extends Expr[A]
  private case class App[T, U](f: Expr[T => U], x: Expr[T]) extends Expr[U]
  private case class Val[T](t: T)(implicit val T: Codec[T]) extends Expr[T]
  private case class Coerce[T, U](t: Expr[T]) extends Expr[U]

  def value[T](t: T)(implicit T: Codec[T]): Expr[T] = Val[T](t)
  def uncheckedLiteral[A](text: String): Expr[A] = Lit[A](text)

  private implicit lazy val exprCodec: Codec[Expr[_]] = new Codec.Variant[Expr[_]]("ML_Expr.ml_expr") {
    val mlType = "ML_Expr.ml_expr"
    protected def dec(idx: Int) = None
    protected def enc(expr: Expr[_]) = expr match {
      case Lit(text) => (0, Codec[String].encode(text))
      case App(f, x) => (1, (exprCodec tuple exprCodec).encode((f, x)))
      case v: Val[_] => (2, Codec[(String, XML.Tree)].encode((v.T.mlType, v.T.encode(v.t))))
      case Coerce(t) => enc(t)
    }
  }

  private val Eval = Operation.implicitly[(String, Expr[_], String), XML.Tree]("eval_expr")
  private val EvalOpaque = Operation.implicitly[((String, String, Expr[_]), Expr[_], String), (BigInt, XML.Tree)]("eval_opaque_expr")
  private val Check = Operation.implicitly[(String, Expr[_], String), Option[String]]("check_expr")

} 
Example 7
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 8
Source File: form_data_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package form_data


    import java.io.File
    import scala.math.BigInt

    import de.zalando.play.controllers.PlayPathBindables


//noinspection ScalaStyle
package yaml {


    case class MultipartPostResponses200(name: BothPostResponses200Name, year: BothPostYear, fileSize: BothPostYear, fileName: BothPostResponses200Name) 
    case class BothPostResponses200(name: BothPostResponses200Name, year: BothPostYear, avatarSize: BothPostYear, ringtoneSize: BothPostYear) 


    import play.api.libs.json._
    import play.api.libs.functional.syntax._
    import de.zalando.play.controllers.MissingDefaultWrites
    object ResponseWrites extends MissingDefaultWrites {
    implicit val BothPostResponses200Writes: Writes[BothPostResponses200] = new Writes[BothPostResponses200] {
        def writes(ss: BothPostResponses200) =
          Json.obj(
            "name" -> ss.name, 
            "year" -> ss.year, 
            "avatarSize" -> ss.avatarSize, 
            "ringtoneSize" -> ss.ringtoneSize
          )
        }
    implicit val MultipartPostResponses200Writes: Writes[MultipartPostResponses200] = new Writes[MultipartPostResponses200] {
        def writes(ss: MultipartPostResponses200) =
          Json.obj(
            "name" -> ss.name, 
            "year" -> ss.year, 
            "fileSize" -> ss.fileSize, 
            "fileName" -> ss.fileName
          )
        }
    }
}

// should be defined after the package because of the https://issues.scala-lang.org/browse/SI-9922

//noinspection ScalaStyle
package object yaml {

    type MultipartPostAvatar = Option[File]
    type BothPostResponses200Name = Option[String]
    type BothPostYear = Option[BigInt]


import play.api.mvc.{QueryStringBindable, PathBindable}

    implicit val bindable_FileQuery = PlayPathBindables.queryBindableFile
    implicit val bindable_BigIntQuery = PlayPathBindables.queryBindableBigInt
    implicit val bindable_OptionFileQuery: QueryStringBindable[Option[File]] = PlayPathBindables.createOptionQueryBindable[File]
    implicit val bindable_OptionBigIntQuery: QueryStringBindable[Option[BigInt]] = PlayPathBindables.createOptionQueryBindable[BigInt]

} 
Example 9
Source File: i041_no_json_deserialiser_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package i041_no_json_deserialiser


    import java.time.ZonedDateTime
    import scala.math.BigDecimal
    import scala.math.BigInt

    import de.zalando.play.controllers.PlayPathBindables


//noinspection ScalaStyle
package yaml {


    case class Money(id: UserId, userId: UserId, amount: MoneyAmount, createDate: MoneyCreateDate) 
    case class User(id: UserId, name: UserName, money: UserMoney) 
    case class UserMoney(id: UserId, userId: UserId, amount: MoneyAmount, createDate: MoneyCreateDate) 
    case class Error(code: Int, message: String) 


    import play.api.libs.json._
    import play.api.libs.functional.syntax._
    import de.zalando.play.controllers.MissingDefaultReads
    object BodyReads extends MissingDefaultReads {
        implicit val MoneyReads: Reads[Money] = (
            (JsPath \ "id").readNullable[Long] and (JsPath \ "userId").readNullable[Long] and (JsPath \ "amount").readNullable[BigDecimal] and (JsPath \ "createDate").readNullable[ZonedDateTime]
        )(Money.apply _)
        implicit val UserMoneyReads: Reads[UserMoney] = (
            (JsPath \ "id").readNullable[Long] and (JsPath \ "userId").readNullable[Long] and (JsPath \ "amount").readNullable[BigDecimal] and (JsPath \ "createDate").readNullable[ZonedDateTime]
        )(UserMoney.apply _)
        implicit val UserReads: Reads[User] = (
            (JsPath \ "id").readNullable[Long] and (JsPath \ "name").readNullable[String] and (JsPath \ "money").read[UserMoney]
        )(User.apply _)
    }

    import play.api.libs.json._
    import play.api.libs.functional.syntax._
    import de.zalando.play.controllers.MissingDefaultWrites
    object ResponseWrites extends MissingDefaultWrites {
    implicit val MoneyWrites: Writes[Money] = new Writes[Money] {
        def writes(ss: Money) =
          Json.obj(
            "id" -> ss.id, 
            "userId" -> ss.userId, 
            "amount" -> ss.amount, 
            "createDate" -> ss.createDate
          )
        }
    implicit val UserMoneyWrites: Writes[UserMoney] = new Writes[UserMoney] {
        def writes(ss: UserMoney) =
          Json.obj(
            "id" -> ss.id, 
            "userId" -> ss.userId, 
            "amount" -> ss.amount, 
            "createDate" -> ss.createDate
          )
        }
    implicit val UserWrites: Writes[User] = new Writes[User] {
        def writes(ss: User) =
          Json.obj(
            "id" -> ss.id, 
            "name" -> ss.name, 
            "money" -> ss.money
          )
        }
    }
}

// should be defined after the package because of the https://issues.scala-lang.org/browse/SI-9922

//noinspection ScalaStyle
package object yaml {

    type MoneyCreateDate = Option[ZonedDateTime]
    type UserId = Option[Long]
    type MoneyAmount = Option[BigDecimal]
    type UserName = Option[String]
    type UserGetResponses200 = Seq[User]


import play.api.mvc.{QueryStringBindable, PathBindable}

    implicit val bindable_BigIntPath = PlayPathBindables.pathBindableBigInt

} 
Example 10
Source File: form_data_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package form_data.yaml

import play.api.libs.Files.TemporaryFile
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc.{AnyContent, Request}
import de.zalando.play.controllers.PlayBodyParsing

import java.io.File
import scala.math.BigInt

import de.zalando.play.controllers.PlayPathBindables


object FormDataParser {

    def postmultipartParseForm(request: Request[AnyContent]):Either[Seq[String],(String, BothPostYear, MultipartPostAvatar)] = {
        val contentType = request.contentType.getOrElse("application/x-www-form-urlencoded")
        def fromDataParts(data: Map[String, Seq[String]], files: Map[String, Option[FilePart[TemporaryFile]]], useFiles: Boolean):Either[Seq[String],(String, BothPostYear, MultipartPostAvatar)] = {
            val name: Either[String,String] = PlayBodyParsing.fromParameters[String]("form")("name", data)
            val year: Either[String,BothPostYear] = PlayBodyParsing.fromParameters[BothPostYear]("form")("year", data)
            val avatar: Either[String,MultipartPostAvatar] = if (useFiles) PlayBodyParsing.fromFileOptional("avatar", files("avatar")) else PlayBodyParsing.fromParameters[MultipartPostAvatar]("form")("avatar", data)
            val all = Seq(name, year, avatar)
            val errors = all.filter(_.isLeft).flatMap(_.left.toSeq)
            if (errors.nonEmpty) Left(errors) else Right((name.right.toOption.get, year.right.toOption.get, avatar.right.toOption.get))
        }
        contentType.toLowerCase match {
            
            case "multipart/form-data" => request.body.asMultipartFormData.map { form =>
                val files: Map[String, Option[FilePart[TemporaryFile]]] =
                (("avatar", form.file("avatar")) :: Nil).toMap
                fromDataParts(form.dataParts, files, useFiles = true)
            }.getOrElse(Left(Seq("Could not find 'multipart/form-data' body")))
            
            case other =>
                Left(Seq("Content type " + other + " is not supported"))
        }
    }


    def postbothParseForm(request: Request[AnyContent]):Either[Seq[String],(String, BothPostYear, MultipartPostAvatar, File)] = {
        val contentType = request.contentType.getOrElse("application/x-www-form-urlencoded")
        def fromDataParts(data: Map[String, Seq[String]], files: Map[String, Option[FilePart[TemporaryFile]]], useFiles: Boolean):Either[Seq[String],(String, BothPostYear, MultipartPostAvatar, File)] = {
            val name: Either[String,String] = PlayBodyParsing.fromParameters[String]("form")("name", data)
            val year: Either[String,BothPostYear] = PlayBodyParsing.fromParameters[BothPostYear]("form")("year", data)
            val avatar: Either[String,MultipartPostAvatar] = if (useFiles) PlayBodyParsing.fromFileOptional("avatar", files("avatar")) else PlayBodyParsing.fromParameters[MultipartPostAvatar]("form")("avatar", data)
            val ringtone: Either[String,File] = if (useFiles) PlayBodyParsing.fromFileRequired("ringtone", files("ringtone")) else PlayBodyParsing.fromParameters[File]("form")("ringtone", data)
            val all = Seq(name, year, avatar, ringtone)
            val errors = all.filter(_.isLeft).flatMap(_.left.toSeq)
            if (errors.nonEmpty) Left(errors) else Right((name.right.toOption.get, year.right.toOption.get, avatar.right.toOption.get, ringtone.right.toOption.get))
        }
        contentType.toLowerCase match {
            case "application/x-www-form-urlencoded" => request.body.asFormUrlEncoded.map { form =>
                val noFiles = Map.empty[String, Option[FilePart[TemporaryFile]]]
                fromDataParts(form, noFiles, useFiles = false)
            }.getOrElse(Left(Seq("Could not find 'application/x-www-form-urlencoded' body")))
            
            case "multipart/form-data" => request.body.asMultipartFormData.map { form =>
                val files: Map[String, Option[FilePart[TemporaryFile]]] =
                (("avatar", form.file("avatar")) :: ("ringtone", form.file("ringtone")) :: Nil).toMap
                fromDataParts(form.dataParts, files, useFiles = true)
            }.getOrElse(Left(Seq("Could not find 'multipart/form-data' body")))
            
            case other =>
                Left(Seq("Content type " + other + " is not supported"))
        }
    }


    def posturl_encodedParseForm(request: Request[AnyContent]):Either[Seq[String],(String, BothPostYear, File)] = {
        val contentType = request.contentType.getOrElse("application/x-www-form-urlencoded")
        def fromDataParts(data: Map[String, Seq[String]], files: Map[String, Option[FilePart[TemporaryFile]]], useFiles: Boolean):Either[Seq[String],(String, BothPostYear, File)] = {
            val name: Either[String,String] = PlayBodyParsing.fromParameters[String]("form")("name", data)
            val year: Either[String,BothPostYear] = PlayBodyParsing.fromParameters[BothPostYear]("form")("year", data)
            val avatar: Either[String,File] = if (useFiles) PlayBodyParsing.fromFileRequired("avatar", files("avatar")) else PlayBodyParsing.fromParameters[File]("form")("avatar", data)
            val all = Seq(name, year, avatar)
            val errors = all.filter(_.isLeft).flatMap(_.left.toSeq)
            if (errors.nonEmpty) Left(errors) else Right((name.right.toOption.get, year.right.toOption.get, avatar.right.toOption.get))
        }
        contentType.toLowerCase match {
            case "application/x-www-form-urlencoded" => request.body.asFormUrlEncoded.map { form =>
                val noFiles = Map.empty[String, Option[FilePart[TemporaryFile]]]
                fromDataParts(form, noFiles, useFiles = false)
            }.getOrElse(Left(Seq("Could not find 'application/x-www-form-urlencoded' body")))
            
            case other =>
                Left(Seq("Content type " + other + " is not supported"))
        }
    }

} 
Example 11
Source File: i041_no_json_deserialiser_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package i041_no_json_deserialiser.yaml

import org.scalacheck.Gen
import org.scalacheck.Arbitrary
import play.api.libs.json.scalacheck.JsValueGenerators
import Arbitrary._
import java.time.ZonedDateTime
import scala.math.BigDecimal
import scala.math.BigInt

object Generators extends JsValueGenerators {
    

    
    def createMoneyCreateDateGenerator = _generate(MoneyCreateDateGenerator)
    def createUserIdGenerator = _generate(UserIdGenerator)
    def createMoneyAmountGenerator = _generate(MoneyAmountGenerator)
    def createBigIntGenerator = _generate(BigIntGenerator)
    def createUserNameGenerator = _generate(UserNameGenerator)
    def createStringGenerator = _generate(StringGenerator)
    def createUserGetResponses200Generator = _generate(UserGetResponses200Generator)
    

    
    def MoneyCreateDateGenerator = Gen.option(arbitrary[ZonedDateTime])
    def UserIdGenerator = Gen.option(arbitrary[Long])
    def MoneyAmountGenerator = Gen.option(arbitrary[BigDecimal])
    def BigIntGenerator = arbitrary[BigInt]
    def UserNameGenerator = Gen.option(arbitrary[String])
    def StringGenerator = arbitrary[String]
    def UserGetResponses200Generator: Gen[List[User]] = Gen.containerOf[List,User](UserGenerator)
    

    def createMoneyGenerator = _generate(MoneyGenerator)
    def createUserGenerator = _generate(UserGenerator)
    def createUserMoneyGenerator = _generate(UserMoneyGenerator)
    def createErrorGenerator = _generate(ErrorGenerator)


    def MoneyGenerator = for {
        id <- UserIdGenerator
        userId <- UserIdGenerator
        amount <- MoneyAmountGenerator
        createDate <- MoneyCreateDateGenerator
    } yield Money(id, userId, amount, createDate)
    def UserGenerator = for {
        id <- UserIdGenerator
        name <- UserNameGenerator
        money <- UserMoneyGenerator
    } yield User(id, name, money)
    def UserMoneyGenerator = for {
        id <- UserIdGenerator
        userId <- UserIdGenerator
        amount <- MoneyAmountGenerator
        createDate <- MoneyCreateDateGenerator
    } yield UserMoney(id, userId, amount, createDate)
    def ErrorGenerator = for {
        code <- arbitrary[Int]
        message <- arbitrary[String]
    } yield Error(code, message)

    def _generate[T](gen: Gen[T]) = (count: Int) => for (i <- 1 to count) yield gen.sample

    
    
    implicit lazy val arbDateTime: Arbitrary[ZonedDateTime] = Arbitrary(for {
        d <- arbitrary[java.util.Date]
    } yield ZonedDateTime.ofInstant(d.toInstant, java.time.ZoneId.systemDefault()))
    
    
    

} 
Example 12
Source File: cross_spec_references_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package cross_spec_references.yaml

import org.scalacheck.Gen
import org.scalacheck.Arbitrary
import play.api.libs.json.scalacheck.JsValueGenerators
import Arbitrary._
import scala.math.BigInt

object Generators extends JsValueGenerators {
    

    
    def createMetaCopyrightGenerator = _generate(MetaCopyrightGenerator)
    def createModelSchemaKeywordsGenerator = _generate(ModelSchemaKeywordsGenerator)
    def createModelSchemaSpecialDescriptionsGenerator = _generate(ModelSchemaSpecialDescriptionsGenerator)
    def createModelSchemaRootDataGenerator = _generate(ModelSchemaRootDataGenerator)
    def createPetIdGenerator = _generate(PetIdGenerator)
    def createModelSchemaRootLinksGenerator = _generate(ModelSchemaRootLinksGenerator)
    def createPetTagsGenerator = _generate(PetTagsGenerator)
    def createModelSchemaSilhouetteIdGenerator = _generate(ModelSchemaSilhouetteIdGenerator)
    def createPetPhotoUrlsGenerator = _generate(PetPhotoUrlsGenerator)
    def createModelSchemaLengthRegisterGenerator = _generate(ModelSchemaLengthRegisterGenerator)
    def createModelSchemaAgeGroupsGenerator = _generate(ModelSchemaAgeGroupsGenerator)
    def createPetCategoryGenerator = _generate(PetCategoryGenerator)
    def createModelSchemaAgeGroupsArrResultGenerator = _generate(ModelSchemaAgeGroupsArrResultGenerator)
    def createPetTagsOptGenerator = _generate(PetTagsOptGenerator)
    def createModelSchemaRootMetaGenerator = _generate(ModelSchemaRootMetaGenerator)
    

    
    def MetaCopyrightGenerator = Gen.option(arbitrary[String])
    def ModelSchemaKeywordsGenerator = Gen.option(arbitrary[String])
    def ModelSchemaSpecialDescriptionsGenerator = Gen.option(PetPhotoUrlsGenerator)
    def ModelSchemaRootDataGenerator = Gen.option(ModelSchemaRootDataOptGenerator)
    def PetIdGenerator = Gen.option(arbitrary[Long])
    def ModelSchemaRootLinksGenerator = Gen.option(ModelSchemaRootLinksOptGenerator)
    def PetTagsGenerator = Gen.option(PetTagsOptGenerator)
    def ModelSchemaSilhouetteIdGenerator = { import ModelSchemaSilhouetteId._ ; Gen.oneOf(Seq(Kitchen, Bikini_top, Toys, Nightwear_combination, Bra, One_piece_underwear, Ball, Cleansing, Skincare, Jewellery, Headgear, Bustier, Beach_trouser, Bedroom, Lounge, Nail, Undershirt, Combination_clothing, Gloves, Fragrance, Other_equipment, Fitness, Bathroom, One_piece_nightwear, Sleeping_bag, Coat, Case, Sandals, Ankle_boots, Stocking, Shirt, Backpack, Face_cosmetic, Travel_equipment, Hair, Sneaker, Beauty_equipment, Bikini_combination, Backless_slipper, Beach_accessoires, Scarf, First_shoe, Voucher, Wallet, Peeling, Glasses, Boards, Sun, Shave, Low_shoe, Underwear_combination, Nightdress, Suit_accessoires, Watch, Headphones, Skates, Boots, Jacket, Etui, Night_shirt, Other_accessoires, Vest, Bag, System, Racket, Trouser, Lip_cosmetic, Keychain, Belt, Ballerina_shoe, One_piece_suit, Night_trouser, Skirt, Tights, Beach_shirt, Dress, Bicycle, Protector, Eye_cosmetic, Bathrobe, Bicycle_equipment, Pullover, One_piece_beachwear, Underpant, Living, Cardigan, Corsage, Shoe_accessoires, Umbrella, Pumps, Tent, T_shirt_top, Ski)) }
    def PetPhotoUrlsGenerator: Gen[List[String]] = Gen.containerOf[List,String](arbitrary[String])
    def ModelSchemaLengthRegisterGenerator = Gen.option(arbitrary[String])
    def ModelSchemaAgeGroupsGenerator: Gen[List[ModelSchemaAgeGroupsArrResult]] = Gen.containerOf[List,ModelSchemaAgeGroupsArrResult](ModelSchemaAgeGroupsArrResultGenerator)
    def PetCategoryGenerator = Gen.option(PetCategoryOptGenerator)
    def ModelSchemaAgeGroupsArrResultGenerator = { import ModelSchemaAgeGroupsArrResult._ ; Gen.oneOf(Seq(Baby, Kid, Teen, Adult)) }
    def PetTagsOptGenerator: Gen[List[PetCategoryOpt]] = Gen.containerOf[List,PetCategoryOpt](PetCategoryOptGenerator)
    def ModelSchemaRootMetaGenerator = Gen.option(ModelSchemaRootMetaOptGenerator)
    

    def createPetCategoryOptGenerator = _generate(PetCategoryOptGenerator)
    def createModelSchemaRootDataOptGenerator = _generate(ModelSchemaRootDataOptGenerator)
    def createModelSchemaRootMetaOptGenerator = _generate(ModelSchemaRootMetaOptGenerator)
    def createModelSchemaRootGenerator = _generate(ModelSchemaRootGenerator)
    def createPetGenerator = _generate(PetGenerator)
    def createModelSchemaRootLinksOptGenerator = _generate(ModelSchemaRootLinksOptGenerator)


    def PetCategoryOptGenerator = for {
        id <- PetIdGenerator
        name <- MetaCopyrightGenerator
    } yield PetCategoryOpt(id, name)
    def ModelSchemaRootDataOptGenerator = for {
        name <- arbitrary[String]
        sizeRegister <- arbitrary[String]
        brand <- arbitrary[String]
        partnerArticleModelId <- arbitrary[BigInt]
        description <- MetaCopyrightGenerator
        ageGroups <- ModelSchemaAgeGroupsGenerator
        keywords <- ModelSchemaKeywordsGenerator
        lengthRegister <- ModelSchemaLengthRegisterGenerator
        silhouetteId <- ModelSchemaSilhouetteIdGenerator
        specialDescriptions <- ModelSchemaSpecialDescriptionsGenerator
        articleModelAttributes <- ModelSchemaSpecialDescriptionsGenerator
    } yield ModelSchemaRootDataOpt(name, sizeRegister, brand, partnerArticleModelId, description, ageGroups, keywords, lengthRegister, silhouetteId, specialDescriptions, articleModelAttributes)
    def ModelSchemaRootMetaOptGenerator = for {
        copyright <- MetaCopyrightGenerator
    } yield ModelSchemaRootMetaOpt(copyright)
    def ModelSchemaRootGenerator = for {
        data <- ModelSchemaRootDataGenerator
        meta <- ModelSchemaRootMetaGenerator
        links <- ModelSchemaRootLinksGenerator
    } yield ModelSchemaRoot(data, meta, links)
    def PetGenerator = for {
        name <- arbitrary[String]
        tags <- PetTagsGenerator
        photoUrls <- PetPhotoUrlsGenerator
        id <- PetIdGenerator
        status <- MetaCopyrightGenerator
        category <- PetCategoryGenerator
    } yield Pet(name, tags, photoUrls, id, status, category)
    def ModelSchemaRootLinksOptGenerator = for {
        self <- MetaCopyrightGenerator
        related <- MetaCopyrightGenerator
    } yield ModelSchemaRootLinksOpt(self, related)

    def _generate[T](gen: Gen[T]) = (count: Int) => for (i <- 1 to count) yield gen.sample

    
    
    
    

} 
Example 13
Source File: catalog_manager.yaml.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package catalog_manager.yaml

import de.zalando.play.controllers.ResponseWriters

import scala.concurrent.Future
import play.api.mvc._
import de.zalando.play.controllers.SwaggerSecurityExtractors._
import catalog_manager.yaml
import play.api.libs.json.JsValue

import scala.math.BigInt



object SecurityExtractorsExecutionContext {
    // this ExecutionContext might be overridden if default configuration is not suitable for some reason
    implicit val ec = de.zalando.play.controllers.Contexts.tokenChecking
}

trait SecurityExtractors {
    def basicAuth_Extractor[User >: Any](): RequestHeader => Future[Option[User]] =
        header => basicAuth(header) { (username: String, password: String) =>
            userFromToken("abracadabra")
    }


    implicit val unauthorizedContentWriter = ResponseWriters.choose[String]("application/json")
    def unauthorizedContent(req: RequestHeader) = Results.Unauthorized("Unauthorized")

     def userFromToken[User >: Any](token: String): User = {
         Token(Some(token))
         // Gettest200(token)
         //controllers_base. Gettest200(Token(Some(token)))
    }
} 
Example 14
Source File: heroku_petstore_api_yaml.scala    From api-first-hand   with MIT License 5 votes vote down vote up
package heroku.petstore.api.yaml
import play.api.mvc.{Action, Controller}
import play.api.data.validation.Constraint
import de.zalando.play.controllers._
import PlayBodyParsing._
import PlayValidations._

import scala.math.BigInt
// ----- constraints and wrapper validations -----
class PetIdGetPetIdConstraints(override val instance: String) extends ValidationBase[String] {
    override val reference = "⌿paths⌿/{petId}⌿get⌿petId"
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class PetIdGetPetIdValidator(instance: String) extends RecursiveValidator {
    override val reference = "⌿paths⌿/{petId}⌿get⌿petId"
    override val validators = Seq(new PetIdGetPetIdConstraints(instance))
}
class PetNameOptConstraints(override val instance: String) extends ValidationBase[String] {
    override val reference = "⌿definitions⌿Pet⌿name⌿Opt"
    override def constraints: Seq[Constraint[String]] =
        Seq(maxLength(100), minLength(3))
}
class PetNameOptValidator(instance: String) extends RecursiveValidator {
    override val reference = "⌿definitions⌿Pet⌿name⌿Opt"
    override val validators = Seq(new PetNameOptConstraints(instance))
}
class PetBirthdayOptConstraints(override val instance: Int) extends ValidationBase[Int] {
    override val reference = "⌿definitions⌿Pet⌿birthday⌿Opt"
    override def constraints: Seq[Constraint[Int]] =
        Seq(max(100.toInt, false), min(1.toInt, false))
}
class PetBirthdayOptValidator(instance: Int) extends RecursiveValidator {
    override val reference = "⌿definitions⌿Pet⌿birthday⌿Opt"
    override val validators = Seq(new PetBirthdayOptConstraints(instance))
}
class GetLimitConstraints(override val instance: BigInt) extends ValidationBase[BigInt] {
    override val reference = "⌿paths⌿/⌿get⌿limit"
    override def constraints: Seq[Constraint[BigInt]] =
        Seq(max(BigInt("10000"), false), min(BigInt("11"), false))
}
class GetLimitValidator(instance: BigInt) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿get⌿limit"
    override val validators = Seq(new GetLimitConstraints(instance))
}
// ----- complex type validators -----
class PetValidator(instance: Pet) extends RecursiveValidator {
    override val reference = "⌿definitions⌿Pet"
    override val validators = Seq(
        new PetNameValidator(instance.name), 
        new PetBirthdayValidator(instance.birthday)
    )
}

// ----- option delegating validators -----
class PetNameValidator(instance: PetName) extends RecursiveValidator {
    override val reference = "⌿definitions⌿Pet⌿name"
    override val validators = instance.toSeq.map { new PetNameOptValidator(_) }
}
class PetBirthdayValidator(instance: PetBirthday) extends RecursiveValidator {
    override val reference = "⌿definitions⌿Pet⌿birthday"
    override val validators = instance.toSeq.map { new PetBirthdayOptValidator(_) }
}
class PutPetValidator(instance: PutPet) extends RecursiveValidator {
    override val reference = "⌿paths⌿/⌿put⌿pet"
    override val validators = instance.toSeq.map { new PetValidator(_) }
}
// ----- array delegating validators -----
// ----- catch all simple validators -----
// ----- composite validators -----
// ----- call validations -----
class PutValidator(pet: PutPet) extends RecursiveValidator {
    override val reference = "⌿paths⌿⌿put"
    override val validators = Seq(
        new PutPetValidator(pet)
    
    )
}
class GetValidator(limit: BigInt) extends RecursiveValidator {
    override val reference = "⌿paths⌿⌿get"
    override val validators = Seq(
        new GetLimitValidator(limit)
    
    )
}
class PetIdGetValidator(petId: String) extends RecursiveValidator {
    override val reference = "⌿paths⌿{petId}⌿get"
    override val validators = Seq(
        new PetIdGetPetIdValidator(petId)
    
    )
}
class PostValidator(pet: Pet) extends RecursiveValidator {
    override val reference = "⌿paths⌿⌿post"
    override val validators = Seq(
        new PetValidator(pet)
    
    )
} 
Example 15
Source File: HPASSpec.scala    From skuber   with Apache License 2.0 5 votes vote down vote up
package skuber.autoscaling
import org.specs2.mutable.Specification

import scala.math.BigInt
import skuber.{Container, ObjectMeta, Pod, ReplicationController}
import play.api.libs.json._
import skuber.autoscaling.HorizontalPodAutoscaler.CrossVersionObjectReference


class HPASSpec extends Specification {
  "This is a unit specification for the skuber HorizontalPodAutoscaler class. ".txt
  
  "A HPAS object can be constructed from the object it scales\n" >> {
    "A HPAS can be constructed from a replication controller" >> {
      val container=Container(name="example",image="example")
      val rc=ReplicationController("example", container, Map("app" -> "example"))
      val hpas=HorizontalPodAutoscaler.scale(rc).
                    withMinReplicas(1).
                    withMaxReplicas(10).
                    withCPUTargetUtilization(80)
      hpas.name mustEqual "example"
      hpas.spec.scaleTargetRef.kind mustEqual "ReplicationController"
      hpas.spec.maxReplicas must_== 10
      hpas.spec.minReplicas must beSome(1)
      hpas.spec.cpuUtilization mustEqual Some(CPUTargetUtilization(80))
    }
  }

  "A HPAS object properly writes with zero minReplicas" >> {
    val hpas=HorizontalPodAutoscaler(
      metadata = ObjectMeta("example"),
      spec = HorizontalPodAutoscaler.Spec(
        scaleTargetRef = CrossVersionObjectReference(name="example")
      )
    ).withMaxReplicas(0).withMinReplicas(0)

    val writeHPAS = Json.toJson(hpas)
    (writeHPAS \ "spec" \ "minReplicas").asOpt[Int] must beSome(0)
    (writeHPAS \ "spec" \ "maxReplicas").asOpt[Int] must beSome(0)
  }
} 
Example 16
Source File: ResourceSpec.scala    From skuber   with Apache License 2.0 5 votes vote down vote up
package skuber

import org.specs2.mutable.Specification // for unit-style testing

import scala.math.BigInt



class ResourceSpec extends Specification {
  "This is a unit specification for the skuber Resource model. ".txt
  
  // Resource type
  "A resource quantity can be constructed from decimal SI values\n" >> {
    "where a value of 100m equates to 0.1" >> { Resource.Quantity("100m").amount mustEqual 0.1 }
    "where a value of 100k equates to 100000" >> { Resource.Quantity("100k").amount mustEqual 100000 }
    "where a value of 100M equates to 100000000" >> { Resource.Quantity("100M").amount mustEqual 100000000 }
    "where a value of 100G equates to 100E+9" >> { Resource.Quantity("100G").amount mustEqual 100E+9 }
    "where a value of 100T equates to 100E+12" >> { Resource.Quantity("100T").amount mustEqual 100E+12 }
    "where a value of 100P equates to 100E+15" >> { Resource.Quantity("100P").amount mustEqual 100E+15 }
    "where a value of 100E equates to 100E+18" >> { Resource.Quantity("100E").amount mustEqual 100E+18 }
  }
  
  "A resource quantity can be constructed from values with scientific E notation\n" >> {
    "where a value of 0.01E+5 equates to 1000" >> { Resource.Quantity("0.01E+5").amount mustEqual 1000 }
    "where a value of 10010.56E-3 equates to 10.01056" >> { Resource.Quantity("10010.56E-3").amount mustEqual 10.01056 }
    "where a value of 55.67e+6 equates to 55670000" >> { Resource.Quantity("55.67e+6").amount mustEqual 55670000 }
    "where a value of 5e+3 equates to 5000" >> { Resource.Quantity("5e+3").amount mustEqual 5000 }
    "where a value of 67700e-33 equates to 67.700" >> { Resource.Quantity("67700e-3").amount mustEqual 67.700 }
  }
  
  "A resource quantity can be constructed from binary SI values\n" >> {
    "where a value of 100Ki equates to 102400" >> { Resource.Quantity("100Ki").amount mustEqual 102400 }
    "where a value of 10Mi equates to 10485760" >> { Resource.Quantity("10Mi").amount mustEqual 10485760 }    
    "where a value of 10Ti equates to 10 *(2 ^ 40) " >> { Resource.Quantity("10Ti").amount mustEqual 10 * Math.pow(2,40) }
    "where a value of 10Pi equates to 10 *(2 ^ 50) " >> { Resource.Quantity("10Pi").amount mustEqual 10 * Math.pow(2,50) }
    "where a value of 10Ei equates to 10 *(2 ^ 60) " >> { 
      val mult = new java.math.BigInteger("10") 
      val base = new java.math.BigInteger("2")
      val value = base.pow(60).multiply(mult)
      val decValue = scala.math.BigDecimal(new java.math.BigDecimal(value))
      System.err.println("....10Ei = " + decValue)
      Resource.Quantity("10Ei").amount mustEqual decValue
    }    
  }
  
  "A resource quantity can be constructed for plain integer and decimal values with no suffixes\n" >> {
    "where a value of 10 is valid" >> { Resource.Quantity("10").amount mustEqual 10 }
    "where a value of -10 is valid" >> { Resource.Quantity("-10").amount mustEqual -10 }
    "where a value of 10.55 is valid" >> { Resource.Quantity("10.55").amount mustEqual 10.55 }
    "where a value of -10.55 is valid" >> { Resource.Quantity("-10.55").amount mustEqual -10.55 }
  }
  
  "A resource quantity will reject bad values\n" >> {
    "where constructing from a value of 10Zi results in an exception" >> 
      { 
        def badVal = Resource.Quantity("10Zi").amount 
        badVal must throwAn[Exception] 
      }
  }
    
} 
Example 17
Source File: ModelSpec.scala    From skuber   with Apache License 2.0 5 votes vote down vote up
package skuber

import org.specs2.mutable.Specification // for unit-style testing

import scala.math.BigInt



class ModelSpec extends Specification {
  "This is a unit specification for the skuber data model. ".txt
  
  
  // Pod(s)
  "A Pods type can be constructed from lists of Pods\n" >> {
    "where an empty list of pods can be used" >> {
      val podList = List[Pod]()
      val pods=PodList(items = podList)
      pods.items.size mustEqual 0
    }
    
    "where a list with a single pod can be used" >> {
      val container1=Container(name="Container1","image1")
      val container2=Container(name="Container2","image2")
      val podspec=Pod.Spec(volumes=Nil, containers=List(container1, container2), serviceAccountName="")
      val pod=Pod("MyPod", podspec)
      val podList = List[Pod](pod)
      val pods=PodList(items = podList)
      pods.items.size mustEqual 1
      pods.items(0).metadata.name mustEqual "MyPod"
    }    
  }   
   // ReplicationController(s)
  "A ReplicationControllers type can be constructed from a list of ReplicationController (a.k.a. RC)\n" >> {
    "where an empty list of RCs can be used" >> {
      val rcList = List[ReplicationController]()
      val rcs=ReplicationControllerList(items = rcList)
      rcs.items.size mustEqual 0
    }
    
    "where a list with a single RC can be used" >> {
      val container1=Container("Container1","image1")
      val container2=Container(name="Container2", "image2")
      val podspec=Pod.Spec(containers=List(container1, container2))
      val rc = ReplicationController("MyRepCon").withReplicas(2).withPodSpec(podspec)
      val rcList = List[ReplicationController](rc)
      val rcs=ReplicationControllerList(items = rcList)
      rcs.items.size mustEqual 1
      rcs.items(0).metadata.name mustEqual "MyRepCon"
      rcs(0).name mustEqual "MyRepCon"
      rcs(0).spec.get.replicas mustEqual 2
      val pspec = for (
          rcspec <- rcs(0).spec;
          tmpl <- rcspec.template;
          podspec <- tmpl.spec
      ) yield(podspec)
      pspec.get.containers.size mustEqual 2
    }    
  }   
} 
Example 18
Source File: EnvVarSpec.scala    From skuber   with Apache License 2.0 5 votes vote down vote up
package skuber.json

import org.specs2.mutable.Specification // for unit-style testing
import org.specs2.execute.Result
import org.specs2.execute.Failure
import org.specs2.execute.Success

import scala.math.BigInt

import java.util.Calendar

import skuber.EnvVar
import format._

import play.api.libs.json._

class EnvVarSpec extends Specification {
  "This is a unit specification for the skuber formatter for env vars.\n ".txt

  // EnvVar reader and writer
  "An EnvVar can be read from json\n" >> {
    "this can be done for an env var with a field ref with a field path" >> {
      val env1 = Json.fromJson[EnvVar](Json.parse(
        """
          |{
          |  "name": "PODNAME",
          |  "valueFrom" : {
          |     "fieldRef": {
          |       "fieldPath": "metadata.name"
          |     }
          |  }
          |}
        """.stripMargin)).get

      val env2 = EnvVar("PODNAME", EnvVar.FieldRef("metadata.name"))

      env1 mustEqual env2
    }
  }
} 
Example 19
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 20
Source File: heroku_petstore_api_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
import play.api.mvc.{Action, Controller}

import play.api.data.validation.Constraint

import de.zalando.play.controllers._

import PlayBodyParsing._

import PlayValidations._

import scala.util._

import scala.math.BigInt




package heroku.petstore.api.yaml {

    class HerokuPetstoreApiYaml extends HerokuPetstoreApiYamlBase {
        val get = getAction { (limit: BigInt) =>  
            // ----- Start of unmanaged code area for action  HerokuPetstoreApiYaml.get
            NotImplementedYet
            // ----- End of unmanaged code area for action  HerokuPetstoreApiYaml.get
        }
        val put = putAction { (pet: PutPet) =>  
            // ----- Start of unmanaged code area for action  HerokuPetstoreApiYaml.put
            NotImplementedYet
            // ----- End of unmanaged code area for action  HerokuPetstoreApiYaml.put
        }
        val post = postAction { (pet: Pet) =>  
            // ----- Start of unmanaged code area for action  HerokuPetstoreApiYaml.post
            NotImplementedYet
            // ----- End of unmanaged code area for action  HerokuPetstoreApiYaml.post
        }
        val getbyPetId = getbyPetIdAction { (petId: String) =>  
            // ----- Start of unmanaged code area for action  HerokuPetstoreApiYaml.getbyPetId
            NotImplementedYet
            // ----- End of unmanaged code area for action  HerokuPetstoreApiYaml.getbyPetId
        }
    
    }
} 
Example 21
Source File: form_data_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
package form_data.yaml

import play.api.libs.Files.TemporaryFile
import play.api.mvc.MultipartFormData.FilePart
import play.api.mvc.{AnyContent, Request}
import de.zalando.play.controllers.PlayBodyParsing

import java.io.File
import scala.math.BigInt

import de.zalando.play.controllers.PlayPathBindables


object FormDataParser {

    def postmultipartParseForm(request: Request[AnyContent]):Either[Seq[String],(String, BothPostYear, MultipartPostAvatar)] = {
        val contentType = request.contentType.getOrElse("application/x-www-form-urlencoded")
        def fromDataParts(data: Map[String, Seq[String]], files: Map[String, Option[FilePart[TemporaryFile]]], useFiles: Boolean):Either[Seq[String],(String, BothPostYear, MultipartPostAvatar)] = {
            val name: Either[String,String] = PlayBodyParsing.fromParameters[String]("form")("name", data)
            val year: Either[String,BothPostYear] = PlayBodyParsing.fromParameters[BothPostYear]("form")("year", data)
            val avatar: Either[String,MultipartPostAvatar] = if (useFiles) PlayBodyParsing.fromFileOptional("avatar", files("avatar")) else PlayBodyParsing.fromParameters[MultipartPostAvatar]("form")("avatar", data)
            val all = Seq(name, year, avatar)
            val errors = all.filter(_.isLeft).flatMap(_.left.toSeq)
            if (errors.nonEmpty) Left(errors) else Right((name.right.toOption.get, year.right.toOption.get, avatar.right.toOption.get))
        }
        contentType.toLowerCase match {
            
            case "multipart/form-data" => request.body.asMultipartFormData.map { form =>
                val files: Map[String, Option[FilePart[TemporaryFile]]] =
                (("avatar", form.file("avatar")) :: Nil).toMap
                fromDataParts(form.dataParts, files, useFiles = true)
            }.getOrElse(Left(Seq("Could not find 'multipart/form-data' body")))
            
            case other =>
                Left(Seq("Content type " + other + " is not supported"))
        }
    }


    def postbothParseForm(request: Request[AnyContent]):Either[Seq[String],(String, BothPostYear, MultipartPostAvatar, File)] = {
        val contentType = request.contentType.getOrElse("application/x-www-form-urlencoded")
        def fromDataParts(data: Map[String, Seq[String]], files: Map[String, Option[FilePart[TemporaryFile]]], useFiles: Boolean):Either[Seq[String],(String, BothPostYear, MultipartPostAvatar, File)] = {
            val name: Either[String,String] = PlayBodyParsing.fromParameters[String]("form")("name", data)
            val year: Either[String,BothPostYear] = PlayBodyParsing.fromParameters[BothPostYear]("form")("year", data)
            val avatar: Either[String,MultipartPostAvatar] = if (useFiles) PlayBodyParsing.fromFileOptional("avatar", files("avatar")) else PlayBodyParsing.fromParameters[MultipartPostAvatar]("form")("avatar", data)
            val ringtone: Either[String,File] = if (useFiles) PlayBodyParsing.fromFileRequired("ringtone", files("ringtone")) else PlayBodyParsing.fromParameters[File]("form")("ringtone", data)
            val all = Seq(name, year, avatar, ringtone)
            val errors = all.filter(_.isLeft).flatMap(_.left.toSeq)
            if (errors.nonEmpty) Left(errors) else Right((name.right.toOption.get, year.right.toOption.get, avatar.right.toOption.get, ringtone.right.toOption.get))
        }
        contentType.toLowerCase match {
            case "application/x-www-form-urlencoded" => request.body.asFormUrlEncoded.map { form =>
                val noFiles = Map.empty[String, Option[FilePart[TemporaryFile]]]
                fromDataParts(form, noFiles, useFiles = false)
            }.getOrElse(Left(Seq("Could not find 'application/x-www-form-urlencoded' body")))
            
            case "multipart/form-data" => request.body.asMultipartFormData.map { form =>
                val files: Map[String, Option[FilePart[TemporaryFile]]] =
                (("avatar", form.file("avatar")) :: ("ringtone", form.file("ringtone")) :: Nil).toMap
                fromDataParts(form.dataParts, files, useFiles = true)
            }.getOrElse(Left(Seq("Could not find 'multipart/form-data' body")))
            
            case other =>
                Left(Seq("Content type " + other + " is not supported"))
        }
    }


    def posturl_encodedParseForm(request: Request[AnyContent]):Either[Seq[String],(String, BothPostYear, File)] = {
        val contentType = request.contentType.getOrElse("application/x-www-form-urlencoded")
        def fromDataParts(data: Map[String, Seq[String]], files: Map[String, Option[FilePart[TemporaryFile]]], useFiles: Boolean):Either[Seq[String],(String, BothPostYear, File)] = {
            val name: Either[String,String] = PlayBodyParsing.fromParameters[String]("form")("name", data)
            val year: Either[String,BothPostYear] = PlayBodyParsing.fromParameters[BothPostYear]("form")("year", data)
            val avatar: Either[String,File] = if (useFiles) PlayBodyParsing.fromFileRequired("avatar", files("avatar")) else PlayBodyParsing.fromParameters[File]("form")("avatar", data)
            val all = Seq(name, year, avatar)
            val errors = all.filter(_.isLeft).flatMap(_.left.toSeq)
            if (errors.nonEmpty) Left(errors) else Right((name.right.toOption.get, year.right.toOption.get, avatar.right.toOption.get))
        }
        contentType.toLowerCase match {
            case "application/x-www-form-urlencoded" => request.body.asFormUrlEncoded.map { form =>
                val noFiles = Map.empty[String, Option[FilePart[TemporaryFile]]]
                fromDataParts(form, noFiles, useFiles = false)
            }.getOrElse(Left(Seq("Could not find 'application/x-www-form-urlencoded' body")))
            
            case other =>
                Left(Seq("Content type " + other + " is not supported"))
        }
    }

} 
Example 22
Source File: instagram_api_yaml.extractor.scala    From play-swagger   with MIT License 5 votes vote down vote up
package instagram.api.yaml

import scala.concurrent.Future
import play.api.mvc._
import de.zalando.play.controllers.SwaggerSecurityExtractors._
import scala.math.BigInt
import scala.math.BigDecimal

object SecurityExtractorsExecutionContext {
    // this ExecutionContext might be overridden if default configuration is not suitable for some reason
    implicit val ec = de.zalando.play.controllers.Contexts.tokenChecking
}

trait SecurityExtractors {
    def oauth_Extractor[User >: Any](scopes: String*): RequestHeader => Future[Option[User]] =
        header => oAuth(scopes)("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")(header) { (token: play.api.libs.json.JsValue) =>
            ???
    }
    def key_Extractor[User >: Any](): RequestHeader => Future[Option[User]] =
        header => queryApiKey("access_token")(header) { (apiKey: String) =>
            ???
    }
    implicit val unauthorizedContentWriter = ???
    def unauthorizedContent(req: RequestHeader) = Results.Unauthorized(???)
} 
Example 23
Source File: heroku_petstore_api_yaml.scala    From play-swagger   with MIT License 5 votes vote down vote up
package heroku.petstore.api.yaml
import play.api.mvc.{Action, Controller}
import play.api.data.validation.Constraint
import de.zalando.play.controllers._
import PlayBodyParsing._
import PlayValidations._

import scala.math.BigInt
// ----- constraints and wrapper validations -----
class PetIdGetPetIdConstraints(override val instance: String) extends ValidationBase[String] {
    override def constraints: Seq[Constraint[String]] =
        Seq()
}
class PetIdGetPetIdValidator(instance: String) extends RecursiveValidator {
    override val validators = Seq(new PetIdGetPetIdConstraints(instance))
}
class PetNameOptConstraints(override val instance: String) extends ValidationBase[String] {
    override def constraints: Seq[Constraint[String]] =
        Seq(maxLength(100), minLength(3))
}
class PetNameOptValidator(instance: String) extends RecursiveValidator {
    override val validators = Seq(new PetNameOptConstraints(instance))
}
class PetBirthdayOptConstraints(override val instance: Int) extends ValidationBase[Int] {
    override def constraints: Seq[Constraint[Int]] =
        Seq(max(100.toInt, false), min(1.toInt, false))
}
class PetBirthdayOptValidator(instance: Int) extends RecursiveValidator {
    override val validators = Seq(new PetBirthdayOptConstraints(instance))
}
class GetLimitConstraints(override val instance: BigInt) extends ValidationBase[BigInt] {
    override def constraints: Seq[Constraint[BigInt]] =
        Seq(max(BigInt("10000"), false), min(BigInt("11"), false))
}
class GetLimitValidator(instance: BigInt) extends RecursiveValidator {
    override val validators = Seq(new GetLimitConstraints(instance))
}
// ----- complex type validators -----
class PetValidator(instance: Pet) extends RecursiveValidator {
    override val validators = Seq(
        new PetNameValidator(instance.name), 
        new PetBirthdayValidator(instance.birthday)
    )
}
// ----- option delegating validators -----
class PetNameValidator(instance: PetName) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new PetNameOptValidator(_) }
}
class PetBirthdayValidator(instance: PetBirthday) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new PetBirthdayOptValidator(_) }
}
class PutPetValidator(instance: PutPet) extends RecursiveValidator {
    override val validators = instance.toSeq.map { new PetValidator(_) }
}
// ----- array delegating validators -----
// ----- catch all simple validators -----
// ----- call validations -----
class PutValidator(pet: PutPet) extends RecursiveValidator {
    override val validators = Seq(
        new PutPetValidator(pet)
    
    )
}
class GetValidator(limit: BigInt) extends RecursiveValidator {
    override val validators = Seq(
        new GetLimitValidator(limit)
    
    )
}
class PetIdGetValidator(petId: String) extends RecursiveValidator {
    override val validators = Seq(
        new PetIdGetPetIdValidator(petId)
    
    )
}
class PostValidator(pet: Pet) extends RecursiveValidator {
    override val validators = Seq(
        new PetValidator(pet)
    
    )
} 
Example 24
Source File: EquihashPowScheme.scala    From EncryCore   with GNU General Public License v3.0 5 votes vote down vote up
package encry.consensus

import com.google.common.primitives.Chars
import encry.crypto.equihash.{Equihash, EquihashValidationErrors}
import org.bouncycastle.crypto.digests.Blake2bDigest
import org.encryfoundation.common.crypto.equihash.EquihashSolution
import org.encryfoundation.common.modifiers.history.{Block, Header, Payload}
import org.encryfoundation.common.utils.Algos
import org.encryfoundation.common.utils.TaggedTypes.{Difficulty, Height, ModifierId}
import scorex.crypto.hash.Digest32
import scala.math.BigInt
import cats.syntax.either._
import encry.crypto.equihash.EquihashValidationErrors._

case class EquihashPowScheme(n: Char, k: Char, version: Byte, preGenesisHeight: Height, maxTarget: BigInt)
  extends ConsensusScheme {

  private val seed: Array[Byte] =
    "equi_seed_12".getBytes(Algos.charset) ++ Chars.toByteArray(n) ++ Chars.toByteArray(k)

  override def verifyCandidate(candidateBlock: CandidateBlock,
                               startingNonce: Long): Either[EquihashValidationErrors, Block] = {
    val difficulty = candidateBlock.difficulty
    val parentId: ModifierId = candidateBlock.parentOpt.map(_.id).getOrElse(Header.GenesisParentId)
    val txsRoot: Digest32 = Payload.rootHash(candidateBlock.transactions.map(_.id))
    val height: Int = candidateBlock.parentOpt.map(_.height).getOrElse(preGenesisHeight) + 1
    val bytesPerWord: Int = n / 8
    val wordsPerHash: Int = 512 / n
    val digest: Blake2bDigest = new Blake2bDigest(null, bytesPerWord * wordsPerHash, null, seed)
    val header: Header = Header(
      version, parentId, txsRoot,
      candidateBlock.timestamp, height, 0L, candidateBlock.difficulty, EquihashSolution.empty, candidateBlock.stateRoot
    )
    for {
      possibleHeader <- generateHeader(startingNonce, digest, header, difficulty)
      validationResult = verify(possibleHeader)
      _ <- Either.cond(validationResult.isRight, (),
        VerifyingCandidateValidationError(s"Incorrect possible header cause: $validationResult"))
      payload: Payload = Payload(possibleHeader.id, candidateBlock.transactions)
    } yield Block(possibleHeader, payload)
  }

  private def generateHeader(nonce: Long,
                             digest: Blake2bDigest,
                             header: Header,
                             difficulty: Difficulty): Either[EquihashValidationErrors, Header] = {
    val currentDigest = new Blake2bDigest(digest)
    Equihash.hashNonce(currentDigest, nonce)
    val solutions = Equihash.gbpBasic(currentDigest, n, k)
    solutions
      .map(solution => header.copy(nonce = nonce, equihashSolution = solution))
      .find(newHeader => correctWorkDone(realDifficulty(newHeader), difficulty))
    match {
      case Some(value) => value.asRight[EquihashValidationErrors]
      case None => GeneratingHeaderError("Generate header failed").asLeft[Header]
    }
  }

  def verify(header: Header): Either[EquihashValidationErrors, Boolean] = Equihash
    .validateSolution(n, k, seed, Equihash.nonceToLeBytes(header.nonce), header.equihashSolution.indexedSeq)

  override def realDifficulty(header: Header): Difficulty =
    Difficulty @@ (maxTarget / BigInt(1, header.powHash))

  override def toString: String = s"EquihashPowScheme(n = ${n.toInt}, k = ${k.toInt})"
}