scala.math.BigDecimal Scala Examples
The following examples show how to use scala.math.BigDecimal.
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: CommandsTest.scala From endpoints4s with MIT License | 5 votes |
package cqrs.commands import java.time.{LocalDateTime, OffsetDateTime, ZoneOffset} import java.util.UUID import org.scalatest.BeforeAndAfterAll import endpoints4s.play.client.{Endpoints, JsonEntitiesFromCodecs} import endpoints4s.play.server.PlayComponents import play.api.Mode import play.api.libs.ws.ahc.{AhcWSClient, AhcWSClientConfig} import play.core.server.{NettyServer, ServerConfig} import scala.concurrent.Future import scala.math.BigDecimal import org.scalatest.freespec.AsyncFreeSpec class CommandsTest extends AsyncFreeSpec with BeforeAndAfterAll { private val server = NettyServer.fromRouterWithComponents(ServerConfig(mode = Mode.Test)) { components => new Commands(PlayComponents.fromBuiltInComponents(components)).routes } val app = server.applicationProvider.get.get import app.materializer private val wsClient = AhcWSClient(AhcWSClientConfig()) object client extends Endpoints("http://localhost:9000", wsClient) with JsonEntitiesFromCodecs with CommandsEndpoints override def afterAll(): Unit = { server.stop() wsClient.close() } "Commands" - { val arbitraryDate = OffsetDateTime .of(LocalDateTime.of(2017, 1, 8, 12, 34, 56), ZoneOffset.UTC) .toInstant val arbitraryValue = BigDecimal(10) "create a new meter" in { client.command(CreateMeter("electricity")).map { maybeEvent => assert(maybeEvent.collect { case StoredEvent(_, MeterCreated(_, "electricity")) => () }.nonEmpty) } } "create a meter and add readings to it" in { for { maybeCreatedEvent <- client.command(CreateMeter("water")) id <- maybeCreatedEvent .collect { case StoredEvent(_, MeterCreated(id, _)) => id } .fold[Future[UUID]](Future.failed(new NoSuchElementException))( Future.successful ) maybeAddedEvent <- client.command( AddRecord(id, arbitraryDate, arbitraryValue) ) _ <- maybeAddedEvent .collect { case StoredEvent( _, RecordAdded(`id`, `arbitraryDate`, `arbitraryValue`) ) => () } .fold[Future[Unit]](Future.failed(new NoSuchElementException))( Future.successful ) } yield assert(true) } } }
Example 2
Source File: instagram_api_yaml.extractor.scala From play-swagger with MIT License | 5 votes |
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 3
Source File: uber_api_yaml.scala From play-swagger with MIT License | 5 votes |
package uber.api.yaml import org.scalacheck.Gen import org.scalacheck.Arbitrary import play.api.libs.json.scalacheck.JsValueGenerators import Arbitrary._ import java.util.UUID import scala.math.BigDecimal import de.zalando.play.controllers.ArrayWrapper object Generators extends JsValueGenerators { def createDoubleGenerator = _generate(DoubleGenerator) def createActivitiesHistoryGenerator = _generate(ActivitiesHistoryGenerator) def createProfilePictureGenerator = _generate(ProfilePictureGenerator) def createErrorCodeGenerator = _generate(ErrorCodeGenerator) def createEstimatesTimeGetCustomer_uuidGenerator = _generate(EstimatesTimeGetCustomer_uuidGenerator) def createProductsGetResponses200Generator = _generate(ProductsGetResponses200Generator) def createPriceEstimateHigh_estimateGenerator = _generate(PriceEstimateHigh_estimateGenerator) def createEstimatesPriceGetResponses200Generator = _generate(EstimatesPriceGetResponses200Generator) def createActivitiesHistoryOptGenerator = _generate(ActivitiesHistoryOptGenerator) def DoubleGenerator = arbitrary[Double] def ActivitiesHistoryGenerator = Gen.option(ActivitiesHistoryOptGenerator) def ProfilePictureGenerator = Gen.option(arbitrary[String]) def ErrorCodeGenerator = Gen.option(arbitrary[Int]) def EstimatesTimeGetCustomer_uuidGenerator = Gen.option(arbitrary[UUID]) def ProductsGetResponses200Generator = Gen.containerOf[List,Product](ProductGenerator) def PriceEstimateHigh_estimateGenerator = Gen.option(arbitrary[BigDecimal]) def EstimatesPriceGetResponses200Generator = Gen.containerOf[List,PriceEstimate](PriceEstimateGenerator) def ActivitiesHistoryOptGenerator = _genList(ActivityGenerator, "csv") def createActivityGenerator = _generate(ActivityGenerator) def createPriceEstimateGenerator = _generate(PriceEstimateGenerator) def createProductGenerator = _generate(ProductGenerator) def createProfileGenerator = _generate(ProfileGenerator) def createActivitiesGenerator = _generate(ActivitiesGenerator) def createErrorGenerator = _generate(ErrorGenerator) def ActivityGenerator = for { uuid <- ProfilePictureGenerator } yield Activity(uuid) def PriceEstimateGenerator = for { low_estimate <- PriceEstimateHigh_estimateGenerator display_name <- ProfilePictureGenerator estimate <- ProfilePictureGenerator high_estimate <- PriceEstimateHigh_estimateGenerator product_id <- ProfilePictureGenerator currency_code <- ProfilePictureGenerator surge_multiplier <- PriceEstimateHigh_estimateGenerator } yield PriceEstimate(low_estimate, display_name, estimate, high_estimate, product_id, currency_code, surge_multiplier) def ProductGenerator = for { image <- ProfilePictureGenerator description <- ProfilePictureGenerator display_name <- ProfilePictureGenerator product_id <- ProfilePictureGenerator capacity <- ProfilePictureGenerator } yield Product(image, description, display_name, product_id, capacity) def ProfileGenerator = for { first_name <- ProfilePictureGenerator email <- ProfilePictureGenerator promo_code <- ProfilePictureGenerator last_name <- ProfilePictureGenerator picture <- ProfilePictureGenerator } yield Profile(first_name, email, promo_code, last_name, picture) def ActivitiesGenerator = for { offset <- ErrorCodeGenerator limit <- ErrorCodeGenerator count <- ErrorCodeGenerator history <- ActivitiesHistoryGenerator } yield Activities(offset, limit, count, history) def ErrorGenerator = for { code <- ErrorCodeGenerator message <- ProfilePictureGenerator fields <- ProfilePictureGenerator } yield Error(code, message, fields) def _generate[T](gen: Gen[T]) = (count: Int) => for (i <- 1 to count) yield gen.sample def _genList[T](gen: Gen[T], format: String): Gen[ArrayWrapper[T]] = for { items <- Gen.containerOf[List,T](gen) } yield ArrayWrapper(format)(items) implicit lazy val arbUUID: Arbitrary[UUID] = Arbitrary(Gen.uuid) }
Example 4
Source File: instagram_api_yaml.scala From play-swagger with MIT License | 5 votes |
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 5
Source File: MllibHelper.scala From twitter-stream-ml with GNU General Public License v3.0 | 5 votes |
package com.giorgioinf.twtml.spark import java.text.Normalizer import org.apache.spark.Logging import org.apache.spark.mllib.feature.HashingTF import org.apache.spark.mllib.linalg.{SparseVector, Vector, Vectors} import org.apache.spark.mllib.regression.LabeledPoint import scala.math.BigDecimal import twitter4j.Status object MllibHelper extends Logging { val numNumberFeatures = 4 var numRetweetBegin = 100 var numRetweetEnd = 1000 var numTextFeatures = 1000 var hashText = new HashingTF(numTextFeatures) var numFeatures = numTextFeatures + numNumberFeatures var numberFeatureIndices = (numTextFeatures to numFeatures-1).toArray def reset(conf:ConfArguments) { numRetweetBegin = conf.numRetweetBegin numRetweetEnd = conf.numRetweetEnd numTextFeatures = conf.numTextFeatures var hashText = new HashingTF(numTextFeatures) var numFeatures = numTextFeatures + numNumberFeatures var numberFeatureIndices = (numTextFeatures to numFeatures-1).toArray log.debug(s"retweet range: ($numRetweetBegin - $numRetweetEnd), numTextFeatures: $numTextFeatures") } def featurizeText(statuses: Status): SparseVector = { val text = statuses.getRetweetedStatus .getText .toLowerCase // Separate accents from characters and then remove non-unicode // characters val noAccentText = Normalizer .normalize(text, Normalizer.Form.NFD) .replaceAll("\\p{M}", "") // bigrams hashText.transform(text.sliding(2).toSeq) .asInstanceOf[SparseVector] } def featurizeNumbers(statuses: Status): Vector = { val user = statuses.getRetweetedStatus.getUser val created = statuses.getRetweetedStatus.getCreatedAt val timeLeft = (System.currentTimeMillis - created.getTime) Vectors.dense( user.getFollowersCount * Math.pow(10, -12), user.getFavouritesCount * Math.pow(10, -12), user.getFriendsCount * Math.pow(10, -12), timeLeft * Math.pow(10, -14) //retweeted.getURLEntities.length, //retweeted.getUserMentionEntities.length ) } def featurize(statuses: Status): LabeledPoint = { val textFeatures = featurizeText(statuses) val numberFeatures = featurizeNumbers(statuses) val features = Vectors.sparse( numFeatures, textFeatures.indices ++ numberFeatureIndices, textFeatures.values ++ numberFeatures.toArray ) LabeledPoint( statuses.getRetweetedStatus.getRetweetCount.toDouble, features ) } def retweetInterval(statuses: Status, start:Long, end:Long):Boolean = { val n = statuses.getRetweetedStatus.getRetweetCount (n >= start && n <= end) } def filtrate(statuses: Status): Boolean = { ( statuses.isRetweet && //statuses.getLang == "en" && retweetInterval(statuses, numRetweetBegin, numRetweetEnd) ) } }
Example 6
Source File: instagram_api_yaml.extractor.scala From api-first-hand with MIT License | 5 votes |
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 7
Source File: uber_api_yaml.scala From api-first-hand with MIT License | 5 votes |
package uber.api.yaml import org.scalacheck.Gen import org.scalacheck.Arbitrary import play.api.libs.json.scalacheck.JsValueGenerators import Arbitrary._ import java.util.UUID import scala.math.BigDecimal object Generators extends JsValueGenerators { def createDoubleGenerator = _generate(DoubleGenerator) def createActivitiesHistoryGenerator = _generate(ActivitiesHistoryGenerator) def createProfilePictureGenerator = _generate(ProfilePictureGenerator) def createErrorCodeGenerator = _generate(ErrorCodeGenerator) def createEstimatesTimeGetCustomer_uuidGenerator = _generate(EstimatesTimeGetCustomer_uuidGenerator) def createProductsGetResponses200Generator = _generate(ProductsGetResponses200Generator) def createPriceEstimateHigh_estimateGenerator = _generate(PriceEstimateHigh_estimateGenerator) def createEstimatesPriceGetResponses200Generator = _generate(EstimatesPriceGetResponses200Generator) def createActivitiesHistoryOptGenerator = _generate(ActivitiesHistoryOptGenerator) def DoubleGenerator = arbitrary[Double] def ActivitiesHistoryGenerator = Gen.option(ActivitiesHistoryOptGenerator) def ProfilePictureGenerator = Gen.option(arbitrary[String]) def ErrorCodeGenerator = Gen.option(arbitrary[Int]) def EstimatesTimeGetCustomer_uuidGenerator = Gen.option(arbitrary[UUID]) def ProductsGetResponses200Generator: Gen[List[Product]] = Gen.containerOf[List,Product](ProductGenerator) def PriceEstimateHigh_estimateGenerator = Gen.option(arbitrary[BigDecimal]) def EstimatesPriceGetResponses200Generator: Gen[List[PriceEstimate]] = Gen.containerOf[List,PriceEstimate](PriceEstimateGenerator) def ActivitiesHistoryOptGenerator: Gen[List[Activity]] = Gen.containerOf[List,Activity](ActivityGenerator) def createActivityGenerator = _generate(ActivityGenerator) def createPriceEstimateGenerator = _generate(PriceEstimateGenerator) def createProductGenerator = _generate(ProductGenerator) def createProfileGenerator = _generate(ProfileGenerator) def createActivitiesGenerator = _generate(ActivitiesGenerator) def createErrorGenerator = _generate(ErrorGenerator) def ActivityGenerator = for { uuid <- ProfilePictureGenerator } yield Activity(uuid) def PriceEstimateGenerator = for { low_estimate <- PriceEstimateHigh_estimateGenerator display_name <- ProfilePictureGenerator estimate <- ProfilePictureGenerator high_estimate <- PriceEstimateHigh_estimateGenerator product_id <- ProfilePictureGenerator currency_code <- ProfilePictureGenerator surge_multiplier <- PriceEstimateHigh_estimateGenerator } yield PriceEstimate(low_estimate, display_name, estimate, high_estimate, product_id, currency_code, surge_multiplier) def ProductGenerator = for { image <- ProfilePictureGenerator description <- ProfilePictureGenerator display_name <- ProfilePictureGenerator product_id <- ProfilePictureGenerator capacity <- ProfilePictureGenerator } yield Product(image, description, display_name, product_id, capacity) def ProfileGenerator = for { first_name <- ProfilePictureGenerator email <- ProfilePictureGenerator promo_code <- ProfilePictureGenerator last_name <- ProfilePictureGenerator picture <- ProfilePictureGenerator } yield Profile(first_name, email, promo_code, last_name, picture) def ActivitiesGenerator = for { offset <- ErrorCodeGenerator limit <- ErrorCodeGenerator count <- ErrorCodeGenerator history <- ActivitiesHistoryGenerator } yield Activities(offset, limit, count, history) def ErrorGenerator = for { code <- ErrorCodeGenerator message <- ProfilePictureGenerator fields <- ProfilePictureGenerator } yield Error(code, message, fields) def _generate[T](gen: Gen[T]) = (count: Int) => for (i <- 1 to count) yield gen.sample implicit lazy val arbUUID: Arbitrary[UUID] = Arbitrary(Gen.uuid) }
Example 8
Source File: i041_no_json_deserialiser_yaml.scala From api-first-hand with MIT License | 5 votes |
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 9
Source File: uber_api_yaml.scala From api-first-hand with MIT License | 5 votes |
package uber.api import java.util.UUID import scala.math.BigDecimal import de.zalando.play.controllers.PlayPathBindables //noinspection ScalaStyle package yaml { case class Activity(uuid: ProfilePicture) case class PriceEstimate(low_estimate: PriceEstimateHigh_estimate, display_name: ProfilePicture, estimate: ProfilePicture, high_estimate: PriceEstimateHigh_estimate, product_id: ProfilePicture, currency_code: ProfilePicture, surge_multiplier: PriceEstimateHigh_estimate) case class Product(image: ProfilePicture, description: ProfilePicture, display_name: ProfilePicture, product_id: ProfilePicture, capacity: ProfilePicture) case class Profile(first_name: ProfilePicture, email: ProfilePicture, promo_code: ProfilePicture, last_name: ProfilePicture, picture: ProfilePicture) case class Activities(offset: ErrorCode, limit: ErrorCode, count: ErrorCode, history: ActivitiesHistory) case class Error(code: ErrorCode, message: ProfilePicture, fields: ProfilePicture) import play.api.libs.json._ import play.api.libs.functional.syntax._ import de.zalando.play.controllers.MissingDefaultWrites object ResponseWrites extends MissingDefaultWrites { implicit val ActivityWrites: Writes[Activity] = new Writes[Activity] { def writes(ss: Activity) = Json.obj( "uuid" -> ss.uuid ) } implicit val ActivitiesWrites: Writes[Activities] = new Writes[Activities] { def writes(ss: Activities) = Json.obj( "offset" -> ss.offset, "limit" -> ss.limit, "count" -> ss.count, "history" -> ss.history ) } implicit val PriceEstimateWrites: Writes[PriceEstimate] = new Writes[PriceEstimate] { def writes(ss: PriceEstimate) = Json.obj( "low_estimate" -> ss.low_estimate, "display_name" -> ss.display_name, "estimate" -> ss.estimate, "high_estimate" -> ss.high_estimate, "product_id" -> ss.product_id, "currency_code" -> ss.currency_code, "surge_multiplier" -> ss.surge_multiplier ) } implicit val ProductWrites: Writes[Product] = new Writes[Product] { def writes(ss: Product) = Json.obj( "image" -> ss.image, "description" -> ss.description, "display_name" -> ss.display_name, "product_id" -> ss.product_id, "capacity" -> ss.capacity ) } implicit val ProfileWrites: Writes[Profile] = new Writes[Profile] { def writes(ss: Profile) = Json.obj( "first_name" -> ss.first_name, "email" -> ss.email, "promo_code" -> ss.promo_code, "last_name" -> ss.last_name, "picture" -> ss.picture ) } } } // should be defined after the package because of the https://issues.scala-lang.org/browse/SI-9922 //noinspection ScalaStyle package object yaml { type ActivitiesHistory = Option[ActivitiesHistoryOpt] type ProfilePicture = Option[String] type ErrorCode = Option[Int] type EstimatesTimeGetCustomer_uuid = Option[UUID] type ProductsGetResponses200 = Seq[Product] type PriceEstimateHigh_estimate = Option[BigDecimal] type EstimatesPriceGetResponses200 = Seq[PriceEstimate] type ActivitiesHistoryOpt = Seq[Activity] import play.api.mvc.{QueryStringBindable, PathBindable} implicit val bindable_UUIDQuery = PlayPathBindables.queryBindableUUID implicit val bindable_OptionIntQuery: QueryStringBindable[Option[Int]] = PlayPathBindables.createOptionQueryBindable[Int] implicit val bindable_OptionStringQuery: QueryStringBindable[Option[String]] = PlayPathBindables.createOptionQueryBindable[String] implicit val bindable_OptionUUIDQuery: QueryStringBindable[Option[UUID]] = PlayPathBindables.createOptionQueryBindable[UUID] }
Example 10
Source File: i041_no_json_deserialiser_yaml.scala From api-first-hand with MIT License | 5 votes |
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 11
Source File: instagram_api_yaml.scala From api-first-hand with MIT License | 5 votes |
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) }