spray.json.RootJsonFormat Scala Examples

The following examples show how to use spray.json.RootJsonFormat. 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: ValidationDirectivesSpec.scala    From squbs   with Apache License 2.0 5 votes vote down vote up
package org.squbs.pattern.validation

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import akka.http.scaladsl.server.directives.MethodDirectives
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.{FunSpecLike, Matchers}
import org.squbs.pattern.validation.ValidationDirectives.{validate => _}
import spray.json.{DefaultJsonProtocol, RootJsonFormat}

object MyJsonProtocol extends SprayJsonSupport with DefaultJsonProtocol {
  implicit val PersonFormat: RootJsonFormat[Person] = jsonFormat4(Person)
}

class ValidationDirectivesSpec extends FunSpecLike with Matchers with ScalatestRouteTest{

  val ValidationPassed = "Validation Passed"

  import MyJsonProtocol._
  import org.squbs.pattern.validation.SampleValidators._

  val route: Route =
    (path("person") & MethodDirectives.post) {
      entity(as[Person]) { person =>
        import ValidationDirectives._
        validate(person) {
          complete(ValidationPassed)
        }
      }
    }

  describe("ValidationDirectives") {

    it(s"should return [$ValidationPassed] string with 200 for a valid content without middle name") {
      Post("/person", Person("John", "Smith", age = 25)) ~> route ~> check {
        status shouldEqual StatusCodes.OK
        responseAs[String] shouldEqual ValidationPassed
      }
    }

    it(s"should return [$ValidationPassed] string with 200 for a valid content with middle name") {
      Post("/person", Person("John", "Smith", Some("Mike"), age = 25)) ~> route ~> check {
        status shouldEqual StatusCodes.OK
        responseAs[String] shouldEqual ValidationPassed
      }
    }

    it("should reject with Last Name") {
      Post("/person", Person("John", "", age = 25)) ~> route ~> check {
        rejections shouldEqual List(ValidationRejection("Last Name"))
      }
    }

    it("should reject with middleName") {
      Post("/person", Person("John", "Smith", Some(""), age = 25)) ~> route ~> check {
        rejections shouldEqual List(ValidationRejection("middleName"))
      }
    }

    it("should reject with Last Name, middleName, age") {
      Post("/person", Person("John", "", Some(""), age = -1)) ~> route ~> check {
        rejections shouldEqual List(ValidationRejection("Last Name, middleName, age"))
      }
    }
  }

} 
Example 2
Source File: ElasticSearch.scala    From cloudformation-template-generator   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.monsanto.arch.cloudformation.model.resource

import com.monsanto.arch.cloudformation.model.{ConditionRef, Token}
import spray.json.{DefaultJsonProtocol, JsonFormat, RootJsonFormat}

case class EBSOptions(
  EBSEnabled:     Option[Token[Boolean]],
  Iops:           Option[Token[Int]],
  VolumeType:     Option[Token[VolumeType]],
  VolumeSize:     Option[Token[Int]]
)
object EBSOptions extends DefaultJsonProtocol {
  implicit val format = jsonFormat4(EBSOptions.apply)
}

case class ElasticsearchClusterConfig(
  DedicatedMasterCount:     Option[Token[Int]],
  DedicatedMasterEnabled:   Option[Token[Boolean]],
  DedicatedMasterType:      Option[Token[String]],
  InstanceCount:            Option[Token[Int]],
  InstanceType:             Option[Token[String]],
  ZoneAwarenessEnabled:     Option[Token[Boolean]]
)
object ElasticsearchClusterConfig extends DefaultJsonProtocol {
  implicit val format = jsonFormat6(ElasticsearchClusterConfig.apply)
}

case class SnapshotOptions(AutomatedSnapshotStartHour: Option[Token[Int]])
object SnapshotOptions extends DefaultJsonProtocol {
  implicit val format = jsonFormat1(SnapshotOptions.apply)
}

case class VPCOptions(
                       SecurityGroupIds : Seq[Token[`AWS::EC2::SecurityGroup`]] = Seq.empty[Token[`AWS::EC2::SecurityGroup`]],
                       SubnetIds: Seq[Token[String]]
                     )

object VPCOptions extends DefaultJsonProtocol {
  implicit val format : RootJsonFormat[VPCOptions] = jsonFormat2(VPCOptions.apply)
}

case class `AWS::Elasticsearch::Domain` (
                                          name:                       String,
                                          DomainName:                 Token[String],
                                          AccessPolicies:             Option[PolicyDocument]                = None,
                                          AdvancedOptions:            Option[Token[Map[String, String]]]    = None,
                                          EBSOptions:                 Option[EBSOptions]                    = None,
                                          ElasticsearchClusterConfig: Option[ElasticsearchClusterConfig]    = None,
                                          ElasticsearchVersion:       Option[Token[String]]                 = None,
                                          SnapshotOptions:            Option[SnapshotOptions]               = None,
                                          Tags:                       Option[Seq[AmazonTag]]                = None,
                                          VPCOptions:                 Option[VPCOptions]                    = None,
                                          override val Condition:     Option[ConditionRef]                  = None,
                                          override val DependsOn:     Option[Seq[String]]                   = None
                                        ) extends Resource[`AWS::Elasticsearch::Domain`]{
  def when(newCondition: Option[ConditionRef] = Condition) : `AWS::Elasticsearch::Domain` = copy(Condition = newCondition)
}
object `AWS::Elasticsearch::Domain` extends DefaultJsonProtocol {
  implicit val format: JsonFormat[`AWS::Elasticsearch::Domain`] = jsonFormat12(`AWS::Elasticsearch::Domain`.apply)
} 
Example 3
Source File: KMS.scala    From cloudformation-template-generator   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.monsanto.arch.cloudformation.model.resource

import com.monsanto.arch.cloudformation.model._
import spray.json.DefaultJsonProtocol._
import spray.json.RootJsonFormat

case class `AWS::KMS::Alias`(
                            name : String,
                            AliasName : Token[String],
                            TargetKeyId : Token[String],
                            override val DependsOn: Option[Seq[String]] = None,
                            override val Condition : Option[ConditionRef] = None
                            ) extends Resource[`AWS::KMS::Alias`] {
  override def when(newCondition: Option[ConditionRef]): `AWS::KMS::Alias` = copy(Condition = newCondition)
}
object `AWS::KMS::Alias` {

  implicit val format : RootJsonFormat[`AWS::KMS::Alias`] = jsonFormat5(`AWS::KMS::Alias`.apply)
}

case class `AWS::KMS::Key`(
                          name : String,
                          Description : Option[Token[String]] = None,
                          Enabled : Option[Token[Boolean]] = None,
                          EnableKeyRotation : Option[Token[Boolean]] = None,
                          KeyPolicy : PolicyDocument,
                          override val DependsOn: Option[Seq[String]] = None,
                          override val Condition: Option[ConditionRef] = None
                          ) extends Resource[`AWS::KMS::Key`] with HasArn {
  override def when(newCondition: Option[ConditionRef]): `AWS::KMS::Key` = copy(Condition = newCondition)

  override def arn: Token[String] = `Fn::GetAtt`(Seq(name, "Arn"))
}

object `AWS::KMS::Key` {

  implicit val format : RootJsonFormat[`AWS::KMS::Key`] = jsonFormat7(`AWS::KMS::Key`.apply)
} 
Example 4
Source File: CodeCommit.scala    From cloudformation-template-generator   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.monsanto.arch.cloudformation.model.resource

import com.monsanto.arch.cloudformation.model.Token.TokenSeq
import com.monsanto.arch.cloudformation.model._
import spray.json.DefaultJsonProtocol._
import spray.json.{ DeserializationException, JsString, JsValue, JsonFormat, RootJsonFormat }

sealed trait CodeCommitEvent extends Product with Serializable

object CodeCommitEvent {
  private type T = CodeCommitEvent
  case object all extends T
  case object updateReference extends T
  case object createReference extends T
  case object deleteReference extends T
  implicit lazy val format: JsonFormat[T] = new JsonFormat[T] {
    def write(t: T): JsValue = JsString(t.toString)
    def read(json: JsValue): T = json match {
      case JsString("all") => all
      case JsString("updateReference") => updateReference
      case JsString("createReference") => createReference
      case JsString("deleteReference") => deleteReference
      case _ => throw DeserializationException(s"Can't parse as CodeCommitEvent: $json")
    }
  }
}

case class CodeCommitTrigger(
                              Branches: Option[TokenSeq[String]] = None,
                              CustomData: Option[String] = None,
                              DestinationArn: Option[Token[String]] = None,
                              Events: Option[Seq[CodeCommitEvent]] = None,
                              Name: String
                            )
object CodeCommitTrigger {
  private type T = CodeCommitTrigger
  implicit lazy val format: JsonFormat[T] = jsonFormat5(apply)
}

case class `AWS::CodeCommit::Repository`(
                                          name: String,
                                          RepositoryName: String,
                                          RepositoryDescription: Option[String] = None,
                                          Triggers: Option[Seq[CodeCommitTrigger]] = None,
                                          override val Condition: Option[ConditionRef] = None,
                                          override val DependsOn: Option[Seq[String]] = None
                                        ) extends Resource[`AWS::CodeCommit::Repository`] {
  override def when(newCondition: Option[ConditionRef]): `AWS::CodeCommit::Repository` = copy(Condition = newCondition)
}

object `AWS::CodeCommit::Repository` {
  implicit lazy val format : RootJsonFormat[`AWS::CodeCommit::Repository`] = jsonFormat6(apply)
} 
Example 5
Source File: EmailAuthProviderManager.scala    From graphcool-framework   with Apache License 2.0 5 votes vote down vote up
package cool.graph.authProviders

