play.api.libs.json.OFormat Scala Examples

The following examples show how to use play.api.libs.json.OFormat. 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: NaptimeModuleTest.scala    From naptime   with Apache License 2.0 8 votes vote down vote up
package org.coursera.naptime

import java.util.Date
import javax.inject.Inject

import akka.stream.Materializer
import com.google.inject.Guice
import com.google.inject.Stage
import com.linkedin.data.schema.DataSchema
import com.linkedin.data.schema.DataSchemaUtil
import com.linkedin.data.schema.PrimitiveDataSchema
import com.linkedin.data.schema.RecordDataSchema
import org.coursera.naptime.model.KeyFormat
import org.coursera.naptime.resources.TopLevelCollectionResource
import org.coursera.naptime.router2.NaptimeRoutes
import org.junit.Test
import org.mockito.Mockito.mock
import org.scalatest.junit.AssertionsForJUnit
import play.api.libs.json.Json
import play.api.libs.json.OFormat

import scala.concurrent.ExecutionContext

object NaptimeModuleTest {
  case class User(name: String, createdAt: Date)
  object User {
    implicit val oFormat: OFormat[User] = Json.format[User]
  }
  class MyResource(implicit val executionContext: ExecutionContext, val materializer: Materializer)
      extends TopLevelCollectionResource[String, User] {
    override implicit def resourceFormat: OFormat[User] = User.oFormat
    override def keyFormat: KeyFormat[KeyType] = KeyFormat.stringKeyFormat
    override def resourceName: String = "myResource"
    implicit val fields = Fields

    def get(id: String) = Nap.get(ctx => ???)
  }
  object MyFakeModule extends NaptimeModule {
    override def configure(): Unit = {
      bindResource[MyResource]
      bind[MyResource].toInstance(mock(classOf[MyResource]))
      bindSchemaType[Date](DataSchemaUtil.dataSchemaTypeToPrimitiveDataSchema(DataSchema.Type.LONG))
    }
  }

  class OverrideTypesHelper @Inject()(val schemaOverrideTypes: NaptimeModule.SchemaTypeOverrides)
}

class NaptimeModuleTest extends AssertionsForJUnit {
  import NaptimeModuleTest._

  
  @Test
  def checkInferredOverrides(): Unit = {
    val injector = Guice.createInjector(Stage.DEVELOPMENT, MyFakeModule, NaptimeModule)
    val overrides = injector.getInstance(classOf[OverrideTypesHelper])
    assert(overrides.schemaOverrideTypes.size === 1)
    assert(overrides.schemaOverrideTypes.contains("java.util.Date"))
  }

  @Test
  def checkComputedOverrides(): Unit = {
    val injector = Guice.createInjector(Stage.DEVELOPMENT, MyFakeModule, NaptimeModule)
    val overrides = injector.getInstance(classOf[OverrideTypesHelper])
    val routes = injector.getInstance(classOf[NaptimeRoutes])
    assert(1 === routes.routerBuilders.size)
    val routerBuilder = routes.routerBuilders.head
    val inferredSchemaKeyed =
      routerBuilder.types.find(_.key == "org.coursera.naptime.NaptimeModuleTest.User").get
    assert(inferredSchemaKeyed.value.isInstanceOf[RecordDataSchema])
    val userSchema = inferredSchemaKeyed.value.asInstanceOf[RecordDataSchema]
    assert(2 === userSchema.getFields.size())
    val initialCreatedAtSchema = userSchema.getField("createdAt").getType.getDereferencedDataSchema
    assert(initialCreatedAtSchema.isInstanceOf[RecordDataSchema])
    assert(
      initialCreatedAtSchema
        .asInstanceOf[RecordDataSchema]
        .getDoc
        .contains("Unable to infer schema"))
    SchemaUtils.fixupInferredSchemas(userSchema, overrides.schemaOverrideTypes)
    val fixedCreatedAtSchema = userSchema.getField("createdAt").getType.getDereferencedDataSchema
    assert(fixedCreatedAtSchema.isInstanceOf[PrimitiveDataSchema])
  }
} 
Example 2
Source File: NestingTests.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
package org.coursera.naptime.resources

import akka.stream.Materializer
import org.coursera.common.jsonformat.JsonFormats.Implicits.dateTimeFormat
import org.coursera.naptime.ResourceTestImplicits
import org.coursera.naptime.model.KeyFormat
import org.coursera.naptime.path.ParseFailure
import org.coursera.naptime.path.ParseSuccess
import org.coursera.naptime.path.RootParsedPathKey
import org.coursera.naptime.resources.NestingTests.FriendInfoResource
import org.coursera.naptime.resources.NestingTests.PeopleResource
import org.joda.time.DateTime
import org.junit.Test
import org.scalatest.junit.AssertionsForJUnit
import play.api.libs.json.Json
import play.api.libs.json.OFormat

import scala.concurrent.ExecutionContext

object NestingTests {
  case class Person(name: String)
  object Person {
    implicit val jsonFormat: OFormat[Person] = Json.format[Person]
  }

  class PeopleResource(
      implicit val executionContext: ExecutionContext,
      val materializer: Materializer)
      extends TopLevelCollectionResource[String, Person] {

    override def keyFormat = KeyFormat.stringKeyFormat
    override implicit def resourceFormat = implicitly
    override def resourceName: String = "people"
  }

  case class FriendInfo(since: DateTime, important: Boolean)
  object FriendInfo {
    implicit val jsonFormat: OFormat[FriendInfo] = Json.format[FriendInfo]
  }

  class FriendInfoResource(peopleResource: PeopleResource)(
      implicit val executionContext: ExecutionContext,
      val materializer: Materializer)
      extends CollectionResource[PeopleResource, String, FriendInfo] {

    override def keyFormat = KeyFormat.stringKeyFormat
    override val parentResource = peopleResource
    override implicit def resourceFormat = implicitly
    override def resourceName: String = "friendInfo"
  }
}

class NestingTests extends AssertionsForJUnit with ResourceTestImplicits {

  @Test
  def topLevelRouting(): Unit = {
    val peopleResource = new PeopleResource
    assert(
      ParseSuccess(None, "asdf" ::: RootParsedPathKey) ===
        peopleResource.pathParser.parse("/people.v1/asdf"))
    assert(
      ParseSuccess(Some("/friendInfo.v1/fdsa"), "asdf" ::: RootParsedPathKey) ===
        peopleResource.pathParser.parse("/people.v1/asdf/friendInfo.v1/fdsa"))
    assert(ParseFailure === peopleResource.pathParser.parse("/friendInfo.v1/asdf"))
  }

  @Test
  def nestedRouting(): Unit = {
    val peopleResource = new PeopleResource
    val friendInfoResource = new FriendInfoResource(peopleResource)
    assert(
      ParseSuccess(None, "fdsa" ::: "asdf" ::: RootParsedPathKey) ===
        friendInfoResource.pathParser.parse("/people.v1/asdf/friendInfo.v1/fdsa"))
    assert(ParseFailure === friendInfoResource.pathParser.parse("/friendInfo.v1/fdsa"))
    assert(ParseFailure === friendInfoResource.pathParser.parse("/people.v1/asdf"))
  }
} 
Example 3
Source File: AnyThing.scala    From swagger-check   with MIT License 5 votes vote down vote up
package de.leanovate.swaggercheck.fixtures.model

import java.net.{URI, URL}
import java.time.temporal.ChronoUnit
import java.time.{Instant, LocalDate}
import java.util.UUID

import de.leanovate.swaggercheck.generators.Generators
import org.scalacheck.{Arbitrary, Gen}
import play.api.libs.json.{Json, OFormat}

import scala.util.Try

case class AnyThing(
                     anUUID: String,
                     anURL: String,
                     anURI: String,
                     anEmail: String,
                     aDate: LocalDate,
                     aDateTime: Instant,
                     anInt32: Int,
                     anInt64: Long,
                     aFloat: Float,
                     aDouble: Double,
                     aBoolean: Boolean,
                     anEnum: String,
                     aMap: Map[String, String]
                   ) {
  def isValid: Boolean = {
    Try {
      UUID.fromString(anUUID)
      new URL(anURL)
      new URI(anURI)
    }.isSuccess && Set("V1", "V2", "V3").contains(anEnum)
  }
}

object AnyThing {
  implicit val jsonFormat: OFormat[AnyThing] = Json.format[AnyThing]

  implicit val arbitrary = Arbitrary(for {
    anUUID <- Gen.uuid.map(_.toString)
    anURL <- Generators.url
    anURI <- Generators.uri
    anEmail <- Generators.email
    aDate <- Arbitrary.arbitrary[Int].map(diff => LocalDate.now().plus(diff, ChronoUnit.DAYS))
    aDateTime <- Arbitrary.arbitrary[Long].map(diff => Instant.now().plus(diff, ChronoUnit.NANOS))
    anInt32 <- Arbitrary.arbitrary[Int]
    anInt64 <- Arbitrary.arbitrary[Long]
    aFloat <- Arbitrary.arbitrary[Float]
    aDouble <- Arbitrary.arbitrary[Double]
    aBoolean <- Arbitrary.arbitrary[Boolean]
    anEnum <- Gen.oneOf("V1", "V2", "V3")
    aMap <- Arbitrary.arbitrary[Map[String, String]]
  } yield AnyThing(anUUID, anURL, anURI, anEmail, aDate, aDateTime, anInt32, anInt64, aFloat, aDouble, aBoolean, anEnum, aMap))
} 
Example 4
Source File: UserResource.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
package resources

