/
MinValidator.scala
78 lines (63 loc) · 2.13 KB
/
MinValidator.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
package com.twitter.finatra.json.internal.caseclass.validation.validators
import com.twitter.finatra.validation.{
ErrorCode,
Min,
ValidationMessageResolver,
ValidationResult,
Validator
}
private[json] object MinValidator {
def errorMessage(resolver: ValidationMessageResolver, value: Any, minValue: Long): String = {
resolver.resolve(classOf[Min], value, minValue)
}
}
private[json] class MinValidator(
validationMessageResolver: ValidationMessageResolver,
annotation: Min
) extends Validator[Min, Any](validationMessageResolver, annotation) {
private val minValue = annotation.value()
/* Public */
override def isValid(value: Any): ValidationResult = {
value match {
case arrayValue: Array[_] =>
validationResult(arrayValue)
case traversableValue: Traversable[_] =>
validationResult(traversableValue)
case bigDecimalValue: BigDecimal =>
validationResult(bigDecimalValue)
case bigIntValue: BigInt =>
validationResult(bigIntValue)
case numberValue: Number =>
validationResult(numberValue)
case _ =>
throw new IllegalArgumentException(s"Class [${value.getClass}] is not supported by ${this.getClass}")
}
}
/* Private */
private def validationResult(value: Traversable[_]) = {
ValidationResult.validate(
minValue <= value.size,
errorMessage(Integer.valueOf(value.size)),
errorCode(Integer.valueOf(value.size))
)
}
private def validationResult(value: BigDecimal) = {
ValidationResult.validate(BigDecimal(minValue) <= value, errorMessage(value), errorCode(value))
}
private def validationResult(value: BigInt) = {
ValidationResult.validate(BigInt(minValue) <= value, errorMessage(value), errorCode(value))
}
private def validationResult(value: Number) = {
ValidationResult.validate(
minValue <= value.doubleValue(),
errorMessage(value),
errorCode(value)
)
}
private def errorMessage(value: Number) = {
MinValidator.errorMessage(validationMessageResolver, value, minValue)
}
private def errorCode(value: Number) = {
ErrorCode.ValueTooSmall(minValue, value)
}
}