import com.github.t3hnar.bcrypt._
import cool.graph.ArgumentSchema
import cool.graph.client.database.DeferredResolverProvider
import cool.graph.client.mutations.Create
import cool.graph.client.schema.SchemaModelObjectTypesBuilder
import cool.graph.client.schema.simple.SimpleArgumentSchema
import cool.graph.client.{ClientInjector, UserContext}
import cool.graph.shared.errors.UserAPIErrors
import cool.graph.shared.errors.UserAPIErrors.{CannotSignUpUserWithCredentialsExist, UniqueConstraintViolation}
import cool.graph.shared.models.IntegrationName._
import cool.graph.shared.models.{AuthProviderMetaInformation, IntegrationName, TypeIdentifier}
import cool.graph.util.coolSangria.Sangria
import cool.graph.util.crypto.Crypto
import sangria.schema.Context
import spray.json.{DefaultJsonProtocol, RootJsonFormat}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

case class JwtEmailAuthData(email: String)

object EmailAuthJsonProtocol extends DefaultJsonProtocol {
  implicit val authDataFormat: RootJsonFormat[JwtEmailAuthData] = jsonFormat1(JwtEmailAuthData)
}

class EmailAuthProviderManager()(implicit injector: ClientInjector) extends AuthProviderManager[Unit]() {
  val clientAuth = injector.clientAuth

  val emailField    = ManagedField(defaultName = "email", typeIdentifier = TypeIdentifier.String, isUnique = true, isReadonly = true)
  val passwordField = ManagedField(defaultName = "password", typeIdentifier = TypeIdentifier.String, isReadonly = true)

  override val managedFields: List[ManagedField] = List(emailField, passwordField)
  override val signupFields: List[ManagedField]  = List(emailField, passwordField)
  override val signinFields: List[ManagedField]  = List(emailField, passwordField)

  override val integrationName: IntegrationName = IntegrationName.AuthProviderEmail

  override val name = "email"

  override def getmetaInformation: Option[AuthProviderMetaInformation] = None

  import EmailAuthJsonProtocol._

  def resolveSignin(ctx: Context[UserContext, Unit], args: Map[String, Any]): Future[Option[AuthData]] = {
    val email    = args("email").asInstanceOf[String]
    val password = args("password").asInstanceOf[String]
    ctx.ctx.dataResolver.resolveByUnique(ctx.ctx.project.getModelByName_!("User"), "email", email) flatMap {
      case Some(user) if password.isBcrypted(user.get[String]("password")) =>
        clientAuth
          .loginUser(ctx.ctx.project, user, Some(JwtEmailAuthData(email = email)))
          .map(token => Some(AuthData(token = token, user = user)))
      case _ => throw UserAPIErrors.CannotSignInCredentialsInvalid()
    }
  }

  override def resolveSignup[T, A](ctx: Context[UserContext, Unit],
                                   customArgs: Map[String, Any],
                                   providerArgs: Map[String, Any],
                                   modelObjectTypesBuilder: SchemaModelObjectTypesBuilder[T],
                                   argumentSchema: ArgumentSchema,
                                   deferredResolverProvider: DeferredResolverProvider[_, UserContext]): Future[Option[AuthData]] = {

    val userModel = ctx.ctx.dataResolver.project.getModelByName_!("User")

    val createArgs = Sangria.rawArgs(
      raw = customArgs ++ providerArgs + (passwordField.defaultName -> Crypto
        .hash(providerArgs(passwordField.defaultName).asInstanceOf[String])))

    val a = new Create(
      model = userModel,
      project = ctx.ctx.project,
      args = createArgs,
      dataResolver = ctx.ctx.dataResolver,
      argumentSchema = SimpleArgumentSchema,
      allowSettingManagedFields = true
    ).run(ctx.ctx.authenticatedRequest, ctx.ctx)
      .recover {
        case e: UniqueConstraintViolation => throw CannotSignUpUserWithCredentialsExist()
      }
      .map(user =>
        clientAuth
          .loginUser(ctx.ctx.project, user, Some(JwtEmailAuthData(email = user.get[String]("email"))))
          .map(token => Some(AuthData(token = token, user = user))))

    a.flatMap(identity)
  }
} 
Example 6
Source File: AzureSearchSchemas.scala    From mmlspark   with MIT License 5 votes vote down vote up
// Copyright (C) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in project root for information.

package com.microsoft.ml.spark.cognitive

import com.microsoft.ml.spark.core.schema.SparkBindings
import spray.json.DefaultJsonProtocol._
import spray.json.{JsonFormat, RootJsonFormat}

object ASResponses extends SparkBindings[ASResponses]

case class ASResponses(value: Seq[ASResponse])

case class ASResponse(key: String, status: Boolean, errorMessage: Option[String], statusCode: Int)

case class IndexInfo(
                    name: Option[String],
                    fields: Seq[IndexField],
                    suggesters: Option[Seq[String]],
                    scoringProfiles: Option[Seq[String]],
                    analyzers: Option[Seq[String]],
                    charFilters: Option[Seq[String]],
                    tokenizers: Option[Seq[String]],
                    tokenFilters: Option[Seq[String]],
                    defaultScoringProfile: Option[Seq[String]],
                    corsOptions: Option[Seq[String]]
                    )

case class IndexField(
                     name: String,
                     `type`: String,
                     searchable: Option[Boolean],
                     filterable: Option[Boolean],
                     sortable: Option[Boolean],
                     facetable: Option[Boolean],
                     retrievable: Option[Boolean],
                     key: Option[Boolean],
                     analyzer: Option[String],
                     searchAnalyzer: Option[String],
                     indexAnalyzer: Option[String],
                     synonymMap: Option[String],
                     fields: Option[Seq[IndexField]]
                     )

case class IndexStats(documentCount: Int, storageSize: Int)

case class IndexList(`@odata.context`: String, value: Seq[IndexName])
case class IndexName(name: String)

object AzureSearchProtocol {
  implicit val IfEnc: JsonFormat[IndexField] = lazyFormat(jsonFormat(
    IndexField,"name","type","searchable","filterable","sortable",
    "facetable","retrievable", "key","analyzer","searchAnalyzer", "indexAnalyzer", "synonymMaps", "fields"))
  implicit val IiEnc: RootJsonFormat[IndexInfo] = jsonFormat10(IndexInfo.apply)
  implicit val IsEnc: RootJsonFormat[IndexStats] = jsonFormat2(IndexStats.apply)
  implicit val InEnc: RootJsonFormat[IndexName] = jsonFormat1(IndexName.apply)
  implicit val IlEnc: RootJsonFormat[IndexList] = jsonFormat2(IndexList.apply)
} 
Example 7
Source File: SpeechSchemas.scala    From mmlspark   with MIT License 5 votes vote down vote up
// Copyright (C) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in project root for information.

package com.microsoft.ml.spark.cognitive

import com.microsoft.ml.spark.core.schema.SparkBindings
import spray.json.{DefaultJsonProtocol, RootJsonFormat}

case class DetailedSpeechResponse(Confidence: Double,
                                  Lexical: String,
                                  ITN: String,
                                  MaskedITN: String,
                                  Display: String)

case class SpeechResponse(RecognitionStatus: String,
                          Offset: Int,
                          Duration: Int,
                          Id: Option[String],
                          DisplayText: Option[String],
                          NBest: Option[Seq[DetailedSpeechResponse]]
                          )

object SpeechResponse extends SparkBindings[SpeechResponse]

object SpeechFormat extends DefaultJsonProtocol {
  implicit val DetailedSpeechResponseFormat: RootJsonFormat[DetailedSpeechResponse] =
    jsonFormat5(DetailedSpeechResponse.apply)
  implicit val SpeechResponseFormat: RootJsonFormat[SpeechResponse] = jsonFormat6(SpeechResponse.apply)
} 
Example 8
Source File: AnomalyDetectorSchemas.scala    From mmlspark   with MIT License 5 votes vote down vote up
// Copyright (C) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in project root for information.

package com.microsoft.ml.spark.cognitive

import com.microsoft.ml.spark.core.schema.SparkBindings
import spray.json.DefaultJsonProtocol._
import spray.json.RootJsonFormat

object TimeSeriesPoint extends SparkBindings[TimeSeriesPoint]

case class TimeSeriesPoint(timestamp: String, value: Double)

case class ADRequest(series: Seq[TimeSeriesPoint],
                     granularity: String,
                     maxAnomalyRatio: Option[Double],
                     sensitivity: Option[Int],
                     customInterval: Option[Int],
                     period: Option[Int])

object ADRequest extends SparkBindings[ADRequest]

case class ADLastResponse(isAnomaly: Boolean,
                          isPositiveAnomaly: Boolean,
                          isNegativeAnomaly: Boolean,
                          period: Int,
                          expectedValue: Double,
                          upperMargin: Double,
                          lowerMargin: Double,
                          suggestedWindow: Int)

object ADLastResponse extends SparkBindings[ADLastResponse]

case class ADSingleResponse(isAnomaly: Boolean,
                            isPositiveAnomaly: Boolean,
                            isNegativeAnomaly: Boolean,
                            period: Int,
                            expectedValue: Double,
                            upperMargin: Double,
                            lowerMargin: Double)

object ADSingleResponse extends SparkBindings[ADSingleResponse]

case class ADEntireResponse(isAnomaly: Seq[Boolean],
                            isPositiveAnomaly: Seq[Boolean],
                            isNegativeAnomaly: Seq[Boolean],
                            period: Int,
                            expectedValues: Seq[Double],
                            upperMargins: Seq[Double],
                            lowerMargins: Seq[Double]) {

  def explode: Seq[ADSingleResponse] = {
    isAnomaly.indices.map {i =>
      ADSingleResponse(
        isAnomaly(i), isPositiveAnomaly(i), isNegativeAnomaly(i),
        period, expectedValues(i), upperMargins(i), lowerMargins(i)
      )
    }
  }
}

object ADEntireResponse extends SparkBindings[ADEntireResponse]

object AnomalyDetectorProtocol {
  implicit val TspEnc: RootJsonFormat[TimeSeriesPoint] = jsonFormat2(TimeSeriesPoint.apply)
  implicit val AdreqEnc: RootJsonFormat[ADRequest] = jsonFormat6(ADRequest.apply)
} 
Example 9
Source File: LesserThanGenerator.scala    From TSimulus   with Apache License 2.0 5 votes vote down vote up
package be.cetic.tsimulus.generators.binary