import java.util.concurrent.atomic.AtomicInteger
import javax.inject.Inject
import javax.inject.Singleton

import org.coursera.naptime.model.KeyFormat
import org.coursera.naptime.model.Keyed
import org.coursera.naptime.NaptimeModule
import org.coursera.naptime.Ok
import org.coursera.example.User
import org.coursera.naptime.courier.CourierFormats
import org.coursera.naptime.resources.TopLevelCollectionResource
import org.coursera.naptime.resources.RestActionHelpers
import play.api.libs.json.OFormat


  def create() = Rest
      .jsonBody[User]
      .create { context =>
        val user = context.body
        val id = userStore.create(user)

        // Could return Ok(Keyed(id, None)) if we want to return 201 Created,
        // with an empty body. Prefer returning the updated body, however.
        Ok(Keyed(id, Some(user)))
      }
}

class ResourceModule extends NaptimeModule {
  override def configure(): Unit = {
    bindResource[UsersResource]
    bind[UserStore].to[UserStoreImpl]
  }
}


trait UserStore {
  def get(id: Int): Option[User]
  def create(user: User): Int
}

class UserStoreImpl extends UserStore {
  @volatile
  var userStore = Map.empty[Int, User]
  val nextId = new AtomicInteger(0)


  def get(id: Int) = userStore.get(id)

  def create(user: User): Int = {
    val id = nextId.incrementAndGet()
    userStore = userStore + (id -> user)
    id
  }


}

class UserBanManager {
  @volatile
  var bannedUsers = Set.empty[Int]
} 
Example 5
Source File: UserResource.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
package resources

import java.util.concurrent.atomic.AtomicInteger
import javax.inject.Inject
import javax.inject.Singleton

import akka.stream.Materializer
import org.coursera.naptime.model.KeyFormat
import org.coursera.naptime.model.Keyed
import org.coursera.naptime.Ok
import org.coursera.example.User
import org.coursera.naptime.courier.CourierFormats
import org.coursera.naptime.resources.TopLevelCollectionResource
import play.api.libs.json.OFormat

import scala.concurrent.ExecutionContext


@Singleton
class UsersResource @Inject() (
    userStore: UserStore,
    banManager: UserBanManager)
    (implicit override val executionContext: ExecutionContext,
    override val materializer: Materializer)
  extends TopLevelCollectionResource[Int, User] {

  override def resourceName = "users"
  override def resourceVersion = 1  // optional; defaults to 1
  implicit val fields = Fields.withDefaultFields(  // default field projection
    "id", "name", "email")

  override def keyFormat: KeyFormat[KeyType] = KeyFormat.intKeyFormat
  override implicit def resourceFormat: OFormat[User] = CourierFormats.recordTemplateFormats[User]

  def get(id: Int) = Nap.get { context =>
    OkIfPresent(id, userStore.get(id))
  }

  def multiGet(ids: Set[Int]) = Nap.multiGet { context =>
    Ok(userStore.all()
      .filter(user => ids.contains(user._1))
      .map { case (id, user) => Keyed(id, user) }.toList)
  }

  def getAll() = Nap.getAll { context =>
    Ok(userStore.all().map { case (id, user) => Keyed(id, user) }.toList)
  }

  def create() = Nap
    .jsonBody[User]
    .create { context =>
      val user = context.body
      val id = userStore.create(user)

      // Could return Ok(Keyed(id, None)) if we want to return 201 Created,
      // with an empty body. Prefer returning the updated body, however.
      Ok(Keyed(id, Some(user)))
    }

  def email(email: String) = Nap.finder { context =>
    Ok(userStore.all()
      .filter(_._2.email == email)
      .map { case (id, user) => Keyed(id, user) }.toList)
  }

}


trait UserStore {
  def get(id: Int): Option[User]
  def create(user: User): Int
  def all(): Map[Int, User]
}

@Singleton
class UserStoreImpl extends UserStore {
  @volatile
  var userStore = Map.empty[Int, User]
  val nextId = new AtomicInteger(0)

  def get(id: Int) = userStore.get(id)

  def create(user: User): Int = {
    val id = nextId.incrementAndGet()
    userStore = userStore + (id -> user)
    id
  }

  def all() = userStore

}

class UserBanManager {
  @volatile
  var bannedUsers = Set.empty[Int]
} 
Example 6
Source File: AuthMacroTest.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
package org.coursera.naptime

import akka.stream.Materializer
import org.coursera.naptime.access.HeaderAccessControl
import org.coursera.naptime.model.KeyFormat
import org.coursera.naptime.resources.TopLevelCollectionResource
import org.coursera.naptime.router2._
import org.junit.Test
import org.scalatest.junit.AssertionsForJUnit
import org.scalatest.mockito.MockitoSugar
import play.api.libs.json.OFormat
import play.api.mvc.RequestHeader

import scala.concurrent.ExecutionContext

case class CustomAuth()

object CustomAuthorizer extends HeaderAccessControl[CustomAuth] {
  override def run(requestHeader: RequestHeader)(implicit executionContext: ExecutionContext) = ???
  override private[naptime] def check(authInfo: CustomAuth) = ???
}

class AuthorizedResource(
    implicit val executionContext: ExecutionContext,
    val materializer: Materializer)
    extends TopLevelCollectionResource[String, Item] {

  override def keyFormat: KeyFormat[String] = KeyFormat.stringKeyFormat

  override implicit def resourceFormat: OFormat[Item] = Item.jsonFormat

  override def resourceName: String = "items"

  implicit val fields = Fields.withDefaultFields("name")

  def get(id: String) =
    Nap
      .auth(CustomAuthorizer)
      .get { ctx =>
        ???
      }

}

object AuthorizedResource {
  val routerBuilder = Router.build[AuthorizedResource]
}

class AuthMacroTest extends AssertionsForJUnit with MockitoSugar with ResourceTestImplicits {

  val schema = AuthorizedResource.routerBuilder.schema

  @Test
  def get(): Unit = {
    val handler = schema.handlers.find(_.name === "get").get
    assert(handler.authType === Some("org.coursera.naptime.CustomAuth"))
  }

} 
Example 7
Source File: RestActionBodyBuilder.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
package org.coursera.naptime.actions

import akka.stream.Materializer
import org.coursera.common.concurrent.Futures
import org.coursera.naptime.model.KeyFormat
import org.coursera.naptime.ResourceFields
import org.coursera.naptime.PaginationConfiguration
import org.coursera.naptime.RestContext
import org.coursera.naptime.RestError
import org.coursera.naptime.RestResponse
import play.api.libs.json.OFormat
import play.api.mvc.BodyParser

import scala.concurrent.ExecutionContext
import scala.concurrent.Future


class RestActionBodyBuilder[
    RACType,
    AuthType,
    BodyType,
    ResourceKeyType,
    ResourceType,
    ResponseType](
    authGeneratorOrAuth: AuthGenerator[BodyType, AuthType],
    bodyParser: BodyParser[BodyType],
    errorHandler: PartialFunction[Throwable, RestError])(
    implicit keyFormat: KeyFormat[ResourceKeyType],
    resourceFormat: OFormat[ResourceType],
    ec: ExecutionContext,
    mat: Materializer) { self =>

  type CategoryEngine =
    RestActionCategoryEngine[RACType, ResourceKeyType, ResourceType, ResponseType]
  type BuiltAction =
    RestAction[RACType, AuthType, BodyType, ResourceKeyType, ResourceType, ResponseType]

  def apply(fn: RestContext[AuthType, BodyType] => RestResponse[ResponseType])(
      implicit category: CategoryEngine,
      fields: ResourceFields[ResourceType],
      paginationConfiguration: PaginationConfiguration): BuiltAction = {

    async(ctx => Future.successful(fn(ctx)))
  }

  def apply(fn: => RestResponse[ResponseType])(
      implicit category: CategoryEngine,
      fields: ResourceFields[ResourceType],
      paginationConfiguration: PaginationConfiguration): BuiltAction = {

    async(_ => Futures.immediate(fn))
  }

  def async(fn: => Future[RestResponse[ResponseType]])(
      implicit category: CategoryEngine,
      fields: ResourceFields[ResourceType],
      paginationConfiguration: PaginationConfiguration): BuiltAction = {

    async(_ => fn)
  }

  def async(fn: RestContext[AuthType, BodyType] => Future[RestResponse[ResponseType]])(
      implicit category: CategoryEngine,
      fields: ResourceFields[ResourceType],
      _paginationConfiguration: PaginationConfiguration): BuiltAction = {

    new RestAction[RACType, AuthType, BodyType, ResourceKeyType, ResourceType, ResponseType] {
      override def restAuthGenerator = authGeneratorOrAuth
      override def restBodyParser = bodyParser
      override def restEngine = category
      override def fieldsEngine = fields
      override def paginationConfiguration = _paginationConfiguration
      override def errorHandler: PartialFunction[Throwable, RestError] = self.errorHandler
      override val keyFormat = self.keyFormat
      override val resourceFormat = self.resourceFormat
      override val executionContext = ec
      override val materializer = mat

      override def apply(
          context: RestContext[AuthType, BodyType]): Future[RestResponse[ResponseType]] =
        Futures.safelyCall(fn(context))
    }
  }
} 
Example 8
Source File: DefinedBodyTypeRestActionBuilder.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
package org.coursera.naptime.actions

