spray.json.JsonFormat Scala Examples
The following examples show how to use spray.json.JsonFormat.
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: BasicTypes.scala From aloha with MIT License | 5 votes |
package com.eharmony.aloha.factory.ri2jf import com.eharmony.aloha.reflect.RefInfo import spray.json.JsonFormat import spray.json.DefaultJsonProtocol._ class BasicTypes extends RefInfoToJsonFormatConversions { def apply[A](implicit conv: RefInfoToJsonFormat, r: RefInfo[A], jf: JsonFormatCaster[A]): Option[JsonFormat[A]] = { if (r == RefInfo[Boolean]) jf[Boolean] else if (r == RefInfo[Byte]) jf[Byte] else if (r == RefInfo[Short]) jf[Short] else if (r == RefInfo[Int]) jf[Int] else if (r == RefInfo[Long]) jf[Long] else if (r == RefInfo[Float]) jf[Float] else if (r == RefInfo[Double]) jf[Double] else if (r == RefInfo[BigDecimal]) jf[BigDecimal] else if (r == RefInfo[BigInt]) jf[BigInt] else if (r == RefInfo[Unit]) jf[Unit] else if (r == RefInfo[Char]) jf[Char] else if (r == RefInfo[Symbol]) jf[Symbol] else if (r == RefInfo[String]) jf[String] else None } }
Example 2
Source File: JsonEncodableParam.scala From mmlspark with MIT License | 5 votes |
// Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in project root for information. package org.apache.spark.ml.param import spray.json._ import spray.json.JsonFormat object ServiceParamJsonProtocol extends DefaultJsonProtocol { override implicit def eitherFormat[A: JsonFormat, B: JsonFormat]: JsonFormat[Either[A, B]] = new JsonFormat[Either[A, B]] { def write(either: Either[A, B]): JsValue = either match { case Left(a) => JsObject.apply(("left", a.toJson)) case Right(b) => JsObject.apply(("right", b.toJson)) } def read(value: JsValue): Either[A, B] = value.asJsObject().fields.head match { case ("left", jv) => Left(jv.convertTo[A]) case ("right", jv) => Right(jv.convertTo[B]) case _ => throw new IllegalArgumentException("Could not parse either type") } } implicit def serviceParamDataFormat[T: JsonFormat]: JsonFormat[ServiceParamData[T]] = jsonFormat2(ServiceParamData.apply) } class JsonEncodableParam[T](parent: Params, name: String, doc: String, isValid: T => Boolean) (@transient implicit val format: JsonFormat[T]) extends Param[T](parent, name, doc, isValid) { def this(parent: Params, name: String, doc: String)(implicit format: JsonFormat[T]) = this(parent, name, doc, ParamValidators.alwaysTrue) override def jsonEncode(value: T): String = { value.toJson.compactPrint } override def jsonDecode(json: String): T = { json.parseJson.convertTo[T] } } case class ServiceParamData[T]( data: Option[Either[T, String]], default: Option[T]) import ServiceParamJsonProtocol._ class ServiceParam[T](parent: Params, name: String, doc: String, isValid: ServiceParamData[T] => Boolean = ParamValidators.alwaysTrue, val isRequired: Boolean = false, val isURLParam: Boolean = false, val toValueString: T => String = {x: T => x.toString} ) (@transient implicit val dataFormat: JsonFormat[T]) extends JsonEncodableParam[ServiceParamData[T]](parent, name, doc, isValid) { type ValueType = T }
Example 3
Source File: AzureSearchSchemas.scala From mmlspark with MIT License | 5 votes |
// 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 4
Source File: SprayUtilities.scala From mmlspark with MIT License | 5 votes |
// Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in project root for information. package com.microsoft.ml.nbtest import spray.json.{JsArray, JsObject, JsValue, JsonFormat} import scala.language.{existentials, implicitConversions} abstract class SprayOp case class IndexOp(item: Int) extends SprayOp case class FieldOp(value: String) extends SprayOp class SprayUtility(val json: JsValue) { private def parseQuery(q: String): List[SprayOp] = { q.split("." (0)).flatMap { t => if (t.contains("]") & t.contains("]")) { t.split("][".toCharArray).filter(_.length > 0).toSeq match { case Seq(index) => Seq(IndexOp(index.toInt)) case Seq(field, index) => Seq(FieldOp(field), IndexOp(index.toInt)) } } else if (!t.contains("]") & !t.contains("]")) { Seq(FieldOp(t)).asInstanceOf[List[SprayOp]] } else { throw new IllegalArgumentException(s"Cannot parse query: $q") } }.toList } private def selectInternal[T](json: JsValue, ops: List[SprayOp])(implicit format: JsonFormat[T]): T = { ops match { case Nil => json.convertTo[T] case IndexOp(i) :: tail => selectInternal[T](json.asInstanceOf[JsArray].elements(i), tail) case FieldOp(f) :: tail => selectInternal[T](json.asInstanceOf[JsObject].fields(f), tail) case _ => throw new MatchError("This code should be unreachable") } } def select[T](query: String)(implicit format: JsonFormat[T]): T = { selectInternal[T](json, parseQuery(query)) } } object SprayImplicits { implicit def sprayUtilityConverter(s: JsValue): SprayUtility = new SprayUtility(s) implicit def sprayUtilityConversion(s: SprayUtility): JsValue = s.json }
Example 5
Source File: FileEntry.scala From seahorse with Apache License 2.0 | 5 votes |
package ai.deepsense.libraryservice import java.io.File import spray.json.{DefaultJsonProtocol, DeserializationException, JsString, JsValue, JsonFormat} import ai.deepsense.commons.json.EnumerationSerializer._ case class FileEntry private[libraryservice] ( name: String, kind: FileType.Value, children: Seq[FileEntry]) object FileEntry { def fromFile(file: java.io.File): FileEntry = { FileEntry(file.getName, FileType.File, Nil) } def fromDirectory(directory: java.io.File): FileEntry = { val sortedFiles = directory.listFiles.sortBy(f => (f.isFile, f.getName)) val children = sortedFiles.map(fileToFileEntry) FileEntry(directory.getName, FileType.Directory, children) } def fileToFileEntry(f: File): FileEntry = { if (f.isFile) { fromFile(f) } else { fromDirectory(f) } } } object FileType extends Enumeration { val File = Value("file") val Directory = Value("directory") implicit val fileTypeJsonFormat = jsonEnumFormat(FileType) } object FileEntryJsonProtocol extends DefaultJsonProtocol { implicit val fileEntryJsonFormat: JsonFormat[FileEntry] = lazyFormat(jsonFormat3(FileEntry.apply)) }
Example 6
Source File: RecentlyFilesHandler.scala From MoVE with Mozilla Public License 2.0 | 5 votes |
package de.thm.move.controllers import java.nio.file.{Files, Path, StandardOpenOption} import javafx.event.ActionEvent import javafx.scene.control.MenuItem import de.thm.move.Global import de.thm.move.implicits.FxHandlerImplicits._ import de.thm.move.util.JFxUtils import de.thm.recent._ import spray.json.JsonFormat class RecentlyFilesHandler(recent:Recent[Path], pathClicked: Path => Unit) { private def menuItem(path:Path): MenuItem = { val item = new MenuItem(path.toString) JFxUtils.addFontIcon(item, "\uf1c9") item.setOnAction { _:ActionEvent => incrementPriorityOf(path) println(recent.recentValuesByPriority) pathClicked(path) } item } def incrementPriorityOf(path:Path): Unit = recent.incrementPriority(path) def getMenuItems:Seq[MenuItem] = recent.recentElementsByPriority.map(menuItem) def writeTo(outputFile:Path)(implicit pathFormat:JsonFormat[Path]): Unit = { val jsonString = recent.toJson Files.write(outputFile, jsonString.getBytes(Global.encoding)) } }
Example 7
Source File: VwSparseMultilabelPredictorProducer.scala From aloha with MIT License | 5 votes |
package com.eharmony.aloha.models.vw.jni.multilabel import com.eharmony.aloha.io.sources.ModelSource import com.eharmony.aloha.models.multilabel._ import com.eharmony.aloha.models.vw.jni.multilabel.json.VwMultilabelModelPluginJsonReader import com.eharmony.aloha.reflect.RefInfo import spray.json.{JsonFormat, JsonReader} case class VwSparseMultilabelPredictorProducer[K]( modelSource: ModelSource, defaultNs: List[Int], namespaces: List[(String, List[Int])], labelNamespace: Char, numLabelsInTrainingSet: Int ) extends SparsePredictorProducer[K] { override def apply(): VwSparseMultilabelPredictor[K] = VwSparseMultilabelPredictor[K](modelSource, defaultNs, namespaces, numLabelsInTrainingSet) } object VwSparseMultilabelPredictorProducer extends MultilabelPluginProviderCompanion { def multilabelPlugin: MultilabelModelParserPlugin = Plugin object Plugin extends MultilabelModelParserPlugin { override def name: String = "vw" override def parser[K](info: PluginInfo[K]) (implicit ri: RefInfo[K], jf: JsonFormat[K]): JsonReader[SparsePredictorProducer[K]] = { VwMultilabelModelPluginJsonReader[K](info.features.keys.toVector, info.labelsInTrainingSet.size) } } }
Example 8
Source File: CollectionTypes.scala From aloha with MIT License | 5 votes |
package com.eharmony.aloha.factory.ri2jf import com.eharmony.aloha.reflect.{RefInfo, RefInfoOps} import spray.json.DefaultJsonProtocol.{immSeqFormat, mapFormat} import spray.json.JsonFormat class CollectionTypes extends RefInfoToJsonFormatConversions { def apply[A](implicit conv: RefInfoToJsonFormat, r: RefInfo[A], jf: JsonFormatCaster[A]): Option[JsonFormat[A]] = { val typeParams = RefInfoOps.typeParams[A] if (RefInfoOps.isSubType[A, collection.immutable.Map[Any, Any]]) typeParams match { case List(tKey, tVal) => for { k <- conv(tKey) v <- conv(tVal) f <- jf(mapFormat(k, v)) } yield f case _ => // TODO: perhaps change the API at some point to better report errors here. None } else if (RefInfoOps.isSubType[A, collection.immutable.Seq[Any]]) for { tEl <- typeParams.headOption el <- conv(tEl) f <- jf(immSeqFormat(el)) } yield f else None } }
Example 9
Source File: JavaTypes.scala From aloha with MIT License | 5 votes |
package com.eharmony.aloha.factory.ri2jf import java.{lang => jl} import com.eharmony.aloha.factory.JavaJsonFormats import com.eharmony.aloha.reflect.RefInfo import spray.json.JsonFormat class JavaTypes extends RefInfoToJsonFormatConversions { def apply[A](implicit conv: RefInfoToJsonFormat, r: RefInfo[A], jf: JsonFormatCaster[A]): Option[JsonFormat[A]] = { if (r == RefInfo[jl.Boolean]) jf(JavaJsonFormats.JavaBooleanJsonFormat) else if (r == RefInfo[jl.Byte]) jf(JavaJsonFormats.JavaByteJsonFormat) else if (r == RefInfo[jl.Short]) jf(JavaJsonFormats.JavaShortJsonFormat) else if (r == RefInfo[jl.Integer]) jf(JavaJsonFormats.JavaIntJsonFormat) else if (r == RefInfo[jl.Long]) jf(JavaJsonFormats.JavaLongJsonFormat) else if (r == RefInfo[jl.Float]) jf(JavaJsonFormats.JavaFloatJsonFormat) else if (r == RefInfo[jl.Double]) jf(JavaJsonFormats.JavaDoubleJsonFormat) else None } }
Example 10
Source File: JsonWritingMatcher.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model import com.monsanto.arch.cloudformation.model.resource.Resource import org.scalatest.Matchers import spray.json.{JsonWriter, JsObject, JsValue, JsonFormat} trait JsonWritingMatcher extends Matchers { implicit class JsonMatchResource(val value : Resource[_]) extends JsonMatcher[Resource[_]] { val format = Resource.seqFormat.format } implicit class JsonMatch[A](val value : A)(implicit val format: JsonWriter[A]) extends JsonMatcher[A] sealed trait JsonMatcher[A] { def value : A def format : JsonWriter[A] def shouldMatch(policy : String): Unit = { import spray.json._ val jsonPolicy = value.toJson(format) val parsedPolicy = policy.parseJson jsonEquals(Seq(), jsonPolicy, parsedPolicy) } } def jsonEquals(path : Seq[String], v1 : JsValue, v2 : JsValue): Unit = withClue("Path: [" + path.mkString(" -> ") + "]") { (v1, v2) match { case (JsObject(o1), JsObject(o2)) => o1.seq.keySet shouldEqual o2.seq.keySet for { key <- o1.seq.keySet } { jsonEquals(path ++ Seq(key), o1.seq(key), o2.seq(key)) } case (j1, j2) => { j1 shouldEqual j2 } } } }
Example 11
Source File: ModelParser.scala From aloha with MIT License | 5 votes |
package com.eharmony.aloha.factory import com.eharmony.aloha.audit.Auditor import com.eharmony.aloha.factory.jsext.JsValueExtensions import com.eharmony.aloha.id.{ModelId, ModelIdentity} import com.eharmony.aloha.models.{Model, Submodel} import com.eharmony.aloha.reflect.RefInfo import com.eharmony.aloha.semantics.Semantics import spray.json.{DefaultJsonProtocol, JsObject, JsValue, JsonFormat, JsonReader} import spray.json.DefaultJsonProtocol.{LongJsonFormat, StringJsonFormat} sealed trait ModelParser { val modelType: String private implicit val modelIdFormat = DefaultJsonProtocol.jsonFormat2(ModelId.apply) protected final def getModelId(json: JsValue): Option[ModelIdentity] = json(ModelParser.modelIdField).collect{case o: JsObject => o.convertTo[ModelId]} } private object ModelParser { val modelIdField = "modelId" } trait ModelParsingPlugin extends ModelParser { def modelJsonReader[U, N, A, B <: U](factory: SubmodelFactory[U, A], semantics: Semantics[A], auditor: Auditor[U, N, B]) (implicit r: RefInfo[N], jf: JsonFormat[N]): Option[JsonReader[Model[A, B]]] } trait SubmodelParsingPlugin extends ModelParser { def submodelJsonReader[U, N, A, B <: U](factory: SubmodelFactory[U, A], semantics: Semantics[A], auditor: Auditor[U, N, B]) (implicit r: RefInfo[N], jf: JsonFormat[N]): Option[JsonReader[Submodel[N, A, U]]] } trait ModelSubmodelParsingPlugin extends ModelParsingPlugin with SubmodelParsingPlugin { def commonJsonReader[U, N, A, B <: U](factory: SubmodelFactory[U, A], semantics: Semantics[A], auditor: Auditor[U, N, B]) (implicit r: RefInfo[N], jf: JsonFormat[N]): Option[JsonReader[_ <: Model[A, B] with Submodel[_, A, B]]] final override def modelJsonReader[U, N, A, B <: U](factory: SubmodelFactory[U, A], semantics: Semantics[A], auditor: Auditor[U, N, B]) (implicit r: RefInfo[N], jf: JsonFormat[N]): Option[JsonReader[Model[A, B]]] = { val reader = commonJsonReader(factory, semantics, auditor) reader.map(jr => jr.asInstanceOf[JsonReader[Model[A, B]]]) } final def submodelJsonReader[U, N, A, B <: U](factory: SubmodelFactory[U, A], semantics: Semantics[A], auditor: Auditor[U, N, B]) (implicit r: RefInfo[N], jf: JsonFormat[N]): Option[JsonReader[Submodel[N, A, U]]] = { val reader = commonJsonReader(factory, semantics, auditor) reader.map(jr => jr.asInstanceOf[JsonReader[Submodel[N, A, U]]]) } }
Example 12
Source File: BasicDecisionTree.scala From aloha with MIT License | 5 votes |
package com.eharmony.aloha.models.tree.decision import com.eharmony.aloha.audit.Auditor import com.eharmony.aloha.factory._ import com.eharmony.aloha.id.ModelIdentity import com.eharmony.aloha.models.tree.Tree import com.eharmony.aloha.models.{SubmodelBase, Subvalue} import com.eharmony.aloha.reflect.RefInfo import com.eharmony.aloha.semantics.Semantics import spray.json.{JsValue, JsonFormat, JsonReader} import scala.collection.immutable override def commonJsonReader[U, N, A, B <: U]( factory: SubmodelFactory[U, A], semantics: Semantics[A], auditor: Auditor[U, N, B]) (implicit r: RefInfo[N], jf: JsonFormat[N]): Option[JsonReader[BasicDecisionTree[U, N, A, B]]] = { Some(new JsonReader[BasicDecisionTree[U, N, A, B]] { override def read(json: JsValue): BasicDecisionTree[U, N, A, B] = { val dtAst = json.convertTo(decisionTreeAstJsonFormat[N]) val mId = getModelId(json) val t = Tree[NodeAst[N], immutable.IndexedSeq, Node[A, N]]( dtAst.nodes, root, id, childIds, treeBuilder[A, N](semantics, dtAst.missingDataOk)) val dt = BasicDecisionTree(mId.get, t, dtAst.returnBest, auditor) dt } }) } } def parser: ModelParser = Parser }
Example 13
Source File: ErrorModel.scala From aloha with MIT License | 5 votes |
package com.eharmony.aloha.models import com.eharmony.aloha.audit.Auditor import com.eharmony.aloha.factory._ import com.eharmony.aloha.factory.jsext.JsValueExtensions import com.eharmony.aloha.id.ModelIdentity import com.eharmony.aloha.reflect.RefInfo import com.eharmony.aloha.semantics.Semantics import spray.json.{DeserializationException, JsValue, JsonFormat, JsonReader} case class ErrorModel[U, +B <: U](modelId: ModelIdentity, errors: Seq[String], auditor: Auditor[U, Nothing, B]) extends SubmodelBase[U, Nothing, Any, B] { def subvalue(a: Any): Subvalue[B, Nothing] = failure(errors, Set.empty) override def toString(): String = "ErrorModel(" + modelId + "," + errors + ")" } object ErrorModel extends ParserProviderCompanion { object Parser extends ModelSubmodelParsingPlugin { val modelType = "Error" private[this] val errorField = "errors" override def commonJsonReader[U, N, A, B <: U]( factory: SubmodelFactory[U, A], semantics: Semantics[A], auditor: Auditor[U, N, B]) (implicit r: RefInfo[N], jf: JsonFormat[N]): Option[JsonReader[ErrorModel[U, B]]] = { Some(new JsonReader[ErrorModel[U, B]] { def read(json: JsValue): ErrorModel[U, B] = { val model = for { errors <- json.sa(errorField) orElse { Option(Seq("Error with unspecified reason.")) } mId <- getModelId(json) } yield ErrorModel(mId, errors, auditor) model getOrElse { throw new DeserializationException("") } } }) } } def parser: ModelParser = Parser }
Example 14
Source File: MultilabelModelJson.scala From aloha with MIT License | 5 votes |
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 15
Source File: ConstantModel.scala From aloha with MIT License | 5 votes |
package com.eharmony.aloha.models import com.eharmony.aloha.audit.Auditor import com.eharmony.aloha.factory._ import com.eharmony.aloha.factory.jsext.JsValueExtensions import com.eharmony.aloha.id.ModelIdentity import com.eharmony.aloha.reflect.RefInfo import com.eharmony.aloha.semantics.Semantics import spray.json.DefaultJsonProtocol.optionFormat import spray.json.{DeserializationException, JsValue, JsonFormat, JsonReader} case class ConstantModel[U, N, +B <: U]( constant: Option[N], modelId: ModelIdentity, auditor: Auditor[U, N, B] ) extends SubmodelBase[U, N, Any, B] { def subvalue(a: Any): Subvalue[B, N] = constant.map(n => success(n)) .getOrElse(failure(Seq("No constant supplied"), Set.empty)) } object ConstantModel extends ParserProviderCompanion { object Parser extends ModelSubmodelParsingPlugin { val modelType = "Constant" private val valueField = "value" override def commonJsonReader[U, N, A, B <: U]( factory: SubmodelFactory[U, A], semantics: Semantics[A], auditor: Auditor[U, N, B]) (implicit r: RefInfo[N], jf: JsonFormat[N]): Option[JsonReader[ConstantModel[U, N, B]]] = { Some(new JsonReader[ConstantModel[U, N, B]] { override def read(json: JsValue): ConstantModel[U, N, B] = { val model = for { jsV <- json(valueField) mId <- getModelId(json) v = jsV.convertTo[Option[N]] m = new ConstantModel(v, mId, auditor) } yield m model getOrElse { throw new DeserializationException("") } } }) } } def parser: ModelParser = Parser }
Example 16
Source File: CloserTesterModel.scala From aloha with MIT License | 5 votes |
package com.eharmony.aloha.models import java.util.concurrent.atomic.AtomicBoolean import com.eharmony.aloha.audit.Auditor import com.eharmony.aloha.ex.SchrodingerException import com.eharmony.aloha.factory.{ModelSubmodelParsingPlugin, ModelParser, ParserProviderCompanion, SubmodelFactory} import com.eharmony.aloha.id.ModelIdentity import com.eharmony.aloha.reflect.RefInfo import com.eharmony.aloha.semantics.Semantics import spray.json.{DeserializationException, JsValue, JsonFormat, JsonReader} import spray.json.DefaultJsonProtocol.{BooleanJsonFormat, optionFormat} import com.eharmony.aloha.factory.jsext.JsValueExtensions case class CloserTesterModel[U, N, +B <: U](modelId: ModelIdentity, auditor: Auditor[U, N, B], shouldThrowOnClose: Boolean = false) extends Model[Any, B] with Submodel[N, Any, B] { private[this] val closed = new AtomicBoolean(false) def isClosed: Boolean = closed.get() override def apply(a: Any): B = throw new UnsupportedOperationException override def subvalue(a: Any): Subvalue[B, N] = throw new UnsupportedOperationException override def close(): Unit = { closed.set(true) if (shouldThrowOnClose) throw new SchrodingerException } } object CloserTesterModel extends ParserProviderCompanion { object Parser extends ModelSubmodelParsingPlugin { val modelType = "CloserTester" private val shouldThrowField = "shouldThrow" override def commonJsonReader[U, N, A, B <: U]( factory: SubmodelFactory[U, A], semantics: Semantics[A], auditor: Auditor[U, N, B]) (implicit r: RefInfo[N], jf: JsonFormat[N]): Option[JsonReader[CloserTesterModel[U, N, B]]] = { Some(new JsonReader[CloserTesterModel[U, N, B]] { override def read(json: JsValue): CloserTesterModel[U, N, B] = { val model = getModelId(json) map { id => val shouldThrow = json(shouldThrowField).flatMap(st => st.convertTo[Option[Boolean]]) getOrElse false new CloserTesterModel(id, auditor, shouldThrow) } model getOrElse { throw new DeserializationException("Couldn't get model ID for CloserTester model.") } } }) } } def parser: ModelParser = Parser }
Example 17
Source File: ElasticSearchClient.scala From pipelines-examples with Apache License 2.0 | 5 votes |
package warez import akka.NotUsed import akka.kafka.ConsumerMessage.CommittableOffset import akka.stream.alpakka.elasticsearch.{ ReadResult, WriteMessage, WriteResult } import akka.stream.alpakka.elasticsearch.scaladsl.{ ElasticsearchFlow, ElasticsearchSource } import akka.stream.scaladsl.Source import org.apache.http.HttpHost import org.elasticsearch.client.RestClient import spray.json.{ JsObject, JsonFormat } import pipelines.akkastream.scaladsl.FlowWithOffsetContext implicit val esClient: RestClient = RestClient.builder(new HttpHost(hostname, port)).build() def indexFlow(): FlowWithOffsetContext[WriteMessage[T, NotUsed], WriteResult[T, CommittableOffset]] = ElasticsearchFlow.createWithContext[T, CommittableOffset](indexName, typeName) def querySource(searchCriteria: String): Source[ReadResult[JsObject], NotUsed] = ElasticsearchSource .create(indexName, typeName, query = s"""{ "bool": { "must": { "query_string": { "query": "$searchCriteria" } } } }""") }
Example 18
Source File: Request.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.lf.engine.trigger import com.daml.lf.data.Ref.{DottedName, Identifier, PackageId, QualifiedName} import spray.json.DefaultJsonProtocol._ import spray.json.{JsString, JsValue, JsonFormat, deserializationError} object Request { implicit object IdentifierFormat extends JsonFormat[Identifier] { def read(value: JsValue): Identifier = value match { case JsString(s) => val components = s.split(":") if (components.length == 3) { val parsed = for { pkgId <- PackageId.fromString(components(0)) mod <- DottedName.fromString(components(1)) entity <- DottedName.fromString(components(2)) } yield Identifier(pkgId, QualifiedName(mod, entity)) parsed match { case Left(e) => deserializationError(e) case Right(id) => id } } else { deserializationError(s"Expected trigger identifier of the form pkgid:mod:name but got $s") } case _ => deserializationError("Expected trigger identifier of the form pkgid:mod:name") } def write(id: Identifier): JsValue = JsString(id.toString) } case class StartParams(triggerName: Identifier) implicit val startParamsFormat = jsonFormat1(StartParams) }
Example 19
Source File: CloudWatchSpec.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import org.scalatest.{FunSpec, Matchers} import spray.json.{JsonFormat, JsString} class CloudWatchSpec extends FunSpec with Matchers { it("should format AWS/EC2") { implicitly[JsonFormat[`AWS::CloudWatch::Alarm::Namespace`]].write(`AWS::CloudWatch::Alarm::Namespace`.`AWS/EC2`) should equal(JsString("AWS/EC2")) } it("should format custom namespace") { implicitly[JsonFormat[`AWS::CloudWatch::Alarm::Namespace`]].write(`AWS::CloudWatch::Alarm::Namespace`("hello")) should equal(JsString("hello")) } it("should format implicit custom namespace") { implicitly[JsonFormat[`AWS::CloudWatch::Alarm::Namespace`]].write("hello" : `AWS::CloudWatch::Alarm::Namespace`) should equal(JsString("hello")) } }
Example 20
Source File: CodeCommit.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 21
Source File: SNS.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import com.monsanto.arch.cloudformation.model.{ResourceRef, Token, ConditionRef} import spray.json.{JsonFormat, DefaultJsonProtocol} case class Subscription(Endpoint: Token[String], Protocol: Token[String]) object Subscription extends DefaultJsonProtocol { implicit val format: JsonFormat[Subscription] = jsonFormat2(Subscription.apply) } case class `AWS::SNS::Topic`( name: String, DisplayName: Option[Token[String]] = None, Subscription: Option[Seq[Token[Subscription]]] = None, TopicName: Option[Token[String]] = None, override val DependsOn: Option[Seq[String]] = None, override val Condition: Option[ConditionRef] = None) extends Resource[`AWS::SNS::Topic`] with HasArn { def when(newCondition: Option[ConditionRef] = Condition) = new `AWS::SNS::Topic`(name, DisplayName, Subscription, TopicName, DependsOn, newCondition) override def arn = ResourceRef(this) } object `AWS::SNS::Topic` extends DefaultJsonProtocol { implicit val format: JsonFormat[`AWS::SNS::Topic`] = jsonFormat6(`AWS::SNS::Topic`.apply) } case class `AWS::SNS::TopicPolicy`( name: String, PolicyDocument: PolicyDocument, Topics: Seq[ResourceRef[`AWS::SNS::Topic`]], override val DependsOn: Option[Seq[String]] = None, override val Condition: Option[ConditionRef] = None) extends Resource[`AWS::SNS::TopicPolicy`] { def when(newCondition: Option[ConditionRef] = Condition) = new `AWS::SNS::TopicPolicy`(name, PolicyDocument, Topics, DependsOn, newCondition) } object `AWS::SNS::TopicPolicy` extends DefaultJsonProtocol { implicit val format: JsonFormat[`AWS::SNS::TopicPolicy`] = jsonFormat5(`AWS::SNS::TopicPolicy`.apply) } trait Subscribable { def asSubscription : Token[Subscription] } case class `AWS::SNS::Subscription`( name : String, Endpoint : Option[Token[String]] = None, Protocol : Token[String], TopicArn : Token[String], override val DependsOn: Option[Seq[String]] = None, override val Condition : Option[ConditionRef] = None) extends Resource[`AWS::SNS::Subscription`] { override def when(newCondition: Option[ConditionRef]): `AWS::SNS::Subscription` = copy(Condition = newCondition) } object `AWS::SNS::Subscription` extends DefaultJsonProtocol { implicit val format : JsonFormat[`AWS::SNS::Subscription`] = jsonFormat6(`AWS::SNS::Subscription`.apply) }
Example 22
Source File: SQS.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import com.monsanto.arch.cloudformation.model.Token.TokenSeq import com.monsanto.arch.cloudformation.model.{ConditionRef, Token, `Fn::GetAtt`} import spray.json.{DefaultJsonProtocol, JsonFormat} case class `AWS::SQS::Queue`(name: String, QueueName: Token[String], DelaySeconds: Token[Int], MessageRetentionPeriod: Token[Int], ReceiveMessageWaitTimeSeconds: Token[Int], VisibilityTimeout: Token[Int], RedrivePolicy: Option[RedrivePolicy] = None, override val DependsOn: Option[Seq[String]] = None, override val Condition: Option[ConditionRef] = None) extends Resource[`AWS::SQS::Queue`] with HasArn with Subscribable { override def arn = `Fn::GetAtt`(Seq(name, "Arn")) def when(newCondition: Option[ConditionRef] = Condition) = copy(Condition = newCondition) override def asSubscription = Subscription( Endpoint = arn, Protocol = "sqs" ) } object `AWS::SQS::Queue` extends DefaultJsonProtocol { implicit val format: JsonFormat[`AWS::SQS::Queue`] = jsonFormat9(`AWS::SQS::Queue`.apply) } case class `AWS::SQS::QueuePolicy`(name: String, PolicyDocument: PolicyDocument, Queues: TokenSeq[String], override val DependsOn: Option[Seq[String]] = None, override val Condition: Option[ConditionRef] = None ) extends Resource[`AWS::SQS::QueuePolicy`] { def when(newCondition: Option[ConditionRef] = Condition) = copy(Condition = newCondition) } object `AWS::SQS::QueuePolicy` extends DefaultJsonProtocol { implicit val format: JsonFormat[`AWS::SQS::QueuePolicy`] = jsonFormat5(`AWS::SQS::QueuePolicy`.apply) } case class RedrivePolicy( deadLetterTargetArn: Token[String], maxReceiveCount: Token[Int] ) object RedrivePolicy extends DefaultJsonProtocol { implicit val format: JsonFormat[RedrivePolicy] = jsonFormat2(RedrivePolicy.apply) }
Example 23
Source File: ECR.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import com.monsanto.arch.cloudformation.model.{ConditionRef, Token} import spray.json.{DefaultJsonProtocol, JsonFormat} case class `AWS::ECR::Repository`( name: String, RepositoryName: Option[Token[String]], RepositoryPolicyText: Option[Token[PolicyDocument]] = None, override val DependsOn: Option[Seq[String]] = None, override val Condition: Option[ConditionRef] = None ) extends Resource[`AWS::ECR::Repository`] { def when(newCondition: Option[ConditionRef] = Condition) = new `AWS::ECR::Repository`(name, RepositoryName, RepositoryPolicyText, DependsOn, newCondition) } object `AWS::ECR::Repository` extends DefaultJsonProtocol { implicit val format: JsonFormat[`AWS::ECR::Repository`] = jsonFormat5(`AWS::ECR::Repository`.apply) }
Example 24
Source File: ElasticSearch.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 25
Source File: EKS.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import com.monsanto.arch.cloudformation.model.{ConditionRef, ResourceRef, Token} import spray.json.{DefaultJsonProtocol, JsonFormat} case class `AWS::EKS::Cluster`( name: String, Name: Token[String], ResourcesVpcConfig: Token[ResourcesVpcConfig], RoleArn: Token[String], Version: Option[Token[String]] = None, override val DependsOn: Option[Seq[String]] = None, override val Condition: Option[ConditionRef] = None ) extends Resource[`AWS::EKS::Cluster`] { def when(newCondition: Option[ConditionRef] = Condition) = new `AWS::EKS::Cluster`(name, Name, ResourcesVpcConfig, RoleArn, Version, DependsOn, newCondition) } case class ResourcesVpcConfig(SecurityGroupIds : Seq[Token[ResourceRef[`AWS::EC2::SecurityGroup`]]], SubnetIds : Seq[Token[ResourceRef[`AWS::EC2::Subnet`]]]) object ResourcesVpcConfig extends DefaultJsonProtocol { implicit val format: JsonFormat[ResourcesVpcConfig] = jsonFormat2(ResourcesVpcConfig.apply) } object `AWS::EKS::Cluster` extends DefaultJsonProtocol { implicit val format: JsonFormat[`AWS::EKS::Cluster`] = jsonFormat7(`AWS::EKS::Cluster`.apply) }
Example 26
Source File: CloudTrail.scala From cloudformation-template-generator with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.monsanto.arch.cloudformation.model.resource import com.monsanto.arch.cloudformation.model.{ConditionRef, Token} import spray.json.DefaultJsonProtocol._ import spray.json.JsonFormat case class `AWS::CloudTrail::Trail`( name : String, CloudWatchLogsLogGroupArn : Option[Token[String]] = None, CloudWatchLogsRoleArn : Option[Token[String]] = None, EnableLogFileValidation : Option[Boolean] = None, IncludeGlobalServiceEvents : Option[Boolean] = None, IsLogging : Boolean, IsMultiRegionTrail : Option[Boolean] = None, KMSKeyId : Option[Token[String]] = None, S3BucketName : Token[String], S3KeyPrefix : Token[String], SnsTopicName : Option[Token[String]] = None, Tags : Seq[ResourceTag], override val DependsOn: Option[Seq[String]] = None, override val Condition: Option[ConditionRef] = None ) extends Resource[`AWS::CloudTrail::Trail`] { override def when(newCondition: Option[ConditionRef]): `AWS::CloudTrail::Trail` = copy(Condition = newCondition) } object `AWS::CloudTrail::Trail` { implicit val format : JsonFormat[`AWS::CloudTrail::Trail`] = jsonFormat14(`AWS::CloudTrail::Trail`.apply) }
Example 27
Source File: JsonRegistry.scala From eventsourcing-intro with Apache License 2.0 | 5 votes |
package eu.reactivesystems.league.infra import eu.reactivesystems.league.impl.{ ClubRegistered, GamePlayed, ResultRevoked } import eu.reactivesystems.league.impl.LeagueEntity._ import spray.json.JsonFormat import scala.reflect.ClassTag object JsonRegistry { val mappings: Map[String, JsonFormat[AnyRef]] = Map( Entry[AddGame], Entry[AddClub], Entry[ChangeGame], Entry[InvalidCommand], Entry[LeagueState], Entry[ClubRegistered], Entry[GamePlayed], Entry[ResultRevoked] ) object Entry { def apply[A: ClassTag: JsonFormat](): (String, JsonFormat[AnyRef]) = (implicitly[ClassTag[A]].runtimeClass .asInstanceOf[Class[A]] .getName, implicitly[JsonFormat[A]].asInstanceOf[JsonFormat[AnyRef]]) } }
Example 28
Source File: SchedoscopeJsonDataFormat.scala From schedoscope with Apache License 2.0 | 5 votes |
package org.schedoscope.scheduler.rest import org.schedoscope.scheduler.service._ import spray.json.{DefaultJsonProtocol, JsonFormat} object SchedoscopeJsonDataFormat extends DefaultJsonProtocol { implicit val runStatusFormat = jsonFormat5(RunStatus) implicit val actionStatusFormat = jsonFormat5(TransformationStatus) implicit val actionStatusListFormat = jsonFormat2(TransformationStatusList) implicit val viewTransformationStatusFormat: JsonFormat[ViewTransformationStatus] = lazyFormat(jsonFormat2(ViewTransformationStatus)) implicit val viewStatusFormat: JsonFormat[ViewStatus] = lazyFormat(jsonFormat15(ViewStatus)) implicit val fieldStatusFormat: JsonFormat[FieldStatus] = lazyFormat(jsonFormat3(FieldStatus)) implicit val viewStatusListFormat = jsonFormat2(ViewStatusList) implicit val queueStatusListFormat = jsonFormat2(QueueStatusList) }
Example 29
Source File: Unmarshallers.scala From JustinDB with Apache License 2.0 | 5 votes |
package justin.httpapi import java.util.UUID import akka.http.scaladsl.unmarshalling._ import akka.stream.Materializer import spray.json.{JsString, JsValue, JsonFormat, _} import scala.concurrent.{ExecutionContext, Future} import scala.util.{Failure, Success, Try} object Unmarshallers { implicit val UuidFormat = new JsonFormat[UUID] { override def read(json: JsValue): UUID = { json match { case JsString(uuid) => Try(UUID.fromString(uuid)) match { case Success(parsedUuid) => parsedUuid case Failure(_) => deserializationError("UUID could not be created from given string") } case _ => deserializationError("UUID could not be converted to UUID object.") } } override def write(obj: UUID): JsValue = JsString(obj.toString) } object UUIDUnmarshaller extends FromStringUnmarshaller[UUID] { override def apply(value: String)(implicit ec: ExecutionContext, materializer: Materializer): Future[UUID] = { Future.apply(UUID.fromString(value)) } } }
Example 30
Source File: Side.scala From scalanda with MIT License | 5 votes |
package com.msilb.scalanda.common.model import spray.json.{JsString, JsValue, JsonFormat, deserializationError} sealed trait Side object Side { case object Buy extends Side { override def toString = "buy" } case object Sell extends Side { override def toString = "sell" } implicit object SideJsonFormat extends JsonFormat[Side] { def write(x: Side): JsValue = JsString(x.toString) def read(value: JsValue): Side = value match { case JsString(x) => x match { case "buy" => Buy case "sell" => Sell } case x => deserializationError("Expected Side as JsString, but got " + x) } } }
Example 31
Source File: ClickhouseJsonSupport.scala From clickhouse-scala-client with GNU Lesser General Public License v3.0 | 5 votes |
package com.crobox.clickhouse.dsl.marshalling import com.crobox.clickhouse.time.IntervalStart import org.joda.time.format.{DateTimeFormatter, DateTimeFormatterBuilder, ISODateTimeFormat} import org.joda.time.{DateTime, DateTimeZone} import spray.json.{JsNumber, JsString, JsValue, JsonFormat, deserializationError, _} import scala.util.Try trait ClickhouseJsonSupport { override def read(json: JsValue): IntervalStart = json match { case JsString(value) => value match { case month(relativeMonth, timezoneId) => new DateTime(UnixStartTimeWithoutTimeZone) .withZoneRetainFields(DateTimeZone.forID(timezoneId)) .plusMonths(relativeMonth.toInt - RelativeMonthsSinceUnixStart) .withZone(DateTimeZone.UTC) case date(dateOnly, timezoneId) => //should handle quarter and year grouping as it returns a date formatter .parseDateTime(dateOnly) .withZoneRetainFields(DateTimeZone.forID(timezoneId)) .withZone(DateTimeZone.UTC) case msTimestamp(millis) => new DateTime(millis.toLong, DateTimeZone.UTC) case timestamp(secs) => new DateTime(secs.toLong * 1000, DateTimeZone.UTC) case _ => // sometimes clickhouse mistakenly returns a long / int value as JsString. Therefor, first try to // parse it as a long... val dateTime = Try { new DateTime(value.toLong, DateTimeZone.UTC) }.toOption // continue with parsing using the formatter dateTime.getOrElse { try { formatter.parseDateTime(value) } catch { case _: IllegalArgumentException => error(s"Couldn't parse $value into valid date time") case _: UnsupportedOperationException => error("Unsupported operation, programmatic misconfiguration?") } } } case JsNumber(millis) => new DateTime(millis.longValue, DateTimeZone.UTC) case _ => throw DeserializationException(s"Unknown date format read from clickhouse for $json") } def error(v: Any): DateTime = { val example = readFormatter.print(0) deserializationError( f"'$v' is not a valid date value. Dates must be in compact ISO-8601 format, e.g. '$example'" ) } } } object ClickhouseJsonSupport extends DefaultJsonProtocol with ClickhouseJsonSupport
Example 32
Source File: HydraKafkaJsonSupport.scala From hydra with Apache License 2.0 | 5 votes |
package hydra.kafka.marshallers import akka.http.scaladsl.marshalling.{Marshaller, Marshalling} import akka.http.scaladsl.model.ContentTypes import akka.util.ByteString import hydra.core.marshallers.HydraJsonSupport import org.apache.kafka.common.{Node, PartitionInfo} import spray.json.{JsNumber, JsObject, JsString, JsValue, JsonFormat} import scala.concurrent.Future trait HydraKafkaJsonSupport extends HydraJsonSupport { implicit object NodeJsonFormat extends JsonFormat[Node] { override def write(node: Node): JsValue = { JsObject( "id" -> JsNumber(node.idString), "host" -> JsString(node.host), "port" -> JsNumber(node.port) ) } override def read(json: JsValue): Node = { json.asJsObject.getFields("id", "host", "port") match { case Seq(id, host, port) => new Node( id.convertTo[Int], host.convertTo[String], port.convertTo[Int] ) case other => spray.json.deserializationError( "Cannot deserialize Node. Invalid input: " + other ) } } } implicit object PartitionInfoJsonFormat extends JsonFormat[PartitionInfo] { import spray.json._ override def write(p: PartitionInfo): JsValue = { JsObject( "partition" -> JsNumber(p.partition()), "leader" -> p.leader().toJson, "isr" -> JsArray(p.inSyncReplicas().toJson) ) } override def read(json: JsValue): PartitionInfo = ??? } implicit val stringFormat = Marshaller[String, ByteString] { ec ⇒ s => Future.successful { List( Marshalling.WithFixedContentType( ContentTypes.`application/json`, () => ByteString(s) ) ) } } }
Example 33
Source File: JsonSupport.scala From akka-http-slick-sample with MIT License | 5 votes |
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) }