import be.cetic.tsimulus.config.{GeneratorFormat, Model}
import be.cetic.tsimulus.generators.Generator
import be.cetic.tsimulus.timeseries.TimeSeries
import be.cetic.tsimulus.timeseries.binary.LesserThanTimeSeries
import spray.json.{DefaultJsonProtocol, JsObject, JsString, JsValue, RootJsonFormat, _}



class LesserThanGenerator( name: Option[String],
                            val a: Either[String, Generator[Any]],
                            val b: Either[String, Generator[Any]],
                            val strict: Option[Boolean]) extends Generator[Any](name, "lesser-than")
{
   override def timeseries(generators: (String) => Generator[Any]) =
   {
      val first = Model.generator(generators)(a).timeseries(generators) match {
         case t: TimeSeries[Double] => t
      }

      val second = Model.generator(generators)(b).timeseries(generators) match {
         case t: TimeSeries[Double] => t
      }

      new LesserThanTimeSeries(first, second, strict match {
         case None => true
         case Some(x) => x
      })
   }

   override def toString = "LesserThan(" + name + ", " + a + ", " + b + ", " + strict + ")"

   override def equals(o: Any) = o match {
      case that: LesserThanGenerator => that.name == this.name &&
         that.a == this.a &&
         that.b == this.b &&
         that.strict == this.strict
      case _ => false
   }

   override def toJson: JsValue = {
      val _a = a match
      {
         case Left(s) => s.toJson
         case Right(g) => g.toJson
      }

      val _b = b match
      {
         case Left(s) => s.toJson
         case Right(g) => g.toJson
      }

      var t = Map(
         "a" -> _a,
         "b" -> _b,
         "type" -> `type`.toJson
      )

      if(name.isDefined) t = t.updated("name", name.toJson)
      if(strict.isDefined) t = t.updated("strict", strict.toJson)

      new JsObject(t)
   }
}

object LesserThanGenerator extends DefaultJsonProtocol
{
   def apply(value: JsValue): LesserThanGenerator =
   {
      val fields = value.asJsObject.fields

      val name = fields.get("name").map(_.convertTo[String])
      val strict = fields.get("strict").map(_.convertTo[Boolean])

      val a = fields("a") match {
         case JsString(s) => Left(s)
         case g => Right(GeneratorFormat.read(g))
      }

      val b = fields("b") match {
         case JsString(s) => Left(s)
         case g => Right(GeneratorFormat.read(g))
      }

      new LesserThanGenerator(name, a, b, strict)
   }
} 
Example 10
Source File: TimeToJson.scala    From TSimulus   with Apache License 2.0 5 votes vote down vote up
package be.cetic.tsimulus.generators

import com.github.nscala_time.time.Imports._
import org.joda.time.format.DateTimeFormatterBuilder
import org.joda.time.{Duration, LocalDateTime, LocalTime}
import spray.json.{JsString, JsValue, RootJsonFormat, _}


trait TimeToJson extends DefaultJsonProtocol
{
   val dtf = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSS")
   val ttf = DateTimeFormat.forPattern("HH:mm:ss.SSS")

   val datetimeFormatter = {
      val parsers = Array(
         DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSS").getParser,
         DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss").getParser
      )

      new DateTimeFormatterBuilder().append(null, parsers).toFormatter()
   }

   val timeFormatter = {
      val parsers = Array(
         DateTimeFormat.forPattern("HH:mm:ss.SSS").getParser,
         DateTimeFormat.forPattern("HH:mm:ss").getParser
      )

      new DateTimeFormatterBuilder().append(null, parsers).toFormatter()
   }

   implicit object LocalDateTimeJsonFormat extends RootJsonFormat[LocalDateTime] {
      def write(d: LocalDateTime) = JsString(dtf.print(d))
      def read(value: JsValue) = value match {
         case JsString(s) => datetimeFormatter.parseLocalDateTime(s)
         case unrecognized => serializationError(s"Serialization problem $unrecognized")
      }
   }

   implicit object LocalTimeJsonFormat extends RootJsonFormat[LocalTime] {
      def write(t: LocalTime) = JsString(ttf.print(t))
      def read(value: JsValue) = value match {
         case JsString(s) => timeFormatter.parseLocalTime(s)
         case unknown => deserializationError(s"unknown LocalTime object: $unknown")
      }
   }

   implicit object DurationFormat extends RootJsonFormat[Duration] {
      def write(d: Duration) = d.getMillis.toJson
      def read(value: JsValue) = new Duration(value.toString.toLong)
   }

   def either2json(element: Either[String,Generator[Any]]) = element match {
      case Left(s) => s.toJson
      case Right(g) => g.toJson
   }
} 
Example 11
Source File: WorkflowManagerClient.scala    From seahorse   with Apache License 2.0 5 votes vote down vote up
package ai.deepsense.workflowmanager.client

import java.net.URL
import java.util.UUID

import scala.concurrent.Future
import scala.language.postfixOps

import akka.actor.ActorSystem
import akka.util.Timeout
import spray.client.pipelining._
import spray.http._
import spray.json.RootJsonFormat

import ai.deepsense.commons.json.envelope.{Envelope, EnvelopeJsonFormat}
import ai.deepsense.commons.rest.client.RestClient
import ai.deepsense.commons.utils.Logging
import ai.deepsense.models.json.workflow.WorkflowInfoJsonProtocol
import ai.deepsense.models.workflows.{Workflow, WorkflowInfo, WorkflowWithVariables}
import ai.deepsense.workflowmanager.model.{WorkflowDescription, WorkflowDescriptionJsonProtocol}

class WorkflowManagerClient(
    override val apiUrl: URL,
    mandatoryUserId: UUID,
    mandatoryUserName: String,
    override val credentials: Option[HttpCredentials])(
    implicit override val as: ActorSystem,
    override val timeout: Timeout)
  extends RestClient
  with WorkflowInfoJsonProtocol
  with WorkflowDescriptionJsonProtocol
  with Logging {

  override def userId: Option[UUID] = Some(mandatoryUserId)
  override def userName: Option[String] = Some(mandatoryUserName)

  implicit private val envelopeWorkflowIdJsonFormat =
    new EnvelopeJsonFormat[Workflow.Id]("workflowId")


  def fetchWorkflows(): Future[List[WorkflowInfo]] = {
    fetchResponse[List[WorkflowInfo]](Get(endpointPath("")))
  }

  def fetchWorkflow(id: Workflow.Id)(implicit workflowJsonFormat: RootJsonFormat[Workflow]): Future[Workflow] = {
    fetchResponse[Workflow](Get(endpointPath(s"$id")))
  }

  def fetchWorkflowInfo(id: Workflow.Id): Future[WorkflowInfo] = {
    fetchResponse[WorkflowInfo](Get(endpointPath(s"$id/info")))
  }

  def cloneWorkflow(workflowId: Workflow.Id,
      workflowDescription: WorkflowDescription):
  Future[Workflow.Id] = {
    fetchResponse[Envelope[Workflow.Id]](Post(
      endpointPath(s"$workflowId/clone"),
      workflowDescription
    )).map(_.content)
  }

  def deleteWorkflow(workflowId: Workflow.Id): Future[Unit] = {
    fetchHttpResponse(Delete(endpointPath(s"$workflowId"))).map(_ => ())
  }

  def uploadWorkflow(workflow: Workflow)
    (implicit rootJsonWorkflow: RootJsonFormat[Workflow]): Future[Workflow.Id] = {
    uploadWorkflow(rootJsonWorkflow.write(workflow).toString())
  }

  def downloadWorkflow(workflowId: Workflow.Id)
    (implicit jsonFormat: RootJsonFormat[WorkflowWithVariables]): Future[Option[WorkflowWithVariables]] = {
    fetchResponse[Option[WorkflowWithVariables]](Get(endpointPath(s"$workflowId/download?export-datasources=true")))
  }

  def uploadWorkflow(workflow: String): Future[Workflow.Id] = {
    fetchResponse[Envelope[Workflow.Id]](Post(
      endpointPath(s"upload"),
      MultipartFormData(Seq(BodyPart(HttpEntity(workflow), "workflowFile"))))).map(_.content)
  }
} 
Example 12
Source File: ClusterHttpManagementProtocol.scala    From akka-management   with Apache License 2.0 5 votes vote down vote up
package akka.management.cluster

import scala.collection.immutable

import akka.annotation.InternalApi
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import spray.json.DefaultJsonProtocol
import spray.json.RootJsonFormat

final case class ClusterUnreachableMember(node: String, observedBy: immutable.Seq[String])
final case class ClusterMember(node: String, nodeUid: String, status: String, roles: Set[String])
object ClusterMember {
  implicit val clusterMemberOrdering: Ordering[ClusterMember] = Ordering.by(_.node)
}
final case class ClusterMembers(
    selfNode: String,
    members: Set[ClusterMember],
    unreachable: immutable.Seq[ClusterUnreachableMember],
    leader: Option[String],
    oldest: Option[String],
    oldestPerRole: Map[String, String])
final case class ClusterHttpManagementMessage(message: String)
final case class ShardRegionInfo(shardId: String, numEntities: Int)
final case class ShardDetails(regions: immutable.Seq[ShardRegionInfo])


@InternalApi private[akka] object ClusterHttpManagementOperation {
  def fromString(value: String): Option[ClusterHttpManagementOperation] =
    Vector(Down, Leave, Join).find(_.toString.equalsIgnoreCase(value))
}