import akka.stream.Materializer
import org.coursera.naptime.RestError
import org.coursera.naptime.access.HeaderAccessControl
import org.coursera.naptime.model.KeyFormat
import play.api.libs.json.OFormat
import play.api.mvc.BodyParser

import scala.concurrent.ExecutionContext


  def returning[NewResponseType](): DefinedBodyTypeRestActionBuilder[
    RACType,
    AuthType,
    BodyType,
    ResourceKeyType,
    ResourceType,
    NewResponseType] =
    new DefinedBodyTypeRestActionBuilder(authGeneratorOrAuth, bodyParser, errorHandler)

  override protected def bodyBuilder[Category, Response](): BodyBuilder[Category, Response] = {
    new RestActionBodyBuilder[
      Category,
      AuthType,
      BodyType,
      ResourceKeyType,
      ResourceType,
      Response](authGeneratorOrAuth, bodyParser, errorHandler)
  }

} 
Example 9
Source File: response.scala    From naptime   with Apache License 2.0 5 votes vote down vote up
package org.coursera.naptime

import com.linkedin.data.DataList
import org.coursera.common.stringkey.StringKeyFormat
import org.coursera.naptime.model.KeyFormat
import org.coursera.naptime.model.Keyed
import org.coursera.naptime.actions.NaptimeSerializer
import org.coursera.naptime.actions.RestActionCategoryEngine2
import play.api.libs.json.JsValue
import play.api.libs.json.OFormat
import play.api.mvc.Result
import play.api.mvc.Results

sealed abstract class RestResponse[+T] {
  def isOk: Boolean
  def isError: Boolean
  def isRedirect: Boolean

  def map[U](fn: T => U): RestResponse[U]
}

final case class Ok[+T](
    content: T,
    related: Map[ResourceName, Ok.Related[_, _]] = Map.empty,
    pagination: Option[ResponsePagination] = None,
    
  case class Related[K, A](
      resourceName: ResourceName,
      objects: Seq[Keyed[K, A]],
      jsonFormat: OFormat[A],
      keyFormat: KeyFormat[K],
      fields: ResourceFields[A]) {
    def toJson(requestFields: RequestFields): Seq[JsValue] = {
      val finalFields = requestFields
        .forResource(resourceName)
        .getOrElse(RequestFields.empty)
        .mergeWithDefaults(fields.defaultFields)
      JsonUtilities.outputSeq(objects, finalFields)(jsonFormat, keyFormat)
    }

    def toPegasus(requestFields: RequestFields, dataList: DataList): RequestFields = {
      RestActionCategoryEngine2.serializeCollection(
        dataList,
        objects,
        keyFormat,
        NaptimeSerializer.playJsonFormats(jsonFormat),
        requestFields,
        fields)
    }
  }

}

final case class RestError(error: NaptimeActionException) extends RestResponse[Nothing] {
  override val isOk = false
  override val isError = true
  override val isRedirect = false

  override def map[U](fn: Nothing => U): RestResponse[U] = this
}

final case class Redirect(url: String, isTemporary: Boolean) extends RestResponse[Nothing] {
  override val isOk = false
  override val isError = false
  override val isRedirect = true

  override def map[U](fn: Nothing => U): RestResponse[U] = this

  def result: Result = {
    if (isTemporary) {
      Results.TemporaryRedirect(url)
    } else {
      Results.MovedPermanently(url)
    }
  }
} 
Example 10
Source File: DesError.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.models.des

import play.api.libs.json.{Format, Json, OFormat, Reads}
import uk.gov.hmrc.vatapi.models.EnumJson
import uk.gov.hmrc.vatapi.models.des.DesErrorCode.DesErrorCode

case class DesError(code: DesErrorCode, reason: String)

object DesError {
  implicit val format: OFormat[DesError] = Json.format[DesError]
  implicit val reads: Reads[DesError] = Json.reads[DesError]
}

object DesErrorCode extends Enumeration {
  type DesErrorCode = Value

  val INVALID_VRN,
  INVALID_ARN,
  INVALID_PAYLOAD,
  INVALID_PERIODKEY,
  DUPLICATE_SUBMISSION,
  DATE_RANGE_TOO_LARGE,
  SERVER_ERROR,
  SERVICE_UNAVAILABLE,
  INVALID_IDNUMBER,
  INVALID_DATETO,
  INVALID_DATEFROM,
  NOT_FOUND,
  VRN_NOT_FOUND,
  NOT_FOUND_VRN,
  INVALID_SUBMISSION,
  INVALID_IDENTIFIER,
  INVALID_IDTYPE,
  INVALID_STATUS,
  INVALID_REGIME,
  INVALID_DATE_TO,
  INVALID_DATE_FROM,
  INVALID_DATE_RANGE,
  NOT_FOUND_BPKEY,
  INVALID_REGIMETYPE,
  INVALID_ONLYOPENITEMS,
  INVALID_INCLUDELOCKS,
  INVALID_CALCULATEACCRUEDINTEREST,
  INVALID_CUSTOMERPAYMENTINFORMATION,
  INVALID_DATA,
  INVALID_INPUTDATA,
  TAX_PERIOD_NOT_ENDED,
  INVALID_ORIGINATOR_ID
  = Value

  implicit val format: Format[DesErrorCode] = EnumJson.enumFormat(DesErrorCode,
    Some(s"Recognized DesErrorCode values: ${DesErrorCode.values.mkString(", ")}"))
} 
Example 11
Source File: ServiceMethod.scala    From typebus   with MIT License 5 votes vote down vote up
package io.surfkit.typebus.annotations

import java.nio.file.Files

import io.surfkit.typebus.ResourceDb
import play.api.libs.json.{Json, OFormat, Format}

import scala.annotation.{StaticAnnotation, compileTimeOnly}
import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context

@compileTimeOnly("enable macro to expand macro annotations")
class ServiceMethod extends StaticAnnotation {
  def macroTransform(annottees: Any*) = macro ServiceMethod.impl
}

object ServiceMethod extends ResourceDb{

  val databaseTableName = "_Service"

  sealed trait Store
  object Store{
    implicit val format: OFormat[Store] = Json.format[Store]
  }
  final case class ServiceMethod(in: String, out: String) extends Store
  object ServiceMethod{
    implicit val format: Format[ServiceMethod] = Json.format[ServiceMethod]
  }
  final case class ServiceStore(methods: Set[ServiceMethod]) extends Store
  object ServiceStore{
    implicit val format: Format[ServiceStore] = Json.format[ServiceStore]
  }

  var methods = Set.empty[ServiceMethod]

  def impl(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
    import c.universe._
    val result =
      annottees.map(_.tree).toList match {
        case q"$mods def $methodName[..$tpes]($arg, meta: EventMeta): Future[$returnType] = { ..$body }" :: Nil =>
        //case q"$mods def $methodName[..$tpes]($arg, meta: EventMeta): Future[$returnType]{..$body}" :: Nil =>
          // https://stackoverflow.com/questions/19379436/cant-access-parents-members-while-dealing-with-macro-annotations
          val retTpe = c.typecheck(q"(??? : $returnType)").tpe
          val argChild = arg.children.head
          val argTpe = c.typecheck(q"(??? : $argChild)").tpe
          //println(s"retTpe:${retTpe}  ${retTpe.typeSymbol.fullName}")
          //println(s"argTpe:${argTpe}  ${argTpe.typeSymbol.fullName}")
          // FIXME: packaging a jar will fail when trying to access the resource files.  For now we can skip this.
          try {
            methods += ServiceMethod(argTpe.typeSymbol.fullName, retTpe.typeSymbol.fullName)
            val servicePath = databaseTablePath(databaseTableName)
            Files.write(servicePath, serialiseServiceStore(ServiceStore(methods)).getBytes)
          }catch{
            case _: Throwable =>
          }
          q"""$mods def $methodName[..$tpes]($arg, meta: EventMeta): Future[$returnType] = { ..$body }"""

        case _ => c.abort(c.enclosingPosition, s"Annotation @ServiceMethod can be used only with methods of the form (T, EventMeta) => Future[U] instead of: ${annottees.map(_.tree).toList}")
      }
    c.Expr[Any](result)
  }

  def serialiseServiceStore(value: ServiceStore): String = Json.toJson(value).toString()
    //Pickle.intoBytes(value).array

  def deSerialiseServiceStore(json: String): ServiceStore = Json.parse(json).as[ServiceStore]
    //Unpickle[ServiceStore].fromBytes(java.nio.ByteBuffer.wrap(bytes))
} 
Example 12
Source File: Resources.scala    From cluster-broccoli   with Apache License 2.0 5 votes vote down vote up
package de.frosner.broccoli.nomad.models

