-
Notifications
You must be signed in to change notification settings - Fork 5
/
Json.scala
executable file
·667 lines (567 loc) · 16.9 KB
/
Json.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
/*
* Copyright (c) 2021 Typelevel
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package fabric
import fabric.filter.JsonFilter
import fabric.merge.MergeConfig
import scala.collection.immutable.VectorMap
import scala.util.Try
/**
* Json represents the base sealed trait for all representable types in Fabric.
*/
sealed trait Json extends Any {
type Type
/**
* Looks up a Json by name in the children.
*
* Throws an exception if invoked on anything except `Obj`
*/
final def apply(lookup: String): Json = get(lookup).getOrElse(
throw new RuntimeException(s"Lookup not found: $lookup")
)
/**
* Looks up a Json by name in the children.
*/
final def get(lookup: String): Option[Json] = this match {
case Obj(map) => map.get(lookup)
case _ => None
}
final def get(lookup: PathEntry): Option[Json] = lookup match {
case PathEntry.Named(name) =>
this match {
case Obj(map) => map.get(name)
case _ => None
}
case PathEntry.Indexed(index) =>
this match {
case Arr(vec) => Try(vec(index)).toOption
case _ => None
}
}
/**
* Looks up a Json based on Path
*
* Example: val o: Option[Json] = someValue("first" \ "second" \ "third")
*/
final def get(path: Path): Option[Json] = if (path.isEmpty) {
Some(this)
} else {
val lookup = path()
val next = path.next()
get(lookup).flatMap(_.get(next))
}
/**
* Looks up a Json based on Path
*
* Example: `val v = someValue("first" \ "second" \ "third")`
*/
final def apply(path: Path): Json =
get(path).getOrElse(throw new RuntimeException(s"Path not found: $path"))
/**
* Looks up a Json by name in the children or creates a new Obj if it doesn't
* exist.
*/
final def getOrCreate(lookup: PathEntry): Json =
get(lookup).getOrElse(lookup match {
case _: PathEntry.Named => obj()
case PathEntry.Indexed(index) =>
throw new RuntimeException(
s"Expecting indexed value: $index, but nothing found"
)
})
/**
* Modifies the value at the specified path and returns back a new root Json
* with the modified path.
*
* Note: We use the term "modify" here from an immutable standpoint. The
* original Json will not change.
*
* @param path
* the path to modify
* @param f
* the function that takes the current Json and returns the modified Json
* @return
* new root Json representing the changes
*/
def modify(path: Path)(f: Json => Json): Json = if (path.isEmpty) {
f(this)
} else {
val child = this.getOrCreate(path())
child.modify(path.next())(f) match {
case Null =>
path() match {
case PathEntry.Named(name) => Obj(asMap - name)
case PathEntry.Indexed(index) => Arr(asVector.patch(index, Nil, 1))
}
case v if v == child => this
case v if isObj =>
path() match {
case PathEntry.Named(name) => Obj(asMap + (name -> v))
case pe =>
throw new RuntimeException(s"Unsupported PathEntry: $pe on obj: $v")
}
case v if isArr =>
throw new RuntimeException(s"Unsupported scenario: $v on ${path()}")
case v =>
path() match {
case PathEntry.Named(name) => obj(name -> v)
case PathEntry.Indexed(0) => arr(v)
case PathEntry.Indexed(index) =>
throw new RuntimeException(
s"Unsupported index for new array: $index - $v"
)
}
}
}
/**
* Applies the filter recursively to this value beginning on the leafs working
* backward up the tree back to the root.
*
* @param filter
* the filter to apply
* @return
* Option[Json]
*/
final def filter(filter: JsonFilter): Option[Json] = JsonFilter(filter, this)
/**
* Convenience functionality for #modify to set a specific value at a path.
*
* @param path
* the path to replace
* @param value
* the new value to set
* @return
* new root Json representing the changes
*/
def set(path: Path, value: Json): Json = modify(path)(_ => value)
/**
* Convenience functionality for #modify to remove the value at a specific
* path.
*
* @param path
* the path to remove
* @return
* new root Json representing the changes
*/
def remove(path: Path): Json = set(path, Null)
/**
* Merges a Json at the specified path
*
* @param value
* the value to merge
* @param path
* the path (defaults to Path.empty)
* @param config
* the merge configuration (defaults to MergeConfig)
* @return
* root Json after merge
*/
final def merge(
value: Json,
path: Path = Path.empty,
config: MergeConfig = MergeConfig
): Json = modify(path) { current =>
config.merge(current, value, path)
}
/**
* The type of value
*/
def `type`: JsonType[Type]
def isEmpty: Boolean
def nonEmpty: Boolean = !isEmpty
/**
* True if this is an Obj
*/
def isObj: Boolean = `type` == JsonType.Obj
/**
* True if this is an Arr
*/
def isArr: Boolean = `type` == JsonType.Arr
/**
* True if this is a Str
*/
def isStr: Boolean = `type` == JsonType.Str
/**
* True if this is a Num
*/
def isNum: Boolean = isNumInt || isNumDec
def isNumInt: Boolean = `type` == JsonType.NumInt
def isNumDec: Boolean = `type` == JsonType.NumDec
/**
* True if this is a Bool
*/
def isBool: Boolean = `type` == JsonType.Bool
/**
* True if this is a Null
*/
def isNull: Boolean = `type` == JsonType.Null
/**
* Safely casts this Json as the specified JsonType. Throws an exception if
* not a match.
*
* @param `type`
* the type to cast this JsonType as
* @tparam V
* the return type
*/
def asType[V <: Json](`type`: JsonType[V]): V = if (this.`type`.is(`type`)) {
this.asInstanceOf[V]
} else if (`type` == JsonType.Str) {
str(toString).asInstanceOf[V]
} else {
throw new RuntimeException(s"$this is a ${this.`type`}, not a ${`type`}")
}
/**
* Safely casts this Json as the specified JsonType. Returns None if it's a
* different type.
*
* @param `type`
* the value type of value you want.
* @tparam V
* the value type
* @return
* Option[V]
*/
final def getAsType[V <: Json](`type`: JsonType[V]): Option[V] = if (
this.`type` == `type`
) {
Some(this.asInstanceOf[V])
} else {
None
}
/**
* Casts to Obj or throws an exception if not an Obj
*/
def asObj: Obj = asType[Obj](JsonType.Obj)
/**
* Casts to Arr or throws an exception if not an Arr
*/
def asArr: Arr = asType[Arr](JsonType.Arr)
/**
* Casts to Str or throws an exception if not a Str
*/
def asStr: Str = asType[Str](JsonType.Str)
/**
* Casts to Num or throws an exception if not a Num
*/
def asNum: Num = asType[Num](JsonType.Num)
/**
* Casts to NumInt or throws an exception if not a NumInt
*/
def asNumInt: NumInt = asType[NumInt](JsonType.NumInt)
/**
* Casts to NumDec or throws an exception if not a NumDec
*/
def asNumDec: NumDec = asType[NumDec](JsonType.NumDec)
/**
* Casts to Bool or throws an exception if not a Bool
*/
def asBool: Bool = asType[Bool](JsonType.Bool)
/**
* Casts to Obj if it's of Obj type or returns None
*/
def getObj: Option[Obj] = getAsType(JsonType.Obj)
/**
* Casts to Arr if it's of Arr type or returns None
*/
def getArr: Option[Arr] = getAsType(JsonType.Arr)
/**
* Casts to Str if it's of Str type or returns None
*/
def getStr: Option[Str] = getAsType(JsonType.Str)
/**
* Casts to Num if it's of Num type or returns None
*/
def getNum: Option[Num] = getAsType(JsonType.Num)
/**
* Casts to Bool if it's of Bool type or returns None
*/
def getBool: Option[Bool] = getAsType(JsonType.Bool)
/**
* Convenience method for asObj.value
*/
def asMap: Map[String, Json] = asObj.value
/**
* Convenience method for asArr.value
*/
def asVector: Vector[Json] = asArr.value
/**
* Convenience method for asStr.value
*/
def asString: String = asStr.value
/**
* Convenience method for asNum.value
*/
def asBigDecimal: BigDecimal = asNum.asBigDecimal
def asByte: Byte = asNum.asByte
def asShort: Short = asNum.asShort
def asInt: Int = asNum.asInt
def asLong: Long = asNum.asLong
def asFloat: Float = asNum.asFloat
def asDouble: Double = asNum.asDouble
/**
* Convenience method for asBool.value
*/
def asBoolean: Boolean = asBool.value
/**
* Convenience method for getObj.map(_.value)
*/
def getMap: Option[Map[String, Json]] = getObj.map(_.value)
/**
* Convenience method for getArr.map(_.value)
*/
def getVector: Option[Vector[Json]] = getArr.map(_.value)
/**
* Convenience method for getStr.map(_.value)
*/
def getString: Option[String] = getStr.map(_.value)
/**
* Convenience method for getNum.map(_.value)
*/
def getBigDecimal: Option[BigDecimal] = getNum.map(_.asBigDecimal)
def getByte: Option[Byte] = getNum.map(_.asByte)
def getShort: Option[Short] = getNum.map(_.asShort)
def getInt: Option[Int] = getNum.map(_.asInt)
def getLong: Option[Long] = getNum.map(_.asLong)
def getFloat: Option[Float] = getNum.map(_.asFloat)
def getDouble: Option[Double] = getNum.map(_.asDouble)
/**
* Convenience method for getBool.map(_.value)
*/
def getBoolean: Option[Boolean] = getBool.map(_.value)
}
object Json {
/**
* Merges multiple Values together. Convenience functionality to handle more
* than two Values.
*/
def merge(values: Json*): Json = if (values.nonEmpty) {
values.tail.foldLeft(values.head)((merged, value) => merged.merge(value))
} else {
Null
}
}
/**
* Obj represents a Map of key-value pairs (String, Json)
*/
final class Obj private (val value: Map[String, Json])
extends AnyVal
with Json {
override type Type = Obj
def keys: Set[String] = value.keySet
override def isEmpty: Boolean = value.isEmpty
override def `type`: JsonType[Obj] = JsonType.Obj
override def toString: String = value
.map { case (key, value) =>
s""""$key": $value"""
}
.mkString("{", ", ", "}")
}
object Obj {
var ExcludeNullValues: Boolean = false
val empty: Obj = Obj()
private def clean(map: Map[String, Json]): Map[String, Json] = if (
ExcludeNullValues
) {
map.filter { case (_, value) =>
value != Null
}
} else {
map
}
def apply(value: Map[String, Json]): Obj = new Obj(clean(value))
def apply(values: (String, Json)*): Obj = apply(VectorMap(values: _*))
def unapply(obj: Obj): Some[Map[String, Json]] = Some(obj.value)
/**
* Processes the supplied map creating an Obj for it. If `parsePath` is set,
* the key will be extracted as as a path based on the `parsePath` separation
* character. If it is not set, the key will be set as-is.
*
* @param map
* the map to parse into an Obj
* @param parsePath
* the optional separation character to parse the keys into paths (defaults
* to Some('.'))
* @return
* Obj
*/
def process(
map: Map[String, String],
parsePath: Option[Char] = Some('.')
): Obj = {
var o = obj()
map.foreach { case (key, value) =>
parsePath match {
case Some(sep) => {
val path = Path.parse(key, sep)
if (path.nonEmpty) {
o = o.merge(str(value), path).asObj
} else {
o = o.merge(str(value), Path("value")).asObj
}
}
case None => o = o.merge(str(value), Path(key)).asObj
}
}
o
}
}
/**
* Str represents a String
*/
case class Str(value: String) extends AnyVal with Json {
override type Type = Str
override def `type`: JsonType[Str] = JsonType.Str
override def isEmpty: Boolean = value.isEmpty
override def asType[V <: Json](`type`: JsonType[V]): V = `type` match {
case JsonType.Bool =>
Try(Bool(value.toBoolean)).toOption
.map(_.asInstanceOf[V])
.getOrElse(
throw ConversionException(
s"$value is a Str and can't be converted to Bool"
)
)
case JsonType.NumInt =>
Try(NumInt(value.toLong)).toOption
.map(_.asInstanceOf[V])
.getOrElse(
throw ConversionException(
s"$value is a Str and can't be converted to NumInt"
)
)
case JsonType.NumDec | JsonType.Num =>
Try(NumDec(BigDecimal(value))).toOption
.map(_.asInstanceOf[V])
.getOrElse(
throw ConversionException(
s"$value is a Str and can't be converted to NumDec"
)
)
case _ => super.asType[V](`type`)
}
override def toString: String = s""""${Str.escape(value)}""""
}
object Str {
def escape(s: String): String = s.map {
case '\b' => "\\b"
case '\f' => "\\f"
case '\n' => "\\n"
case '\r' => "\\r"
case '\t' => "\\t"
case '\\' => "\\\\"
case '"' => "\\\""
case c => c.toString
}.mkString
}
sealed trait Num extends Any with Json {
def asInt: Int
def asLong: Long
def asFloat: Float
def asDouble: Double
def asBigInt: BigInt
def asBigDecimal: BigDecimal
}
/**
* NumInt represents a numeric value and wraps a Long
*/
case class NumInt(value: Long) extends Num {
override type Type = NumInt
override def `type`: JsonType[NumInt] = JsonType.NumInt
override def asType[V <: Json](`type`: JsonType[V]): V = if (
`type` == JsonType.NumDec
) {
NumDec(BigDecimal(value)).asInstanceOf[V]
} else {
super.asType[V](`type`)
}
override def asByte: Byte = value.toByte
override def asShort: Short = value.toShort
override def asInt: Int = value.toInt
override def asLong: Long = value
override def asFloat: Float = value.toFloat
override def asDouble: Double = value.toDouble
override def asBigInt: BigInt = BigInt(value)
override def asBigDecimal: BigDecimal = BigDecimal(value)
override def isEmpty: Boolean = false
override def equals(obj: Any): Boolean = obj match {
case that: NumInt => this.value == that.value
case that: NumDec => BigDecimal(value) == that.value
case _ => false
}
override def toString: String = value.toString
}
/**
* NumDec represents a numeric value and wraps a BigDecimal
*/
case class NumDec(value: BigDecimal) extends Num {
override type Type = NumDec
override def `type`: JsonType[NumDec] = JsonType.NumDec
override def asType[V <: Json](`type`: JsonType[V]): V = if (
`type` == JsonType.NumInt
) {
NumInt(value.toLong).asInstanceOf[V]
} else {
super.asType[V](`type`)
}
override def asByte: Byte = value.toByte
override def asShort: Short = value.toShort
override def asInt: Int = value.toInt
override def asLong: Long = value.toLong
override def asFloat: Float = value.toFloat
override def asDouble: Double = value.toDouble
override def asBigInt: BigInt = value.toBigInt
override def asBigDecimal: BigDecimal = value
override def isEmpty: Boolean = false
override def equals(obj: Any): Boolean = obj match {
case that: NumInt => this.value == BigDecimal(that.value)
case that: NumDec => this.value == that.value
case _ => false
}
override def toString: String = value.toString()
}
/**
* Bool represents a boolean value
*/
case class Bool(value: Boolean) extends AnyVal with Json {
override type Type = Bool
override def `type`: JsonType[Bool] = JsonType.Bool
override def isEmpty: Boolean = false
override def toString: String = value.toString
}
/**
* Arr represents an array (Vector[Json])
*/
case class Arr(value: Vector[Json]) extends AnyVal with Json {
override type Type = Arr
override def `type`: JsonType[Arr] = JsonType.Arr
override def isEmpty: Boolean = value.isEmpty
override def toString: String = value.mkString("[", ", ", "]")
}
sealed trait Null extends Json
/**
* Null represents a null Json
*/
object Null extends Null {
override type Type = Null
override def `type`: JsonType[Null] = JsonType.Null
override def isEmpty: Boolean = true
override def toString: String = "null"
}