trait ClusterHttpManagementJsonProtocol extends SprayJsonSupport with DefaultJsonProtocol {
  implicit val clusterUnreachableMemberFormat: RootJsonFormat[ClusterUnreachableMember] =
    jsonFormat2(ClusterUnreachableMember)
  implicit val clusterMemberFormat: RootJsonFormat[ClusterMember] = jsonFormat4(ClusterMember.apply)
  implicit val clusterMembersFormat: RootJsonFormat[ClusterMembers] = jsonFormat6(ClusterMembers)
  implicit val clusterMemberMessageFormat: RootJsonFormat[ClusterHttpManagementMessage] =
    jsonFormat1(ClusterHttpManagementMessage)
  implicit val shardRegionInfoFormat: RootJsonFormat[ShardRegionInfo] = jsonFormat2(ShardRegionInfo)
  implicit val shardDetailsFormat: RootJsonFormat[ShardDetails] = jsonFormat1(ShardDetails)
} 
Example 13
Source File: EchoListService.scala    From swagger-akka-http-sample   with Apache License 2.0 5 votes vote down vote up
package com.example.akka.echolist

import akka.http.scaladsl.server.{Directives, Route}
import com.example.akka.DefaultJsonFormats
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.media.{Content, Schema}
import io.swagger.v3.oas.annotations.parameters.RequestBody
import io.swagger.v3.oas.annotations.responses.ApiResponse
import javax.ws.rs.core.MediaType
import javax.ws.rs.{Consumes, POST, Path, Produces}
import pl.iterators.kebs.json.KebsSpray
import spray.json.RootJsonFormat

@Path("/echolist")
object EchoListService extends Directives with DefaultJsonFormats with KebsSpray {

  case class EchoList(listName: String, values: Seq[String])

  implicit val echoListFormat: RootJsonFormat[EchoList] = jsonFormatN[EchoList]

  val route: Route = echo

  @POST
  @Consumes(Array(MediaType.APPLICATION_JSON))
  @Produces(Array(MediaType.APPLICATION_JSON))
  @Operation(summary = "Echo List", description = "Echo List",
    requestBody = new RequestBody(content = Array(new Content(schema = new Schema(implementation = classOf[EchoList])))),
    responses = Array(
      new ApiResponse(responseCode = "200", description = "Echo List",
        content = Array(new Content(schema = new Schema(implementation = classOf[EchoList])))),
      new ApiResponse(responseCode = "400", description = "Bad Request"))
  )
  def echo: Route =
    path("echolist") {
      post {
        entity(as[EchoList]) { request =>
          complete(request)
        }
      }
    }

} 
Example 14
Source File: AddService.scala    From swagger-akka-http-sample   with Apache License 2.0 5 votes vote down vote up
package com.example.akka.add

import javax.ws.rs.{Consumes, POST, Path, Produces}
import akka.actor.ActorRef
import akka.http.scaladsl.server.{Directives, Route}
import akka.pattern.ask
import akka.util.Timeout
import com.example.akka.DefaultJsonFormats
import com.example.akka.add.AddActor._
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.media.{Content, Schema}
import io.swagger.v3.oas.annotations.parameters.RequestBody
import io.swagger.v3.oas.annotations.responses.ApiResponse
import javax.ws.rs.core.MediaType
import spray.json.RootJsonFormat

import scala.concurrent.ExecutionContext
import scala.concurrent.duration.DurationInt

@Path("/add")
class AddService(addActor: ActorRef)(implicit executionContext: ExecutionContext)
  extends Directives with DefaultJsonFormats {

  implicit val timeout: Timeout = Timeout(2.seconds)

  implicit val requestFormat: RootJsonFormat[AddRequest] = jsonFormat1(AddRequest)
  implicit val responseFormat: RootJsonFormat[AddResponse] = jsonFormat1(AddResponse)

  val route: Route = add

  @POST
  @Consumes(Array(MediaType.APPLICATION_JSON))
  @Produces(Array(MediaType.APPLICATION_JSON))
  @Operation(summary = "Add integers", description = "Add integers",
    requestBody = new RequestBody(content = Array(new Content(schema = new Schema(implementation = classOf[AddRequest])))),
    responses = Array(
      new ApiResponse(responseCode = "200", description = "Add response",
        content = Array(new Content(schema = new Schema(implementation = classOf[AddResponse])))),
      new ApiResponse(responseCode = "500", description = "Internal server error"))
  )
  def add: Route =
    path("add") {
      post {
        entity(as[AddRequest]) { request =>
          complete { (addActor ? request).mapTo[AddResponse] }
        }
      }
    }

} 
Example 15
Source File: EchoEnumeratumService.scala    From swagger-akka-http-sample   with Apache License 2.0 5 votes vote down vote up
package com.example.akka.echoenumeratum

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.server.{Directives, Route}
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.media.{Content, Schema}
import io.swagger.v3.oas.annotations.parameters.RequestBody
import io.swagger.v3.oas.annotations.responses.ApiResponse
import javax.ws.rs.core.MediaType
import javax.ws.rs.{Consumes, POST, Path, Produces}
import pl.iterators.kebs.json.{KebsEnumFormats, KebsSpray}
import spray.json.{DefaultJsonProtocol, RootJsonFormat}

@Path("/echoenumeratum")
object EchoEnumeratumService extends Directives with SprayJsonSupport with DefaultJsonProtocol
  with KebsSpray with KebsEnumFormats {

  case class EchoEnumeratum(enumValue: SizeEnum)

  implicit val echoEnumeratumFormat: RootJsonFormat[EchoEnumeratum] = jsonFormatN[EchoEnumeratum]

  val route: Route = echo

  @POST
  @Consumes(Array(MediaType.APPLICATION_JSON))
  @Produces(Array(MediaType.APPLICATION_JSON))
  @Operation(summary = "Echo Enumeratum", description = "Echo Enumeratum",
    requestBody = new RequestBody(content = Array(new Content(schema = new Schema(implementation = classOf[EchoEnumeratum])))),
    responses = Array(
      new ApiResponse(responseCode = "200", description = "Echo Enumeratum",
        content = Array(new Content(schema = new Schema(implementation = classOf[EchoEnumeratum])))),
      new ApiResponse(responseCode = "400", description = "Bad Request"))
  )
  def echo: Route =
    path("echoenumeratum") {
      post {
        entity(as[EchoEnumeratum]) { request =>
          complete(request)
        }
      }
    }

} 
Example 16
Source File: AddOptionService.scala    From swagger-akka-http-sample   with Apache License 2.0 5 votes vote down vote up
package com.example.akka.addoption

import javax.ws.rs.{Consumes, POST, Path, Produces}
import akka.actor.ActorRef
import akka.http.scaladsl.server.{Directives, Route}
import akka.pattern.ask
import akka.util.Timeout
import com.example.akka.DefaultJsonFormats
import com.example.akka.addoption.AddOptionActor._
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.media.{Content, Schema}
import io.swagger.v3.oas.annotations.parameters.RequestBody
import io.swagger.v3.oas.annotations.responses.ApiResponse
import javax.ws.rs.core.MediaType
import spray.json.RootJsonFormat

import scala.concurrent.ExecutionContext
import scala.concurrent.duration.DurationInt

@Path("/addOption")
class AddOptionService(addActor: ActorRef)(implicit executionContext: ExecutionContext)
  extends Directives with DefaultJsonFormats {

  implicit val timeout: Timeout = Timeout(2.seconds)

  implicit val requestFormat: RootJsonFormat[AddOptionRequest] = jsonFormat2(AddOptionRequest)
  implicit val responseFormat: RootJsonFormat[AddOptionResponse] = jsonFormat1(AddOptionResponse)

  val route: Route = addOption

  @POST
  @Consumes(Array(MediaType.APPLICATION_JSON))
  @Produces(Array(MediaType.APPLICATION_JSON))
  @Operation(summary = "Add integers", description = "Add integers",
    requestBody = new RequestBody(content = Array(new Content(schema = new Schema(implementation = classOf[AddOptionRequest])))),
    responses = Array(
      new ApiResponse(responseCode = "200", description = "Add response",
        content = Array(new Content(schema = new Schema(implementation = classOf[AddOptionResponse])))),
      new ApiResponse(responseCode = "500", description = "Internal server error"))
  )
  def addOption: Route =
    path("addOption") {
      post {
        entity(as[AddOptionRequest]) { request =>
          complete { (addActor ? request).mapTo[AddOptionResponse] }
        }
      }
    }

} 
Example 17
Source File: HelloService.scala    From swagger-akka-http-sample   with Apache License 2.0 5 votes vote down vote up
package com.example.akka.hello

import javax.ws.rs.{GET, Path, Produces}
import akka.actor.ActorRef
import akka.http.scaladsl.server.{Directives, Route}
import akka.pattern.ask
import akka.util.Timeout
import com.example.akka.DefaultJsonFormats
import com.example.akka.hello.HelloActor._
import io.swagger.v3.oas.annotations.enums.ParameterIn
import io.swagger.v3.oas.annotations.media.{Content, Schema}
import io.swagger.v3.oas.annotations.responses.ApiResponse
import io.swagger.v3.oas.annotations.{Operation, Parameter}
import javax.ws.rs.core.MediaType
import spray.json.RootJsonFormat

import scala.concurrent.ExecutionContext
import scala.concurrent.duration.DurationInt

@Path("/hello")
class HelloService(hello: ActorRef)(implicit executionContext: ExecutionContext)
  extends Directives with DefaultJsonFormats {

  implicit val timeout: Timeout = Timeout(2.seconds)
  implicit val greetingFormat: RootJsonFormat[Greeting] = jsonFormat1(Greeting)

  val route: Route =
    getHello ~
    getHelloSegment

  @GET
  @Produces(Array(MediaType.APPLICATION_JSON))
  @Operation(summary = "Return Hello greeting (anonymous)", description = "Return Hello greeting for anonymous request",
    responses = Array(
      new ApiResponse(responseCode = "200", description = "Hello response",
        content = Array(new Content(schema = new Schema(implementation = classOf[Greeting])))),
      new ApiResponse(responseCode = "500", description = "Internal server error"))
  )
  def getHello: Route =
    path("hello") {
      get {
        complete { (hello ? AnonymousHello).mapTo[Greeting] }
      }
    }

  @GET
  @Produces(Array(MediaType.APPLICATION_JSON))
  @Operation(summary = "Return Hello greeting", description = "Return Hello greeting for named user",
    parameters = Array(new Parameter(name = "name", in = ParameterIn.PATH, description = "user name")),
    responses = Array(
      new ApiResponse(responseCode = "200", description = "Hello response",
        content = Array(new Content(schema = new Schema(implementation = classOf[Greeting])))),
      new ApiResponse(responseCode = "500", description = "Internal server error"))
  )
  def getHelloSegment: Route =
    path("hello" / Segment) { name =>
      get {
        complete { (hello ? Hello(name)).mapTo[Greeting] }
      }
    }
} 
Example 18
Source File: EchoEnumService.scala    From swagger-akka-http-sample   with Apache License 2.0 5 votes vote down vote up
package com.example.akka.echoenum