import play.api.libs.functional.syntax._
import play.api.libs.json.{JsPath, OFormat}
import shapeless.tag
import shapeless.tag.@@
import squants.information.{Information, Megabytes}
import squants.time.{Frequency, Megahertz}


final case class Resources(cpu: Frequency @@ Resources.CPU, memory: Information @@ Resources.Memory)

object Resources {
  sealed trait CPU
  sealed trait Memory

  implicit val resourcesFormat: OFormat[Resources] = (
    (JsPath \ "CPU")
      .format[Double]
      .inmap[Frequency @@ CPU](mhz => tag[CPU](Megahertz(mhz)), _.toMegahertz)
      and
        (JsPath \ "MemoryMB")
          .format[Double]
          .inmap[Information @@ Memory](mb => tag[Memory](Megabytes(mb)), _.toMegabytes)
  )(Resources.apply, unlift(Resources.unapply))
} 
Example 13
Source File: ConsoleOutput.scala    From scastie   with Apache License 2.0 5 votes vote down vote up
package com.olegych.scastie.api

import play.api.libs.json._
import play.api.libs.json.OFormat

sealed trait ConsoleOutput {
  def show: String
}

object ConsoleOutput {
  case class SbtOutput(output: ProcessOutput) extends ConsoleOutput {
    def show: String = s"sbt: ${output.line}"
  }

  case class UserOutput(output: ProcessOutput) extends ConsoleOutput {
    def show: String = output.line
  }

  case class ScastieOutput(line: String) extends ConsoleOutput {
    def show: String = s"scastie: $line"
  }

  implicit object ConsoleOutputFormat extends Format[ConsoleOutput] {
    val formatSbtOutput: OFormat[SbtOutput] = Json.format[SbtOutput]
    private val formatUserOutput = Json.format[UserOutput]
    private val formatScastieOutput = Json.format[ScastieOutput]

    def writes(output: ConsoleOutput): JsValue = {
      output match {
        case sbtOutput: SbtOutput =>
          formatSbtOutput.writes(sbtOutput) ++ JsObject(Seq("tpe" -> JsString("SbtOutput")))
        case userOutput: UserOutput =>
          formatUserOutput.writes(userOutput) ++ JsObject(Seq("tpe" -> JsString("UserOutput")))
        case scastieOutput: ScastieOutput =>
          formatScastieOutput.writes(scastieOutput) ++ JsObject(Seq("tpe" -> JsString("ScastieOutput")))
      }
    }

    def reads(json: JsValue): JsResult[ConsoleOutput] = {
      json match {
        case obj: JsObject =>
          val vs = obj.value
          vs.get("tpe").orElse(vs.get("$type")) match {
            case Some(tpe) =>
              tpe match {
                case JsString("SbtOutput")  => formatSbtOutput.reads(json)
                case JsString("UserOutput") => formatUserOutput.reads(json)
                case JsString("ScastieOutput") =>
                  formatScastieOutput.reads(json)
                case _ => JsError(Seq())
              }
            case None => JsError(Seq())
          }
        case _ => JsError(Seq())
      }
    }
  }
} 
Example 14
Source File: Github.scala    From scastie   with Apache License 2.0 5 votes vote down vote up
package com.olegych.scastie.web.oauth2

import com.olegych.scastie.web.PlayJsonSupport

import akka.http.scaladsl._
import akka.http.scaladsl.model._
import HttpMethods.POST
import headers._
import Uri._
import unmarshalling.Unmarshal

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import com.olegych.scastie.api.User

import scala.concurrent.Future
import com.typesafe.config.ConfigFactory
import play.api.libs.json.{OFormat, Reads}

case class AccessToken(access_token: String)

class Github(implicit system: ActorSystem, materializer: ActorMaterializer) extends PlayJsonSupport {
  import system.dispatcher

  import play.api.libs.json._
  implicit val formatUser: OFormat[User] = Json.format[User]
  implicit val readAccessToken: Reads[AccessToken] = Json.reads[AccessToken]

  private val config =
    ConfigFactory.load().getConfig("com.olegych.scastie.web.oauth2")
  val clientId: String = config.getString("client-id")
  private val clientSecret = config.getString("client-secret")
  private val redirectUri = config.getString("uri") + "/callback"

  def getUserWithToken(token: String): Future[User] = info(token)
  def getUserWithOauth2(code: String): Future[User] = {
    def access = {
      Http()
        .singleRequest(
          HttpRequest(
            method = POST,
            uri = Uri("https://github.com/login/oauth/access_token").withQuery(
              Query(
                "client_id" -> clientId,
                "client_secret" -> clientSecret,
                "code" -> code,
                "redirect_uri" -> redirectUri
              )
            ),
            headers = List(Accept(MediaTypes.`application/json`))
          )
        )
        .flatMap(
          response => Unmarshal(response).to[AccessToken].map(_.access_token)
        )
    }

    access.flatMap(info)
  }

  private def info(token: String): Future[User] = {
    def fetchGithub(path: Path, query: Query = Query.Empty) = {
      HttpRequest(
        uri = Uri(s"https://api.github.com").withPath(path).withQuery(query),
        headers = List(Authorization(GenericHttpCredentials("token", token)))
      )
    }

    Http()
      .singleRequest(fetchGithub(Path.Empty / "user"))
      .flatMap(response => Unmarshal(response).to[User])
  }
} 
Example 15
Source File: RequiringFormats.scala    From courscala   with Apache License 2.0 5 votes vote down vote up
package org.coursera.common.jsonformat

import play.api.libs.json.Format
import play.api.libs.json.JsError
import play.api.libs.json.OFormat
import play.api.libs.json.Reads


object RequiringFormats {

  def requiringReads[T](delegate: Reads[T]): Reads[T] = Reads { json =>
    try {
      delegate.reads(json)
    } catch {
      case e: IllegalArgumentException => JsError(e.getMessage)
    }
  }

  def requiringFormat[T](delegate: Format[T]): Format[T] = {
    Format(requiringReads(delegate), delegate)
  }

  def requiringOFormat[T](delegate: OFormat[T]): OFormat[T] = {
    OFormat(requiringReads(delegate), delegate)
  }

} 
Example 16
Source File: TypedFormats.scala    From courscala   with Apache License 2.0 5 votes vote down vote up
package org.coursera.common.jsonformat

import org.coursera.common.stringkey.StringKeyFormat
import play.api.libs.json.Format
import play.api.libs.json.Json
import play.api.libs.json.OFormat
import play.api.libs.json.OWrites
import play.api.libs.json.Reads
import play.api.libs.json.Writes
import play.api.libs.json.__


object TypedFormats {

  def typedDefinitionFormat[T, D](
      typeName: T,
      defaultFormat: Format[D])
      (implicit stringKeyFormat: StringKeyFormat[T]): OFormat[D] = {
    OFormat(
      typedDefinitionReads(typeName, defaultFormat),
      typedDefinitionWrites(typeName, defaultFormat))
  }

  def typedDefinitionReads[T, D](
      typeName: T,
      defaultReads: Reads[D])
      (implicit stringKeyFormat: StringKeyFormat[T]): Reads[D] = {
    import JsonFormats.Implicits.ReadsPathMethods
    implicit val typeNameFormat = JsonFormats.stringKeyFormat[T]

    for {
      _ <- (__ \ "typeName").read[T].filter(_ == typeName).withRootPath
      definition <- {
        val definitionExtractingReads = (__ \ "definition").json.pick.withRootPath
        defaultReads.compose(definitionExtractingReads)
      }
    } yield {
      definition
    }
  }

  def typedDefinitionWrites[T, D](
      typeName: T,
      defaultWrites: Writes[D])
      (implicit stringKeyFormat: StringKeyFormat[T]): OWrites[D] = {
    implicit val typeNameFormat = JsonFormats.stringKeyFormat[T]
    OWrites { model: D =>
      val modelJson = Json.toJson(model)(defaultWrites)
      Json.obj("typeName" -> typeName, "definition" -> modelJson)
    }
  }

} 
Example 17
Source File: OrFormats.scala    From courscala   with Apache License 2.0 5 votes vote down vote up
package org.coursera.common.jsonformat

import play.api.libs.json.Format
import play.api.libs.json.JsError
import play.api.libs.json.OFormat
import play.api.libs.json.OWrites
import play.api.libs.json.Reads
import play.api.libs.json.Writes

import scala.reflect.ClassTag
import scala.reflect.classTag

object OrFormats {

  def unimplementedReads[T: ClassTag]: Reads[T] = {
    Reads(_ => JsError(s"Invoked `unimplementedReads` for ${classTag[T]}"))
  }

  def unimplementedWrites[T: ClassTag]: Writes[T] = Writes { _ =>
    throw new UnsupportedOperationException(s"Invoked `unimplementedOWrites for ${classTag[T]}")
  }

  def unimplementedOWrites[T: ClassTag]: OWrites[T] = OWrites { _ =>
    throw new UnsupportedOperationException(s"Invoked `unimplementedOWrites for ${classTag[T]}")
  }

  def unimplementedFormat[T: ClassTag]: Format[T] = Format(unimplementedReads, unimplementedWrites)

  def unimplementedOFormat[T: ClassTag]: OFormat[T] =
    OFormat(unimplementedReads[T], unimplementedOWrites[T])

  implicit class OrReads[A](reads: Reads[A]) {
    def orReads[B <: A: Reads]: Reads[A] = {
      import play.api.libs.functional.syntax._
      reads or implicitly[Reads[B]].map(b => b: A)
    }
  }

  implicit class OrWrites[A](writes: Writes[A]) {
    def orWrites[B <: A: Writes: ClassTag](implicit classTag: ClassTag[A]): Writes[A] = Writes {
      case b: B => implicitly[Writes[B]].writes(b)
      case a: A => writes.writes(a)
    }
  }

  implicit class OrOWrites[A](oWrites: OWrites[A]) {
    def orOWrites[B <: A: OWrites: ClassTag](implicit classTag: ClassTag[A]): OWrites[A] = OWrites {
      case b: B => implicitly[OWrites[B]].writes(b)
      case a: A => oWrites.writes(a)
    }
  }

  implicit class OrFormat[A](format: Format[A]) {
    def orFormat[B <: A: Format: ClassTag](implicit classTag: ClassTag[A]): Format[A] = {
      Format(format.orReads[B], format.orWrites[B])
    }
  }

  implicit class OrOFormat[A](oFormat: OFormat[A]) {
    def orOFormat[B <: A: OFormat: ClassTag](implicit classTag: ClassTag[A]): OFormat[A] = {
      OFormat(oFormat.orReads[B], oFormat.orOWrites[B])
    }
  }

} 
Example 18
Source File: FlatTypedFormats.scala    From courscala   with Apache License 2.0 5 votes vote down vote up
package org.coursera.common.jsonformat

import org.coursera.common.stringkey.StringKeyFormat
import play.api.libs.json.Json
import play.api.libs.json.OFormat
import play.api.libs.json.OWrites
import play.api.libs.json.Reads
import play.api.libs.json.__


object FlatTypedFormats {

  def flatTypedDefinitionFormat[T: StringKeyFormat, D](typeName: T, defaultFormat: OFormat[D]):
    OFormat[D] = {

    OFormat(
      flatTypedDefinitionReads(typeName, defaultFormat),
      flatTypedDefinitionWrites(typeName, defaultFormat))
  }

  def flatTypedDefinitionReads[T: StringKeyFormat, D](typeName: T, defaultReads: Reads[D]):
    Reads[D] = {

    import JsonFormats.Implicits.ReadsPathMethods
    implicit val typeNameFormat = JsonFormats.stringKeyFormat[T]

    for {
      _ <- (__ \ "typeName").read[T].filter(_ == typeName).withRootPath
      definition <- {
        val typeNameDroppingReads = (__ \ "typeName").json.prune.withRootPath
        defaultReads.compose(typeNameDroppingReads)
      }
    } yield {
      definition
    }
  }

  def flatTypedDefinitionWrites[T: StringKeyFormat, D](typeName: T, defaultWrites: OWrites[D]):
    OWrites[D] = {

    implicit val typeNameFormat = JsonFormats.stringKeyFormat[T]
    OWrites { model: D =>
      val modelJson = defaultWrites.writes(model)

      require(!modelJson.keys.contains("typeName"), "Model cannot contain reserved field 'typeName'")
      modelJson + ("typeName" -> Json.toJson(typeName))
    }
  }

} 
Example 19
Source File: UpDownRule.scala    From smui   with Apache License 2.0 5 votes vote down vote up
package models.rules

import anorm.SqlParser.get
import anorm.{NamedParameter, RowParser, ~}
import models.{Id, IdObject, SearchInputId}
import play.api.libs.json.{Json, OFormat}

class UpDownRuleId(id: String) extends Id(id)
object UpDownRuleId extends IdObject[UpDownRuleId](new UpDownRuleId(_))


case class UpDownRule(id: UpDownRuleId = UpDownRuleId(),
                      upDownType: Int,
                      boostMalusValue: Int,
                      term: String,
                      isActive: Boolean) extends RuleWithTerm {

  override def toNamedParameters(searchInputId: SearchInputId): Seq[NamedParameter] = {
    super.toNamedParameters(searchInputId) ++ Seq[NamedParameter](
      UpDownRule.BOOST_MALUS_VALUE -> boostMalusValue,
      UpDownRule.UP_DOWN_TYPE -> upDownType
    )
  }
}

object UpDownRule extends RuleObjectWithTerm[UpDownRule] {

  val TABLE_NAME = "up_down_rule"

  val UP_DOWN_TYPE = "up_down_type"
  val BOOST_MALUS_VALUE = "boost_malus_value"

  val TYPE_UP = 0
  val TYPE_DOWN = 1

  override def fieldNames: Seq[String] = super.fieldNames ++ Seq(BOOST_MALUS_VALUE, UP_DOWN_TYPE)

  implicit val jsonFormat: OFormat[UpDownRule] = Json.format[UpDownRule]

  val sqlParser: RowParser[UpDownRule] = {
    get[UpDownRuleId](s"$TABLE_NAME.$ID") ~
      get[Int](s"$TABLE_NAME.$UP_DOWN_TYPE") ~
      get[Int](s"$TABLE_NAME.$BOOST_MALUS_VALUE") ~
      get[String](s"$TABLE_NAME.$TERM") ~
      get[Int](s"$TABLE_NAME.$STATUS") map { case id ~ upDownType ~ boostMalusValue ~ term ~ status =>
      UpDownRule(id, upDownType, boostMalusValue, term, isActiveFromStatus(status))
    }
  }

} 
Example 20
Source File: HttpTradingMarkets.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.domain.account.PublicKey
import io.swagger.annotations.ApiModelProperty
import play.api.libs.json.{Json, OFormat}

case class HttpTradingMarkets(@ApiModelProperty(
                                value = "Base58 encoded Matcher Public Key",
                                dataType = "string",
                                example = "HBqhfdFASRQ5eBBpu2y6c6KKi1az6bMx8v1JxX4iW1Q8",
                              ) matcherPublicKey: PublicKey,
                              @ApiModelProperty(
                                value = "Market data with meta information",
                                dataType = "[Lcom.wavesplatform.dex.api.http.entities.HttpMarketDataWithMeta;",
                              ) markets: Seq[HttpMarketDataWithMeta])

object HttpTradingMarkets {
  implicit val httpTradingMarketsFormat: OFormat[HttpTradingMarkets] = Json.format[HttpTradingMarkets]
} 
Example 21
Source File: HttpOrderBookInfo.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import io.swagger.annotations.ApiModelProperty
import play.api.libs.json.{Json, OFormat}

case class HttpOrderBookInfo(@ApiModelProperty(
                              value = "Restrictions of orders' amount and price",
                              allowEmptyValue = true
                            ) restrictions: Option[HttpOrderRestrictions],
                             @ApiModelProperty(
                              value = "Matching rules, tick size in particular",
                              allowEmptyValue = true
                            )
                            matchingRules: HttpMatchingRules)

object HttpOrderBookInfo {
  implicit val httpOrderBookInfoFormat: OFormat[HttpOrderBookInfo] = Json.format[HttpOrderBookInfo]
} 
Example 22
Source File: HttpOrderBookHistoryItem.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.domain.asset.{Asset, AssetPair}
import com.wavesplatform.dex.domain.order.{Order, OrderType}
import com.wavesplatform.dex.model.{AcceptedOrderType, OrderInfo, OrderStatus}
import io.swagger.annotations.ApiModelProperty
import play.api.libs.json.{Json, OFormat}

case class HttpOrderBookHistoryItem(@ApiModelProperty(
                                      value = "Base58 encoded Order ID",
                                      dataType = "string",
                                      example = "7VEr4T9icqopHWLawGAZ7AQiJbjAcnzXn65ekYvbpwnN"
                                    ) id: Order.Id,
                                    @ApiModelProperty(
                                      value = "Order side (sell or buy)",
                                      dataType = "string",
                                      example = "sell"
                                    ) `type`: OrderType,
                                    @ApiModelProperty(
                                      value = "Order type (limit or market)",
                                      dataType = "string",
                                      example = "limit"
                                    ) orderType: AcceptedOrderType,
                                    @ApiModelProperty() amount: Long,
                                    @ApiModelProperty() filled: Long,
                                    @ApiModelProperty() price: Long,
                                    @ApiModelProperty() fee: Long,
                                    @ApiModelProperty() filledFee: Long,
                                    @ApiModelProperty(
                                      value = "Base58 encoded Matcher fee asset ID",
                                      dataType = "string",
                                      example = "6RQYnag6kTXaoGi3yPmX9JMpPya8WQntSohisKKCMGr"
                                    ) feeAsset: Asset,
                                    @ApiModelProperty() timestamp: Long,
                                    @ApiModelProperty(
                                      value = "Status",
                                      allowableValues = "Accepted, NotFound, PartiallyFilled, Filled, Cancelled"
                                    ) status: String,
                                    @ApiModelProperty() assetPair: AssetPair,
                                    @ApiModelProperty(value = "Average weighed price") avgWeighedPrice: Long,
                                    @ApiModelProperty(
                                      value = "Order version",
                                      dataType = "integer",
                                      example = "3"
                                    ) version: Byte)