import akka.http.scaladsl.server.{Directives, Route}
import com.example.akka.DefaultJsonFormats
import com.fasterxml.jackson.core.`type`.TypeReference
import com.fasterxml.jackson.module.scala.JsonScalaEnumeration
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.media.{Content, Schema}
import io.swagger.v3.oas.annotations.parameters.RequestBody
import io.swagger.v3.oas.annotations.responses.ApiResponse
import javax.ws.rs.core.MediaType
import javax.ws.rs.{Consumes, POST, Path, Produces}
import spray.json.{DeserializationException, JsString, JsValue, RootJsonFormat}

@Path("/echoenum")
object EchoEnumService extends Directives with DefaultJsonFormats {

  //case class EchoEnum(@Schema(required = true, `type` = "string", allowableValues = Array("TALL", "GRANDE", "VENTI"))
  //                    enumValue: SizeEnum.Value)
  class SizeEnumTypeClass extends TypeReference[SizeEnum.type]
  case class EchoEnum(@JsonScalaEnumeration(classOf[SizeEnumTypeClass]) enumValue: SizeEnum.Value)

  implicit val enumFormat: RootJsonFormat[SizeEnum.Value] =
    new RootJsonFormat[SizeEnum.Value] {
      def write(obj: SizeEnum.Value): JsValue = JsString(obj.toString)
      def read(json: JsValue): SizeEnum.Value = {
        json match {
          case JsString(txt) => SizeEnum.withName(txt)
          case somethingElse => throw DeserializationException(s"Expected a value from enum $SizeEnum instead of $somethingElse")
        }
      }
    }
  implicit val echoEnumFormat: RootJsonFormat[EchoEnum] = jsonFormat1(EchoEnum)

  val route: Route = echo

  @POST
  @Consumes(Array(MediaType.APPLICATION_JSON))
  @Produces(Array(MediaType.APPLICATION_JSON))
  @Operation(summary = "Echo Enum", description = "Echo Enum",
    requestBody = new RequestBody(content = Array(new Content(schema = new Schema(implementation = classOf[EchoEnum])))),
    responses = Array(
      new ApiResponse(responseCode = "200", description = "Echo Enum",
        content = Array(new Content(schema = new Schema(implementation = classOf[EchoEnum])))),
      new ApiResponse(responseCode = "400", description = "Bad Request"))
  )
  def echo: Route =
    path("echoenum") {
      post {
        entity(as[EchoEnum]) { request =>
          complete(request)
        }
      }
    }

} 
Example 19
Source File: VwDownsampledMultilabeledJson.scala    From aloha   with MIT License 5 votes vote down vote up
package com.eharmony.aloha.dataset.vw.multilabel.json

import com.eharmony.aloha.dataset.json.{Namespace, SparseSpec}
import com.eharmony.aloha.dataset.vw.json.VwJsonLike
import spray.json.{DefaultJsonProtocol, RootJsonFormat}

import scala.collection.{immutable => sci}


final case class VwDownsampledMultilabeledJson(
    imports: sci.Seq[String],
    features: sci.IndexedSeq[SparseSpec],
    namespaces: Option[Seq[Namespace]] = Some(Nil),
    normalizeFeatures: Option[Boolean] = Some(false),
    positiveLabels: String,
    numDownsampledNegLabels: Int
) extends VwJsonLike {

  require(
    0 < numDownsampledNegLabels,
    s"numDownsampledNegLabels must be positive, found $numDownsampledNegLabels"
  )
}

object VwDownsampledMultilabeledJson extends DefaultJsonProtocol {
  implicit val vwDownsampledMultilabeledJson: RootJsonFormat[VwDownsampledMultilabeledJson] =
    jsonFormat6(VwDownsampledMultilabeledJson.apply)
} 
Example 20
Source File: VwMultilabeledJson.scala    From aloha   with MIT License 5 votes vote down vote up
package com.eharmony.aloha.dataset.vw.multilabel.json

import com.eharmony.aloha.dataset.json.{Namespace, SparseSpec}
import com.eharmony.aloha.dataset.vw.json.VwJsonLike
import spray.json.{DefaultJsonProtocol, RootJsonFormat}

import scala.collection.{immutable => sci}


final case class VwMultilabeledJson(
    imports: sci.Seq[String],
    features: sci.IndexedSeq[SparseSpec],
    namespaces: Option[Seq[Namespace]] = Some(Nil),
    normalizeFeatures: Option[Boolean] = Some(false),
    positiveLabels: String)
  extends VwJsonLike

object VwMultilabeledJson extends DefaultJsonProtocol {
  implicit val labeledVwJsonFormat: RootJsonFormat[VwMultilabeledJson] =
    jsonFormat5(VwMultilabeledJson.apply)
} 
Example 21
Source File: MultilabelModelJson.scala    From aloha   with MIT License 5 votes vote down vote up
package com.eharmony.aloha.models.multilabel.json

import com.eharmony.aloha.id.ModelId
import com.eharmony.aloha.models.multilabel.PluginInfo
import com.eharmony.aloha.models.reg.json.{Spec, SpecJson}
import spray.json.DefaultJsonProtocol._
import spray.json.{JsObject, JsonFormat, RootJsonFormat}

import scala.collection.immutable.ListMap
import com.eharmony.aloha.factory.ScalaJsonFormats

trait MultilabelModelJson extends SpecJson with ScalaJsonFormats {

  protected[this] case class Plugin(`type`: String)

  
  protected[this] case class MultilabelData[K](
      modelType: String,
      modelId: ModelId,
      features: ListMap[String, Spec],
      numMissingThreshold: Option[Int],
      labelsInTrainingSet: Vector[K],
      labelsOfInterest: Option[String],
      underlying: JsObject
  ) extends PluginInfo[K]

  protected[this] final implicit def multilabelDataJsonFormat[K: JsonFormat]: RootJsonFormat[MultilabelData[K]] =
    jsonFormat7(MultilabelData[K])

  protected[this] final implicit val pluginJsonFormat: RootJsonFormat[Plugin] =
    jsonFormat1(Plugin)
} 
Example 22
Source File: Subject.scala    From openwhisk   with Apache License 2.0 5 votes vote down vote up
package org.apache.openwhisk.core.entity

import scala.util.Try

import spray.json.JsString
import spray.json.JsValue
import spray.json.RootJsonFormat
import spray.json.deserializationError

protected[core] class Subject private (private val subject: String) extends AnyVal {
  protected[core] def asString = subject // to make explicit that this is a string conversion
  protected[entity] def toJson = JsString(subject)
  override def toString = subject
}

protected[core] object Subject extends ArgNormalizer[Subject] {

  
  protected[core] def apply(): Subject = {
    Subject("anon-" + rand.alphanumeric.take(27).mkString)
  }

  override protected[core] implicit val serdes = new RootJsonFormat[Subject] {
    def write(s: Subject) = s.toJson

    def read(value: JsValue) =
      Try {
        val JsString(s) = value
        Subject(s)
      } getOrElse deserializationError("subject malformed")
  }

  private val rand = new scala.util.Random()
} 
Example 23
Source File: ValidationApi.scala    From ohara   with Apache License 2.0 5 votes vote down vote up
package oharastream.ohara.client.configurator
import oharastream.ohara.common.util.CommonUtils
import oharastream.ohara.kafka.connector.json.SettingInfo
import spray.json.{RootJsonFormat, _}

import scala.concurrent.{ExecutionContext, Future}
object ValidationApi {
  val VALIDATION_KIND: String = "validate"

  private[this] implicit val SETTING_INFO_FORMAT: RootJsonFormat[SettingInfo] = new RootJsonFormat[SettingInfo] {
    override def write(obj: SettingInfo): JsValue = obj.toJsonString.parseJson

    override def read(json: JsValue): SettingInfo = SettingInfo.ofJson(json.toString())
  }

  
    def connectorRequest: ConnectorRequest
  }

  def access: Access = new Access(VALIDATION_KIND) {
    override def connectorRequest: ConnectorRequest = new ConnectorRequest {
      override def verify()(implicit executionContext: ExecutionContext): Future[SettingInfo] =
        exec.put[oharastream.ohara.client.configurator.ConnectorApi.Creation, SettingInfo, ErrorApi.Error](
          s"$url/${ConnectorApi.KIND}",
          creation
        )
    }
  }
} 
Example 24
Source File: ContainerApi.scala    From ohara   with Apache License 2.0 5 votes vote down vote up
package oharastream.ohara.client.configurator
import oharastream.ohara.common.setting.ObjectKey
import spray.json.DefaultJsonProtocol._
import spray.json.RootJsonFormat

import scala.concurrent.{ExecutionContext, Future}

object ContainerApi {
  val KIND: String = "container"

  @deprecated(message = s"replaced by $KIND", since = "0.11.0")
  val CONTAINER_PREFIX_PATH: String = "containers"

  final case class PortMapping(hostIp: String, hostPort: Int, containerPort: Int)
  implicit val PORT_MAPPING_FORMAT: RootJsonFormat[PortMapping] = jsonFormat3(PortMapping)

  final case class ContainerInfo(
    nodeName: String,
    id: String,
    imageName: String,
    state: String,
    kind: String,
    name: String,
    size: Long,
    portMappings: Seq[PortMapping],
    environments: Map[String, String],
    hostname: String
  )