object HttpOrderBookHistoryItem {

  implicit val httpOrderBookHistoryItemFormat: OFormat[HttpOrderBookHistoryItem] = Json.format

  def fromOrderInfo(id: Order.Id, info: OrderInfo[OrderStatus]): HttpOrderBookHistoryItem = HttpOrderBookHistoryItem(
    id = id,
    `type` = info.side,
    orderType = info.orderType,
    amount = info.amount,
    filled = info.status.filledAmount,
    price = info.price,
    fee = info.matcherFee,
    filledFee = info.status.filledFee,
    feeAsset = info.feeAsset,
    timestamp = info.timestamp,
    status = info.status.name,
    assetPair = info.assetPair,
    avgWeighedPrice = info.avgWeighedPrice,
    version = info.orderVersion
  )
} 
Example 23
Source File: HttpOrderRestrictions.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.json
import com.wavesplatform.dex.settings.OrderRestrictionsSettings
import io.swagger.annotations.ApiModelProperty
import play.api.libs.json.{Format, Json, OFormat}

case class HttpOrderRestrictions(@ApiModelProperty(dataType = "string", example = "0.001") stepAmount: Double,
                                 @ApiModelProperty(dataType = "string", example = "1000000") minAmount: Double,
                                 @ApiModelProperty(dataType = "string", example = "0.00000001") maxAmount: Double,
                                 @ApiModelProperty(dataType = "string", example = "0.001") stepPrice: Double,
                                 @ApiModelProperty(dataType = "string", example = "100000") minPrice: Double,
                                 @ApiModelProperty(dataType = "string", example = "0.00000001") maxPrice: Double)

object HttpOrderRestrictions {

  implicit val doubleFormat: Format[Double]                                = json.stringAsDoubleFormat
  implicit val httpOrderRestrictionsFormat: OFormat[HttpOrderRestrictions] = Json.format[HttpOrderRestrictions]

  def fromSettings(settings: OrderRestrictionsSettings): HttpOrderRestrictions =
    HttpOrderRestrictions(
      stepAmount = settings.stepAmount,
      minAmount = settings.minAmount,
      maxAmount = settings.maxAmount,
      stepPrice = settings.stepPrice,
      minPrice = settings.minPrice,
      maxPrice = settings.maxPrice
    )
} 
Example 24
Source File: HttpMarketDataWithMeta.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.domain.asset.Asset
import io.swagger.annotations.ApiModelProperty
import play.api.libs.json.{Json, OFormat}

case class HttpMarketDataWithMeta(
    @ApiModelProperty(
      value = "Base58 encoded amount asset ID",
      dataType = "string",
      example = "8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS"
    ) amountAsset: Asset,
    @ApiModelProperty(example = "BTC") amountAssetName: String,
    @ApiModelProperty(value = "Info about amount asset decimals", allowEmptyValue = true) amountAssetInfo: Option[HttpAssetInfo],
    @ApiModelProperty(
      value = "Base58 encoded price asset ID",
      dataType = "string",
      example = "34N9YcEETLWn93qYQ64EsP1x89tSruJU44RrEMSXXEPJ"
    ) priceAsset: Asset,
    @ApiModelProperty(example = "USDT") priceAssetName: String,
    @ApiModelProperty(value = "Info about price asset decimals", allowEmptyValue = true) priceAssetInfo: Option[HttpAssetInfo],
    @ApiModelProperty() created: Long,
    @ApiModelProperty(allowEmptyValue = true) restrictions: Option[HttpOrderRestrictions],
    @ApiModelProperty() matchingRules: HttpMatchingRules)

object HttpMarketDataWithMeta {
  implicit val httpMarketDataWithMetaFormat: OFormat[HttpMarketDataWithMeta] = Json.format[HttpMarketDataWithMeta]
} 
Example 25
Source File: PredefinedTag.scala    From smui   with Apache License 2.0 5 votes vote down vote up
package models

import java.io.InputStream
import java.sql.Connection

import play.api.Logger
import play.api.libs.json.{Json, OFormat}

case class PredefinedTag(property: Option[String],
                         value: String,
                         solrIndexName: Option[String],
                         exported: Option[Boolean]) {

}

object PredefinedTag {

  val logger = Logger(getClass)

  implicit val jsonFormat: OFormat[PredefinedTag] = Json.format[PredefinedTag]

  def fromStream(stream: InputStream): Seq[PredefinedTag] = {
    try {
      Json.parse(stream).as[Seq[PredefinedTag]]
    } finally {
      stream.close()
    }
  }

  def updateInDB(predefinedTags: Seq[PredefinedTag])(implicit connection: Connection): (Seq[InputTagId], Seq[InputTag]) = {
    val indexIdsByName = SolrIndex.listAll.map(i => i.name -> i.id).toMap
    val tagsInDBByContent = InputTag.loadAll().map(t => t.tagContent -> t).toMap

    val newTags = predefinedTags.map { tag =>
      TagContent(tag.solrIndexName.flatMap(indexIdsByName.get), tag.property, tag.value) -> tag
    }.toMap

    val toDelete = tagsInDBByContent.filter { case (content, tag) => tag.predefined && !newTags.contains(content) }.map(_._2.id).toSeq
    val toInsert = newTags.filter(t => !tagsInDBByContent.contains(t._1)).map { case (tc, t) =>
      InputTag.create(tc.solrIndexId, t.property, t.value, t.exported.getOrElse(true), predefined = true)
    }.toSeq

    InputTag.insert(toInsert: _*)
    InputTag.deleteByIds(toDelete)
    if (toDelete.nonEmpty || toInsert.nonEmpty) {
      logger.info(s"Inserted ${toInsert.size} new predefined tags into the DB and deleted ${toDelete.size} no longer existing predefined tags.")
    }

    (toDelete, toInsert)
  }

} 
Example 26
Source File: SearchInputWithRules.scala    From smui   with Apache License 2.0 5 votes vote down vote up
package models

import java.sql.Connection
import models.rules._
import play.api.libs.json.{Json, OFormat}

case class SearchInputWithRules(id: SearchInputId,
                                term: String,
                                synonymRules: List[SynonymRule] = Nil,
                                upDownRules: List[UpDownRule] = Nil,
                                filterRules: List[FilterRule] = Nil,
                                deleteRules: List[DeleteRule] = Nil,
                                redirectRules: List[RedirectRule] = Nil,
                                tags: Seq[InputTag] = Seq.empty,
                                isActive: Boolean,
                                comment: String) {

  lazy val trimmedTerm: String = term.trim()

  def allRules: List[Rule] = {
    synonymRules ++ upDownRules ++ filterRules ++ deleteRules ++ redirectRules
  }

  def hasAnyActiveRules: Boolean = {
    allRules.exists(r => r.isActive)
  }

}

object SearchInputWithRules {

  implicit val jsonFormat: OFormat[SearchInputWithRules] = Json.format[SearchInputWithRules]

  def loadById(id: SearchInputId)(implicit connection: Connection): Option[SearchInputWithRules] = {
    SearchInput.loadById(id).map { input =>
      SearchInputWithRules(input.id, input.term,
        synonymRules = SynonymRule.loadByInputId(id),
        upDownRules = UpDownRule.loadByInputId(id),
        filterRules = FilterRule.loadByInputId(id),
        deleteRules = DeleteRule.loadByInputId(id),
        redirectRules = RedirectRule.loadByInputId(id),
        tags = TagInputAssociation.loadTagsBySearchInputId(id),
        isActive = input.isActive,
        comment = input.comment)
    }
  }

  
  def loadWithUndirectedSynonymsAndTagsForSolrIndexId(solrIndexId: SolrIndexId)(implicit connection: Connection): List[SearchInputWithRules] = {
    val inputs = SearchInput.loadAllForIndex(solrIndexId)
    val rules = SynonymRule.loadUndirectedBySearchInputIds(inputs.map(_.id))
    val tags = TagInputAssociation.loadTagsBySearchInputIds(inputs.map(_.id))

    inputs.map { input =>
      SearchInputWithRules(input.id, input.term,
        synonymRules = rules.getOrElse(input.id, Nil).toList,
        tags = tags.getOrElse(input.id, Seq.empty),
        isActive = input.isActive,
        comment = input.comment) // TODO consider only transferring "hasComment" for list overview
    }
  }

  def update(searchInput: SearchInputWithRules)(implicit connection: Connection): Unit = {
    SearchInput.update(searchInput.id, searchInput.term, searchInput.isActive, searchInput.comment)

    SynonymRule.updateForSearchInput(searchInput.id, searchInput.synonymRules)
    UpDownRule.updateForSearchInput(searchInput.id, searchInput.upDownRules)
    FilterRule.updateForSearchInput(searchInput.id, searchInput.filterRules)
    DeleteRule.updateForSearchInput(searchInput.id, searchInput.deleteRules)
    RedirectRule.updateForSearchInput(searchInput.id, searchInput.redirectRules)

    TagInputAssociation.updateTagsForSearchInput(searchInput.id, searchInput.tags.map(_.id))
  }