  implicit val CONTAINER_INFO_FORMAT: RootJsonFormat[ContainerInfo] = jsonFormat10(ContainerInfo)

  final case class ContainerGroup(clusterKey: ObjectKey, clusterType: String, containers: Seq[ContainerInfo])
  implicit val CONTAINER_GROUP_FORMAT: RootJsonFormat[ContainerGroup] = jsonFormat3(ContainerGroup)

  class Access private[configurator] extends BasicAccess(KIND) {
    def get(key: ObjectKey)(implicit executionContext: ExecutionContext): Future[Seq[ContainerGroup]] =
      exec.get[Seq[ContainerGroup], ErrorApi.Error](urlBuilder.key(key).build())
  }

  def access: Access = new Access
} 
Example 25
Source File: MetricsApi.scala    From ohara   with Apache License 2.0 5 votes vote down vote up
package oharastream.ohara.client.configurator

import spray.json.DefaultJsonProtocol._
import spray.json.RootJsonFormat

object MetricsApi {
  
  final case class Meter(
    name: String,
    value: Double,
    valueInPerSec: Option[Double],
    unit: String,
    document: String,
    queryTime: Long,
    startTime: Option[Long],
    lastModified: Option[Long]
  ) {
    def duration: Option[Long] = lastModified.flatMap(last => startTime.map(s => last - s))
  }

  implicit val METER_FORMAT: RootJsonFormat[Meter] = jsonFormat8(Meter)
  final case class Metrics(meters: Seq[Meter])
  object Metrics {
    val EMPTY: Metrics = Metrics(Seq.empty)
  }
  implicit val METRICS_FORMAT: RootJsonFormat[Metrics] = jsonFormat1(Metrics.apply)
} 
Example 26
Source File: JsonSupport.scala    From akka-http-slick-sample   with MIT License 5 votes vote down vote up
package net.softler.data.model

import java.sql.Timestamp
import java.time.Instant
import java.util.UUID

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import spray.json.{DefaultJsonProtocol, JsNumber, JsString, JsValue, JsonFormat, RootJsonFormat}

trait BaseJsonProtocol extends DefaultJsonProtocol {
  implicit val timestampFormat: JsonFormat[Timestamp] = new JsonFormat[Timestamp] {
    override def write(obj: Timestamp): JsValue = JsNumber(obj.getTime)

    override def read(json: JsValue): Timestamp = json match {
      case JsNumber(x) => Timestamp.from(Instant.ofEpochMilli(x.toLong))
      case _ =>
        throw new IllegalArgumentException(
          s"Can not parse json value [$json] to a timestamp object")
    }
  }

  implicit val uuidJsonFormat: JsonFormat[UUID] = new JsonFormat[UUID] {
    override def write(x: UUID): JsValue = JsString(x.toString)

    override def read(value: JsValue): UUID = value match {
      case JsString(x) => UUID.fromString(x)
      case x =>
        throw new IllegalArgumentException("Expected UUID as JsString, but got " + x.getClass)
    }
  }
}


trait JsonProtocol extends SprayJsonSupport with BaseJsonProtocol {
  implicit val userFormat: RootJsonFormat[User] = jsonFormat10(User)
} 
Example 27
Source File: AggregationFunctionsIT.scala    From clickhouse-scala-client   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package com.crobox.clickhouse.dsl

import java.util.UUID

import com.crobox.clickhouse.TestSchemaClickhouseQuerySpec
import com.crobox.clickhouse.ClickhouseClientSpec
import org.scalatest.time.{Millis, Seconds, Span}
import spray.json.DefaultJsonProtocol._
import spray.json.RootJsonFormat

class AggregationFunctionsIT
    extends ClickhouseClientSpec
    with TestSchemaClickhouseQuerySpec {

  private val entries = 200145
  override val table1Entries: Seq[Table1Entry] =
    Seq.fill(entries)(Table1Entry(UUID.randomUUID(), numbers = Seq(1, 2, 3)))
  override val table2Entries: Seq[Table2Entry] =
    Seq.fill(entries)(Table2Entry(UUID.randomUUID(), randomString, randomInt, randomString, None))

  override implicit def patienceConfig =
    PatienceConfig(timeout = scaled(Span(10, Seconds)), interval = scaled(Span(20, Millis)))

  "Combinators" should "apply for aggregations" in {
    case class Result(columnResult: String) {
      def result = columnResult.toInt
    }
    implicit val resultFormat: RootJsonFormat[Result] = jsonFormat[String, Result](Result.apply, "result")
    val resultSimple = chExecutor
      .execute[Result](select(uniq(shieldId) as "result") from OneTestTable)
      .futureValue
    val resultExact = chExecutor
      .execute[Result](select(uniqExact(shieldId) as "result") from OneTestTable)
      .futureValue
    resultSimple.rows.head.result shouldBe (entries +- entries / 100)
    resultSimple.rows.head.result should not be entries
    resultExact.rows.head.result shouldBe entries
  }

  it should "run quantiles" in {
    case class Result(result: Seq[Int])
    implicit val resultFormat: RootJsonFormat[Result] = jsonFormat[Seq[Int], Result](Result.apply, "result")
    val result = chExecutor
      .execute[Result](
        select(quantiles(col2, 0.1F, 0.2F, 0.3F, 0.4F, 0.5F, 0.99F) as ref[Seq[Int]]("result")) from TwoTestTable
      )
      .futureValue
    result.rows.head.result should have length 6
  }

  it should "run for each" in {
    case class Result(result: Seq[String])
    implicit val resultFormat: RootJsonFormat[Result] = jsonFormat[Seq[String], Result](Result.apply, "result")
    val result = chExecutor
      .execute[Result](
        select(forEach[Int, TableColumn[Seq[Int]], Double](numbers) { column =>
          sum(column)
        } as "result") from OneTestTable
      )
      .futureValue
    val queryResult = result.rows.head.result.map(_.toInt)
    queryResult should have length 3
    queryResult should contain theSameElementsAs Seq(entries, entries * 2, entries * 3)
  }

} 
Example 28
Source File: StringFunctionsIT.scala    From clickhouse-scala-client   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package com.crobox.clickhouse.dsl

import java.util.UUID

import com.crobox.clickhouse.{ClickhouseClientSpec, TestSchemaClickhouseQuerySpec}
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.{Millis, Seconds, Span}
import spray.json.DefaultJsonProtocol.{jsonFormat, _}
import spray.json.RootJsonFormat

class StringFunctionsIT
    extends ClickhouseClientSpec
    with TestSchemaClickhouseQuerySpec
    with ScalaFutures {

  private val columnString = "oneem,twoem,threeem"
  override val table2Entries: Seq[Table2Entry] =
    Seq(Table2Entry(UUID.randomUUID(), columnString, randomInt, randomString, None))

  override implicit def patienceConfig =
    PatienceConfig(timeout = scaled(Span(10, Seconds)), interval = scaled(Span(20, Millis)))

  case class Result(result: String)
  implicit val resultFormat: RootJsonFormat[Result] = jsonFormat[String, Result](Result.apply, "result")

  it should "split by character" in {
    val resultRows =
      chExecutor.execute[Result](select(arrayJoin(splitByChar(",", col1)) as "result") from TwoTestTable).futureValue.rows
    resultRows.length shouldBe 3
    resultRows.map(_.result) should contain theSameElementsAs Seq("oneem", "twoem", "threeem")
  }

  it should "split by string" in {
    val resultRows =
      chExecutor.execute[Result](select(arrayJoin(splitByString("em,", col1)) as "result") from TwoTestTable).futureValue.rows
    resultRows.length shouldBe 3
    resultRows.map(_.result) should contain theSameElementsAs Seq("one", "two", "threeem")
  }

  it should "concatenate string back" in {
    val resultRows =
      chExecutor
        .execute[Result](select(arrayStringConcat(splitByChar(",", col1), ",") as "result") from TwoTestTable)
        .futureValue
        .rows
    resultRows.length shouldBe 1
    resultRows.map(_.result).head shouldBe columnString

  }

} 
Example 29
Source File: JsonSupport.scala    From darwin   with Apache License 2.0 5 votes vote down vote up
package it.agilelab.darwin.server.rest

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import org.apache.avro.Schema
import spray.json.{DefaultJsonProtocol, JsObject, JsString, JsValue, JsonParser, PrettyPrinter, RootJsonFormat}

trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
  implicit val printer: PrettyPrinter.type = PrettyPrinter

  implicit val schemaFormat: RootJsonFormat[Schema] = new RootJsonFormat[Schema] {

    override def write(obj: Schema): JsValue = JsonParser(obj.toString(true))

    override def read(json: JsValue): Schema = new Schema.Parser().parse(json.prettyPrint)
  }

  implicit val schemaWithIdFormat: RootJsonFormat[(Long, Schema)] = new RootJsonFormat[(Long, Schema)] {

    override def write(obj: (Long, Schema)): JsValue = JsObject(Map(
      "id" -> JsString(obj._1.toString),
      "schema" -> schemaFormat.write(obj._2)
    ))

    override def read(json: JsValue): (Long, Schema) = json match {
      case JsObject(fields) =>
        val id = fields.get("id") match {
          case Some(JsString(number)) => number
          case _ => throw new Exception("Id field should be a long")
        }

        val schema = fields.get("schema") match {
          case Some(x@JsObject(_)) => x
          case _ => throw new Exception("schema should be an object")
        }

        (id.toLong, schemaFormat.read(schema))
      case _ => throw new Exception("should be an object")
    }
  }
} 
Example 30
Source File: HttpRouter.scala    From JustinDB   with Apache License 2.0 5 votes vote down vote up
package justin.httpapi

import java.util.UUID

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import justin.db.Data
import justin.db.client.{ActorRefStorageNodeClient, GetValueResponse, WriteValueResponse}
import justin.db.replica.{R, W}
import justin.db.storage.Base64
import justin.db.versioning.NodeIdVectorClockBase64
import justin.httpapi.JustinDirectives._
import justin.httpapi.Unmarshallers.UUIDUnmarshaller
import spray.json.DefaultJsonProtocol._
import spray.json.RootJsonFormat

import scala.concurrent.ExecutionContext
import scala.util.{Failure, Success}

object HttpRouter {
  import Unmarshallers.UuidFormat

  case class Result(value: String)
  implicit val valueFormat: RootJsonFormat[Result] = jsonFormat1(Result)

  case class ConflictedData(id: String, value: String, vclock: Base64)
  implicit val conflictedDataFormat: RootJsonFormat[ConflictedData] = jsonFormat3(ConflictedData)

  case class PutValue(id: UUID, value: String, w: Int)
  implicit val putValueFormat: RootJsonFormat[PutValue] = jsonFormat3(PutValue)
}

class HttpRouter(client: ActorRefStorageNodeClient)(implicit ec: ExecutionContext) {
  import HttpRouter._

  private[this] def transformConflictedData(data: Data) = {
    val vcBase64 = new NodeIdVectorClockBase64().encode(data.vclock).get
    ConflictedData(data.id.toString, data.value, vcBase64)
  }

  def routes: Route = withVectorClockHeader { vClockHeader =>
    {
      (get & path("get") & pathEndOrSingleSlash & parameters(('id.as(UUIDUnmarshaller), 'r.as[Int]))) { (uuid, r) =>
        onComplete(client.get(uuid, R(r))) {
          case Success(GetValueResponse.Found(data))     => respondWithHeader(VectorClockHeader(data.vclock)) { complete(OK -> Result(data.value)) }
          case Success(GetValueResponse.Conflicts(data)) => complete(MultipleChoices -> data.map(transformConflictedData))
          case Success(GetValueResponse.NotFound(id))    => complete(NotFound -> Result(s"Couldn't found value with id ${id.toString}"))
          case Success(GetValueResponse.Failure(err))    => complete(BadRequest -> Result(err))
          case Failure(ex)                               => complete(InternalServerError -> Result(ex.getMessage))
        }
      }
    } ~
    (post & path("put") & pathEndOrSingleSlash & entity(as[PutValue])) { putValue =>
      complete {
        client.write(Data(putValue.id, putValue.value, vClockHeader.vectorClock), W(putValue.w)).map[ToResponseMarshallable] {
          case WriteValueResponse.Success(id)  => NoContent
          case WriteValueResponse.Conflict     => MultipleChoices -> Result("Multiple Choices")
          case WriteValueResponse.Failure(err) => BadRequest      -> Result(err)
        }
      }
    }
  }
} 
Example 31
Source File: Limits.scala    From openwhisk   with Apache License 2.0 5 votes vote down vote up
package org.apache.openwhisk.core.entity

import scala.util.Try
import spray.json.JsValue
import spray.json.RootJsonFormat
import spray.json.deserializationError
import spray.json.DefaultJsonProtocol


protected[core] case class TriggerLimits protected[core] () extends Limits {
  override protected[entity] def toJson: JsValue = TriggerLimits.serdes.write(this)
}

protected[core] object ActionLimits extends ArgNormalizer[ActionLimits] with DefaultJsonProtocol {

  override protected[core] implicit val serdes = new RootJsonFormat[ActionLimits] {
    val helper = jsonFormat4(ActionLimits.apply)

    def read(value: JsValue) = {
      val obj = Try {
        value.asJsObject.convertTo[Map[String, JsValue]]
      } getOrElse deserializationError("no valid json object passed")

      val time = TimeLimit.serdes.read(obj.get("timeout") getOrElse deserializationError("'timeout' is missing"))
      val memory = MemoryLimit.serdes.read(obj.get("memory") getOrElse deserializationError("'memory' is missing"))
      val logs = obj.get("logs") map { LogLimit.serdes.read(_) } getOrElse LogLimit()
      val concurrency = obj.get("concurrency") map { ConcurrencyLimit.serdes.read(_) } getOrElse ConcurrencyLimit()

      ActionLimits(time, memory, logs, concurrency)
    }

    def write(a: ActionLimits) = helper.write(a)
  }
}

protected[core] object TriggerLimits extends ArgNormalizer[TriggerLimits] with DefaultJsonProtocol {

  override protected[core] implicit val serdes = jsonFormat0(TriggerLimits.apply _)
} 
Example 32
Source File: ErrorApi.scala    From ohara   with Apache License 2.0 5 votes vote down vote up
package oharastream.ohara.client.configurator
import oharastream.ohara.client.HttpExecutor
import org.apache.commons.lang3.exception.ExceptionUtils
import spray.json.DefaultJsonProtocol._
import spray.json.RootJsonFormat

object ErrorApi {
  
  final case class Error(code: String, message: String, stack: String, apiUrl: Option[String])
      extends HttpExecutor.Error

  def of(e: Throwable): Error =
    Error(
      code = e.getClass.getName,
      message = if (e.getMessage == null) "unknown" else e.getMessage,
      stack = ExceptionUtils.getStackTrace(e),
      apiUrl = None
    )

  implicit val ERROR_FORMAT: RootJsonFormat[Error] = jsonFormat4(Error)
} 
Example 33
Source File: SemVer.scala    From openwhisk   with Apache License 2.0 5 votes vote down vote up
package org.apache.openwhisk.core.entity

import spray.json.deserializationError
import spray.json.JsString
import spray.json.JsValue
import spray.json.RootJsonFormat
import scala.util.Try


  protected[entity] def apply(str: String): SemVer = {
    try {
      val parts = if (str != null && str.nonEmpty) str.split('.') else Array[String]()
      val major = if (parts.size >= 1) parts(0).toInt else 0
      val minor = if (parts.size >= 2) parts(1).toInt else 0
      val patch = if (parts.size >= 3) parts(2).toInt else 0
      SemVer(major, minor, patch)
    } catch {
      case _: Throwable => throw new IllegalArgumentException(s"bad semantic version $str")
    }
  }

  implicit val serdes = new RootJsonFormat[SemVer] {
    def write(v: SemVer) = v.toJson

    def read(value: JsValue) =
      Try {
        val JsString(v) = value
        SemVer(v)
      } getOrElse deserializationError("semantic version malformed")
  }
} 
Example 34
Source File: TimeLimit.scala    From openwhisk   with Apache License 2.0 5 votes vote down vote up
package org.apache.openwhisk.core.entity

import pureconfig._
import pureconfig.generic.auto._

import scala.concurrent.duration._
import scala.util.Failure
import scala.util.Success
import scala.util.Try
import spray.json.JsNumber
import spray.json.JsValue
import spray.json.RootJsonFormat
import spray.json.deserializationError
import org.apache.openwhisk.core.ConfigKeys


  @throws[IllegalArgumentException]
  protected[core] def apply(duration: FiniteDuration): TimeLimit = {
    require(duration != null, s"duration undefined")
    require(
      duration >= MIN_DURATION,
      s"duration ${duration.toMillis} milliseconds below allowed threshold of ${MIN_DURATION.toMillis} milliseconds")
    require(
      duration <= MAX_DURATION,
      s"duration ${duration.toMillis} milliseconds exceeds allowed threshold of ${MAX_DURATION.toMillis} milliseconds")
    new TimeLimit(duration)
  }

  override protected[core] implicit val serdes = new RootJsonFormat[TimeLimit] {
    def write(t: TimeLimit) = JsNumber(t.millis)

    def read(value: JsValue) =
      Try {
        val JsNumber(ms) = value
        require(ms.isWhole, "time limit must be whole number")
        TimeLimit(Duration(ms.intValue, MILLISECONDS))
      } match {
        case Success(limit)                       => limit
        case Failure(e: IllegalArgumentException) => deserializationError(e.getMessage, e)
        case Failure(e: Throwable)                => deserializationError("time limit malformed", e)
      }
  }
} 
Example 35
Source File: Privilege.scala    From openwhisk   with Apache License 2.0 5 votes vote down vote up
package org.apache.openwhisk.core.entitlement

import scala.util.Try

import spray.json.DeserializationException
import spray.json.JsString
import spray.json.JsValue
import spray.json.RootJsonFormat

sealed trait Privilege


protected[core] object Privilege extends Enumeration {

  case object READ extends Privilege
  case object PUT extends Privilege
  case object DELETE extends Privilege
  case object ACTIVATE extends Privilege
  case object REJECT extends Privilege

  val CRUD: Set[Privilege] = Set(READ, PUT, DELETE)
  val ALL: Set[Privilege] = CRUD + ACTIVATE

  def fromName(name: String) = name match {
    case "READ"     => READ
    case "PUT"      => PUT
    case "DELETE"   => DELETE
    case "ACTIVATE" => ACTIVATE
    case "REJECT"   => REJECT
  }

  implicit val serdes = new RootJsonFormat[Privilege] {
    def write(p: Privilege) = JsString(p.toString)

    def read(json: JsValue) =
      Try {
        val JsString(str) = json
        Privilege.fromName(str.trim.toUpperCase)
      } getOrElse {
        throw new DeserializationException("Privilege must be a valid string")
      }
  }
} 
Example 36
Source File: ArtifactStoreProvider.scala    From openwhisk   with Apache License 2.0 5 votes vote down vote up
package org.apache.openwhisk.core.database

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory
import spray.json.RootJsonFormat
import org.apache.openwhisk.common.Logging
import org.apache.openwhisk.spi.{Spi, SpiLoader}
import org.apache.openwhisk.core.entity.DocumentReader

import scala.reflect.ClassTag


trait ArtifactStoreProvider extends Spi {
  def makeStore[D <: DocumentSerializer: ClassTag](useBatching: Boolean = false)(
    implicit jsonFormat: RootJsonFormat[D],
    docReader: DocumentReader,
    actorSystem: ActorSystem,
    logging: Logging,
    materializer: ActorMaterializer): ArtifactStore[D]