  def delete(id: SearchInputId)(implicit connection: Connection): Int = {
    val deleted = SearchInput.delete(id)
    if (deleted > 0) {
      for (rule <- Rule.allRules) {
        rule.deleteBySearchInput(id)
      }
      TagInputAssociation.deleteBySearchInputId(id)
    }
    deleted
  }

} 
Example 27
Source File: SuggestedSolrField.scala    From smui   with Apache License 2.0 5 votes vote down vote up
package models

import java.sql.Connection
import java.time.LocalDateTime

import anorm.SqlParser.get
import anorm._
import play.api.libs.json.{Json, OFormat}

class SuggestedSolrFieldId(id: String) extends Id(id)
object SuggestedSolrFieldId extends IdObject[SuggestedSolrFieldId](new SuggestedSolrFieldId(_))


case class SuggestedSolrField(id: SuggestedSolrFieldId = SuggestedSolrFieldId(),
                         name: String) {

}

object SuggestedSolrField {

  implicit val jsonFormat: OFormat[SuggestedSolrField] = Json.format[SuggestedSolrField]

  val TABLE_NAME = "suggested_solr_field"
  val ID = "id"
  val NAME = "name"
  val SOLR_INDEX_ID = "solr_index_id"
  val LAST_UPDATE = "last_update"

  val sqlParser: RowParser[SuggestedSolrField] = {
    get[SuggestedSolrFieldId](s"$TABLE_NAME.$ID") ~
      get[String](s"$TABLE_NAME.$NAME") map { case id ~ name =>
      SuggestedSolrField(id, name)
    }
  }

  def listAll(solrIndexId: SolrIndexId)(implicit connection: Connection): List[SuggestedSolrField] = {
    SQL"select * from #$TABLE_NAME where #$SOLR_INDEX_ID = $solrIndexId order by #$NAME asc".as(sqlParser.*)
  }

  def insert(solrIndexId: SolrIndexId, fieldName: String)(implicit connection: Connection): SuggestedSolrField = {
    val field = SuggestedSolrField(SuggestedSolrFieldId(), fieldName)
    SQL(s"insert into $TABLE_NAME($ID, $NAME, $SOLR_INDEX_ID, $LAST_UPDATE) values ({$ID}, {$NAME}, {$SOLR_INDEX_ID}, {$LAST_UPDATE})")
      .on(
        ID -> field.id,
        NAME -> fieldName,
        SOLR_INDEX_ID -> solrIndexId,
        LAST_UPDATE -> LocalDateTime.now()
      )
      .execute()
    field
  }


} 
Example 28
Source File: HttpMarketStatus.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.api.http.entities

import com.wavesplatform.dex.actors.orderbook.OrderBookActor.MarketStatus
import com.wavesplatform.dex.domain.order.OrderType
import com.wavesplatform.dex.model.{LastTrade, LevelAgg}
import io.swagger.annotations.ApiModelProperty
import play.api.libs.json.{Json, OFormat}

case class HttpMarketStatus(@ApiModelProperty(
                              allowEmptyValue = true,
                              dataType = "integer"
                            ) lastPrice: Option[Long],
                            @ApiModelProperty(
                              allowEmptyValue = true,
                              dataType = "integer"
                            ) lastAmount: Option[Long],
                            @ApiModelProperty(
                              value = "Side (sell or buy)",
                              dataType = "string",
                              example = "buy",
                              allowEmptyValue = true
                            )
                            lastSide: Option[OrderType],
                            @ApiModelProperty(
                              allowEmptyValue = true,
                              dataType = "integer"
                            ) bid: Option[Long],
                            @ApiModelProperty(
                              allowEmptyValue = true,
                              dataType = "integer"
                            ) bidAmount: Option[Long],
                            @ApiModelProperty(
                              allowEmptyValue = true,
                              dataType = "integer"
                            ) ask: Option[Long],
                            @ApiModelProperty(
                              allowEmptyValue = true,
                              dataType = "integer"
                            ) askAmount: Option[Long]) {

  @ApiModelProperty(hidden = true)
  val lastTrade: Option[LastTrade] =
    for {
      lp <- lastPrice
      la <- lastAmount
      ls <- lastSide
    } yield LastTrade(lp, la, ls)

  @ApiModelProperty(hidden = true)
  val bestBid: Option[LevelAgg] =
    for {
      bba <- bidAmount
      bbp <- bid
    } yield LevelAgg(bba, bbp)

  @ApiModelProperty(hidden = true)
  val bestAsk: Option[LevelAgg] =
    for {
      baa <- askAmount
      bap <- ask
    } yield LevelAgg(baa, bap)
}

object HttpMarketStatus {

  def fromMarketStatus(ms: MarketStatus): HttpMarketStatus =
    HttpMarketStatus(
      lastPrice = ms.lastTrade.map(_.price),
      lastAmount = ms.lastTrade.map(_.amount),
      lastSide = ms.lastTrade.map(_.side),
      bid = ms.bestBid.map(_.price),
      bidAmount = ms.bestBid.map(_.amount),
      ask = ms.bestAsk.map(_.price),
      askAmount = ms.bestAsk.map(_.amount)
    )

  implicit val httpMarketStatusFormat: OFormat[HttpMarketStatus] = Json.format[HttpMarketStatus]
} 
Example 29
Source File: DeleteRule.scala    From smui   with Apache License 2.0 5 votes vote down vote up
package models.rules

import anorm.SqlParser.get
import anorm.{RowParser, ~}
import models.{Id, IdObject}
import play.api.libs.json.{Json, OFormat}

class DeleteRuleId(id: String) extends Id(id)
object DeleteRuleId extends IdObject[DeleteRuleId](new DeleteRuleId(_))


case class DeleteRule(id: DeleteRuleId = DeleteRuleId(),
                      term: String,
                      isActive: Boolean) extends RuleWithTerm {

}

object DeleteRule extends RuleObjectWithTerm[DeleteRule] {

  val TABLE_NAME = "delete_rule"

  implicit val jsonFormat: OFormat[DeleteRule] = Json.format[DeleteRule]

  override val sqlParser: RowParser[DeleteRule] = {
    get[DeleteRuleId](s"$TABLE_NAME.$ID") ~
      get[String](s"$TABLE_NAME.$TERM") ~
      get[Int](s"$TABLE_NAME.$STATUS") map { case id ~ term ~ status =>
      DeleteRule(id, term, isActiveFromStatus(status))
    }
  }
} 
Example 30
Source File: SynonymRule.scala    From smui   with Apache License 2.0 5 votes vote down vote up
package models.rules

import java.sql.Connection

import anorm.SqlParser.get
import anorm._
import models.{Id, IdObject, SearchInputId}
import play.api.libs.json.{Json, OFormat}

class SynonymRuleId(id: String) extends Id(id)
object SynonymRuleId extends IdObject[SynonymRuleId](new SynonymRuleId(_))

case class SynonymRule(id: SynonymRuleId = SynonymRuleId(),
                       synonymType: Int,
                       term: String,
                       isActive: Boolean) extends RuleWithTerm {

  override def toNamedParameters(searchInputId: SearchInputId): Seq[NamedParameter] = {
    super.toNamedParameters(searchInputId) ++ Seq[NamedParameter](
      SynonymRule.TYPE -> synonymType
    )
  }
}

object SynonymRule extends RuleObjectWithTerm[SynonymRule] {

  val TABLE_NAME = "synonym_rule"
  val TYPE = "synonym_type"

  val TYPE_UNDIRECTED = 0
  val TYPE_DIRECTED = 1

  implicit val jsonFormat: OFormat[SynonymRule] = Json.format[SynonymRule]

  override def fieldNames: Seq[String] = super.fieldNames :+ TYPE

  val sqlParser: RowParser[SynonymRule] = {
    get[SynonymRuleId](s"$TABLE_NAME.$ID") ~
      get[Int](s"$TABLE_NAME.$TYPE") ~
      get[String](s"$TABLE_NAME.$TERM") ~
      get[Int](s"$TABLE_NAME.$STATUS") map { case id ~ synonymType ~ term ~ status =>
        SynonymRule(id, synonymType, term, isActiveFromStatus(status))
    }
  }

  def loadUndirectedBySearchInputIds(ids: Seq[SearchInputId])(implicit connection: Connection): Map[SearchInputId, Seq[SynonymRule]] = {
    ids.grouped(100).toSeq.flatMap { idGroup =>
      SQL"select * from #$TABLE_NAME where #$TYPE = #$TYPE_UNDIRECTED AND #$SEARCH_INPUT_ID in ($idGroup)".as((sqlParser ~ get[SearchInputId](SEARCH_INPUT_ID)).*).map { case rule ~ id =>
        id -> rule
      }
    }.groupBy(_._1).mapValues(_.map(_._2))
  }

} 
Example 31
Source File: RedirectRule.scala    From smui   with Apache License 2.0 5 votes vote down vote up
package models.rules

import anorm.SqlParser.get
import anorm.{NamedParameter, RowParser, ~}
import models.{Id, IdObject, SearchInputId}
import play.api.libs.json.{Json, OFormat}

class RedirectRuleId(id: String) extends Id(id)
object RedirectRuleId extends IdObject[RedirectRuleId](new RedirectRuleId(_))