  protected def getAttachmentStore[D <: DocumentSerializer: ClassTag]()(
    implicit actorSystem: ActorSystem,
    logging: Logging,
    materializer: ActorMaterializer): Option[AttachmentStore] = {
    if (ConfigFactory.load().hasPath("whisk.spi.AttachmentStoreProvider")) {
      Some(SpiLoader.get[AttachmentStoreProvider].makeStore[D]())
    } else {
      None
    }
  }
} 
Example 37
Source File: CouchDbStoreProvider.scala    From openwhisk   with Apache License 2.0 5 votes vote down vote up
package org.apache.openwhisk.core.database

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import spray.json.RootJsonFormat
import org.apache.openwhisk.common.Logging
import org.apache.openwhisk.core.ConfigKeys
import org.apache.openwhisk.core.entity.DocumentReader
import org.apache.openwhisk.core.entity.size._
import pureconfig._
import pureconfig.generic.auto._

import scala.reflect.ClassTag

case class CouchDbConfig(provider: String,
                         protocol: String,
                         host: String,
                         port: Int,
                         username: String,
                         password: String,
                         databases: Map[String, String]) {
  assume(Set(protocol, host, username, password).forall(_.nonEmpty), "At least one expected property is missing")

  def databaseFor[D](implicit tag: ClassTag[D]): String = {
    val entityType = tag.runtimeClass.getSimpleName
    databases.get(entityType) match {
      case Some(name) => name
      case None       => throw new IllegalArgumentException(s"Database name mapping not found for $entityType")
    }
  }
}

object CouchDbStoreProvider extends ArtifactStoreProvider {

  def makeStore[D <: DocumentSerializer: ClassTag](useBatching: Boolean)(
    implicit jsonFormat: RootJsonFormat[D],
    docReader: DocumentReader,
    actorSystem: ActorSystem,
    logging: Logging,
    materializer: ActorMaterializer): ArtifactStore[D] = makeArtifactStore(useBatching, getAttachmentStore())

  def makeArtifactStore[D <: DocumentSerializer: ClassTag](useBatching: Boolean,
                                                           attachmentStore: Option[AttachmentStore])(
    implicit jsonFormat: RootJsonFormat[D],
    docReader: DocumentReader,
    actorSystem: ActorSystem,
    logging: Logging,
    materializer: ActorMaterializer): ArtifactStore[D] = {
    val dbConfig = loadConfigOrThrow[CouchDbConfig](ConfigKeys.couchdb)
    require(
      dbConfig.provider == "Cloudant" || dbConfig.provider == "CouchDB",
      s"Unsupported db.provider: ${dbConfig.provider}")

    val inliningConfig = loadConfigOrThrow[InliningConfig](ConfigKeys.db)

    new CouchDbRestStore[D](
      dbConfig.protocol,
      dbConfig.host,
      dbConfig.port,
      dbConfig.username,
      dbConfig.password,
      dbConfig.databaseFor[D],
      useBatching,
      inliningConfig,
      attachmentStore)
  }
} 
Example 38
Source File: JsonSupport.scala    From Learn-Scala-Programming   with MIT License 5 votes vote down vote up
package ch14

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import ch14.Commands._
import ch14.Events._
import spray.json.{DefaultJsonProtocol, RootJsonFormat}
import stamina.StaminaAkkaSerializer
import stamina.json._

trait JsonSupport extends SprayJsonSupport {

  import DefaultJsonProtocol._

  type RJF[T] = RootJsonFormat[T]

  implicit val createArticleJF: RJF[CreateArticle] = jsonFormat2(CreateArticle)
  implicit val deleteArticleJF: RJF[DeleteArticle] = jsonFormat1(DeleteArticle)
  implicit val purchaseJF: RJF[PurchaseArticles] = jsonFormat1(PurchaseArticles)
  implicit val restockJF: RJF[RestockArticles] = jsonFormat1(RestockArticles)

  implicit val createdJF: RJF[ArticleCreated] = jsonFormat2(ArticleCreated)
  implicit val deletedJF: RJF[ArticleDeleted] = jsonFormat1(ArticleDeleted)
  implicit val pJF: RJF[ArticlesPurchased] = jsonFormat1(ArticlesPurchased)
  implicit val reJF: RJF[ArticlesRestocked] = jsonFormat1(ArticlesRestocked)

  implicit val invJF: RJF[Inventory] = jsonFormat1(Inventory)

}

object PersistenceSupport extends JsonSupport {
  val v1createdP = persister[ArticleCreated]("article-created")
  val v1deletedP = persister[ArticleDeleted]("article-deleted")
  val v1purchasedP = persister[ArticlesPurchased]("articles-purchased")
  val v1restockedP = persister[ArticlesRestocked]("articles-restocked")
  val v1inventoryP = persister[Inventory]("inventory")
}

import PersistenceSupport._

class EventSerializer
    extends StaminaAkkaSerializer(v1createdP,
                                  v1deletedP,
                                  v1purchasedP,
                                  v1restockedP,
                                  v1inventoryP) 
Example 39
Source File: LightbendApi.scala    From scabot   with Apache License 2.0 5 votes vote down vote up
package scabot
package lightbend

import spray.json.{RootJsonFormat, DefaultJsonProtocol}

trait LightbendApi extends LightbendApiTypes with DefaultJsonProtocol with LightbendApiActions

trait LightbendApiTypes {
  case class CLARecord(user: String, signed: Boolean, version: Option[String], currentVersion: String)
}

trait LightbendJsonProtocol extends LightbendApiTypes with DefaultJsonProtocol {
  private type RJF[x] = RootJsonFormat[x]
  implicit lazy val _fmtCLARecord: RJF[CLARecord] = jsonFormat4(CLARecord)
}

trait LightbendApiActions extends LightbendJsonProtocol with core.HttpClient {
  class LightbendConnection {
    import spray.http.{GenericHttpCredentials, Uri}
    import spray.httpx.SprayJsonSupport._
    import spray.client.pipelining._

    private implicit def connection = setupConnection("www.lightbend.com")

    def checkCla(user: String) = pWithStatus[CLARecord](Get(Uri("/contribute/cla/scala/check" / user)))
  }
} 
Example 40
Source File: CoreTransactionTestCaseProtocol.scala    From bitcoin-s   with MIT License 5 votes vote down vote up
package org.bitcoins.core.protocol.transaction.testprotocol

import org.bitcoins.core.currency.{CurrencyUnit, Satoshis}
import org.bitcoins.core.number.{Int64, UInt32}
import org.bitcoins.core.protocol.script.ScriptPubKey
import org.bitcoins.core.protocol.transaction.{Transaction, TransactionOutPoint}
import org.bitcoins.core.script.constant.ScriptToken
import org.bitcoins.core.script.flag.{ScriptFlag, ScriptFlagFactory}
import org.bitcoins.core.serializers.script.ScriptParser
import org.bitcoins.core.util.{BitcoinSLogger, BytesUtil}
import org.bitcoins.crypto.DoubleSha256Digest
import spray.json.{DefaultJsonProtocol, JsArray, JsValue, RootJsonFormat}


  def parseOutPointsScriptPubKeysAmount(array: JsArray): Seq[
    (TransactionOutPoint, ScriptPubKey, Option[CurrencyUnit])] = {
    val result = array.elements.map {
      case array: JsArray =>
        val prevoutHashHex =
          BytesUtil.flipEndianness(array.elements.head.convertTo[String])
        val prevoutHash = DoubleSha256Digest(prevoutHashHex)

        val prevoutIndex = array.elements(1).convertTo[Long] match {
          case -1 => UInt32("ffffffff")
          case index
              if index >= UInt32.min.toLong && index <= UInt32.max.toLong =>
            UInt32(index)
        }

        val amount =
          if (array.elements.size == 4)
            Some(Satoshis(array.elements(3).convertTo[Long]))
          else None

        //val prevoutIndex = UInt32(array.elements(1).convertTo[Int])
        val outPoint = TransactionOutPoint(prevoutHash, prevoutIndex)
        val scriptTokens: Seq[ScriptToken] =
          ScriptParser.fromString(array.elements(2).convertTo[String])
        val scriptPubKey = ScriptPubKey.fromAsm(scriptTokens)
        (outPoint, scriptPubKey, amount)
      case _: JsValue =>
        throw new RuntimeException(
          "All tx outpoint/scriptpubkey info must be array elements")
    }
    result
  }
} 
Example 41
Source File: HttpBootstrapJsonProtocol.scala    From akka-management   with Apache License 2.0 5 votes vote down vote up
package akka.management.cluster.bootstrap.contactpoint

import akka.actor.{ Address, AddressFromURIString }
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import spray.json.{ DefaultJsonProtocol, JsString, JsValue, RootJsonFormat }

trait HttpBootstrapJsonProtocol extends SprayJsonSupport with DefaultJsonProtocol {
  import HttpBootstrapJsonProtocol._

  implicit object AddressFormat extends RootJsonFormat[Address] {
    override def read(json: JsValue): Address = json match {
      case JsString(s) => AddressFromURIString.parse(s)
      case invalid     => throw new IllegalArgumentException(s"Illegal address value! Was [$invalid]")
    }

    override def write(obj: Address): JsValue = JsString(obj.toString)
  }
  implicit val SeedNodeFormat: RootJsonFormat[SeedNode] = jsonFormat1(SeedNode)
  implicit val ClusterMemberFormat: RootJsonFormat[ClusterMember] = jsonFormat4(ClusterMember)
  implicit val ClusterMembersFormat: RootJsonFormat[SeedNodes] = jsonFormat2(SeedNodes)
}

object HttpBootstrapJsonProtocol extends DefaultJsonProtocol {

  final case class SeedNode(address: Address)

  // we use Address since we want to know which protocol is being used (tcp, artery, artery-tcp etc)
  final case class ClusterMember(node: Address, nodeUid: Long, status: String, roles: Set[String])
  implicit val clusterMemberOrdering: Ordering[ClusterMember] = Ordering.by(_.node)

  final case class SeedNodes(selfNode: Address, seedNodes: Set[ClusterMember])

}