case class RedirectRule(id: RedirectRuleId = RedirectRuleId(),
                        target: String,
                        isActive: Boolean) extends Rule {

  override def toNamedParameters(searchInputId: SearchInputId): Seq[NamedParameter] = {
    super.toNamedParameters(searchInputId) ++ Seq[NamedParameter](
      RedirectRule.TARGET -> target
    )
  }
}

object RedirectRule extends RuleObject[RedirectRule] {

  val TABLE_NAME = "redirect_rule"
  val TARGET = "target"

  implicit val jsonFormat: OFormat[RedirectRule] = Json.format[RedirectRule]

  override def fieldNames: Seq[String] = super.fieldNames :+ TARGET

  override def orderByField: String = TARGET

  override val sqlParser: RowParser[RedirectRule] = {
    get[RedirectRuleId](s"$TABLE_NAME.$ID") ~
      get[String](s"$TABLE_NAME.$TARGET") ~
      get[Int](s"$TABLE_NAME.$STATUS") map { case id ~ target ~ status =>
      RedirectRule(id, target, isActiveFromStatus(status))
    }
  }

} 
Example 32
Source File: Metadata.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.models.nrs.request

import org.joda.time.DateTime
import play.api.libs.json.{Format, JsValue, Json, OFormat}
import utils.DateUtils

case class Metadata(businessId: String,
                    notableEvent: String,
                    payloadContentType: String,
                    payloadSha256Checksum: Option[String],
                    userSubmissionTimestamp: DateTime,
                    identityData: Option[IdentityData],
                    userAuthToken: String,
                    headerData: JsValue,
                    searchKeys: SearchKeys)

object Metadata {
  implicit val idformat: OFormat[IdentityData] = IdentityData.format
  implicit val dateFormats: Format[DateTime] = DateUtils.isoInstantDateFormat
  implicit val format: OFormat[Metadata] = Json.format[Metadata]
} 
Example 33
Source File: IdentityData.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package v1.models.nrs.request

import org.joda.time.{DateTime, LocalDate}
import play.api.libs.json.{Format, Json, OFormat}
import uk.gov.hmrc.auth.core.retrieve._
import uk.gov.hmrc.auth.core.{AffinityGroup, ConfidenceLevel, CredentialRole}
import utils.DateUtils

case class IdentityData(internalId: Option[String] = None,
                        externalId: Option[String] = None,
                        agentCode: Option[String] = None,
                        credentials: Option[Credentials] = None,
                        confidenceLevel: ConfidenceLevel,
                        nino: Option[String] = None,
                        saUtr: Option[String] = None,
                        name: Option[Name] = None,
                        dateOfBirth: Option[LocalDate] = None,
                        email: Option[String] = None,
                        agentInformation: AgentInformation,
                        groupIdentifier: Option[String] = None,
                        credentialRole: Option[CredentialRole],
                        mdtpInformation: Option[MdtpInformation] = None,
                        itmpName: ItmpName,
                        itmpDateOfBirth: Option[LocalDate] = None,
                        itmpAddress: ItmpAddress,
                        affinityGroup: Option[AffinityGroup],
                        credentialStrength: Option[String] = None,
                        loginTimes: LoginTimes)

object IdentityData {
  implicit val localDateFormats: Format[LocalDate] = DateUtils.dateFormat
  implicit val credFormat: OFormat[Credentials] = Json.format[Credentials]
  implicit val nameFormat: OFormat[Name] = Json.format[Name]
  implicit val agentInfoFormat: OFormat[AgentInformation] = Json.format[AgentInformation]
  implicit val mdtpInfoFormat: OFormat[MdtpInformation] = Json.format[MdtpInformation]
  implicit val itmpNameFormat: OFormat[ItmpName] = Json.format[ItmpName]
  implicit val itmpAddressFormat: OFormat[ItmpAddress] = Json.format[ItmpAddress]
  implicit val dateTimeFormats: Format[DateTime] = DateUtils.isoInstantDateFormat
  implicit val loginTimesFormat: OFormat[LoginTimes] = Json.format[LoginTimes]
  implicit val format: OFormat[IdentityData] = Json.format[IdentityData]
} 
Example 34
Source File: ApiDefinition.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package definition

import play.api.libs.json.{Format, Json, OFormat}
import utils.enums.Enums

case class Access(`type`: String, whitelistedApplicationIds: Seq[String])

object Access {
  implicit val formatAccess: OFormat[Access] = Json.format[Access]
}

case class Parameter(name: String, required: Boolean = false)

object Parameter {
  implicit val formatParameter: OFormat[Parameter] = Json.format[Parameter]
}

case class PublishingException(message: String) extends Exception(message)

sealed trait APIStatus

object APIStatus extends Enumeration {
  case object ALPHA extends APIStatus
  case object BETA extends APIStatus
  case object STABLE extends APIStatus
  case object DEPRECATED extends APIStatus
  case object RETIRED extends APIStatus

  implicit val formatApiVersion: Format[APIStatus] = Enums.format[APIStatus]
  val parser: PartialFunction[String, APIStatus] = Enums.parser[APIStatus]
}

case class APIVersion(version: String, access: Option[Access] = None, status: APIStatus, endpointsEnabled: Boolean) {

  require(version.nonEmpty, "version is required")
}

object APIVersion {
  implicit val formatAPIVersion: OFormat[APIVersion] = Json.format[APIVersion]
}

case class APIDefinition(name: String,
                         description: String,
                         context: String,
                         categories: Seq[String],
                         versions: Seq[APIVersion],
                         requiresTrust: Option[Boolean]) {

  require(name.nonEmpty, "name is required")
  require(context.nonEmpty, "context is required")
  require(categories.nonEmpty, "at least one category is required")
  require(description.nonEmpty, "description is required")
  require(versions.nonEmpty, "at least one version is required")
  require(uniqueVersions, "version numbers must be unique")

  private def uniqueVersions = {
    !versions.map(_.version).groupBy(identity).mapValues(_.size).exists(_._2 > 1)
  }
}

object APIDefinition {
  implicit val formatAPIDefinition: OFormat[APIDefinition] = Json.format[APIDefinition]
}

case class Scope(key: String, name: String, description: String)

object Scope {
  implicit val formatScope: OFormat[Scope] = Json.format[Scope]
}

case class Definition(scopes: Seq[Scope], api: APIDefinition)

object Definition {
  implicit val formatDefinition: OFormat[Definition] = Json.format[Definition]
} 
Example 35
Source File: FinancialData.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.models.des

import play.api.libs.json.{Json, OFormat}
import uk.gov.hmrc.vatapi.models.Amount

case class FinancialData(
                          idType: Option[String] = None,
                          idNumber: Option[String] = None,
                          regimeType: Option[String] = None,
                          processingDate: String,
                          financialTransactions: Seq[FinancialTransaction]
                        ) {

}

object FinancialData {
  implicit val financialTransactionFormat: OFormat[FinancialTransaction] = FinancialTransaction.format
  implicit val format: OFormat[FinancialData] = Json.format[FinancialData]
}

case class FinancialTransaction(
                                 chargeType: String,
                                 mainType: Option[String] = None,
                                 periodKey: Option[String] = None,
                                 periodKeyDescription: Option[String] = None,
                                 taxPeriodFrom: Option[String] = None,
                                 taxPeriodTo: Option[String] = None,
                                 businessPartner: Option[String] = None,
                                 contractAccountCategory: Option[String] = None,
                                 contractAccount: Option[String] = None,
                                 contractObjectType: Option[String] = None,
                                 contractObject: Option[String] = None,
                                 sapDocumentNumber: Option[String] = None,
                                 sapDocumentNumberItem: Option[String] = None,
                                 chargeReference: Option[String] = None,
                                 mainTransaction: Option[String] = None,
                                 subTransaction: Option[String] = None,
                                 originalAmount: Option[Amount] = Some(BigDecimal(0)),
                                 outstandingAmount: Option[Amount] = None,
                                 clearedAmount: Option[Amount] = None,
                                 accruedInterest: Option[Amount] = None,
                                 items: Option[Seq[FinancialItem]] = None
                               )

object FinancialTransaction {
  implicit val itemFormat: OFormat[FinancialItem] = FinancialItem.format
  implicit val format: OFormat[FinancialTransaction] = Json.format[FinancialTransaction]
}

case class FinancialItem(
                          subItem: Option[String] = None,
                          dueDate: Option[String] = None,
                          amount: Option[Amount] = None,
                          clearingDate: Option[String] = None,
                          clearingReason: Option[String] = None,
                          outgoingPaymentMethod: Option[String] = None,
                          paymentLock: Option[String] = None,
                          clearingLock: Option[String] = None,
                          interestLock: Option[String] = None,
                          dunningLock: Option[String] = None,
                          returnFlag: Option[Boolean] = None,
                          paymentReference: Option[String] = None,
                          paymentAmount: Option[Amount] = None,
                          paymentMethod: Option[String] = None,
                          paymentLot: Option[String] = None,
                          paymentLotItem: Option[String] = None,
                          clearingSAPDocument: Option[String] = None,
                          statisticalDocument: Option[String] = None
                        )

object FinancialItem {
  implicit val format: OFormat[FinancialItem] = Json.format[FinancialItem]
}