From 1286317ff473265333a3809d1038aa133fd6d662 Mon Sep 17 00:00:00 2001 From: Zach Smith Date: Wed, 20 Dec 2017 12:34:56 -0800 Subject: Add InetAddress JSON format --- src/main/scala/xyz/driver/core/json.scala | 13 +++++++++++++ src/test/scala/xyz/driver/core/JsonTest.scala | 19 +++++++++++++++++++ 2 files changed, 32 insertions(+) (limited to 'src') diff --git a/src/main/scala/xyz/driver/core/json.scala b/src/main/scala/xyz/driver/core/json.scala index 313849c..e338638 100644 --- a/src/main/scala/xyz/driver/core/json.scala +++ b/src/main/scala/xyz/driver/core/json.scala @@ -1,5 +1,6 @@ package xyz.driver.core +import java.net.InetAddress import java.util.UUID import scala.reflect.runtime.universe._ @@ -143,6 +144,18 @@ object json { implicit val authCredentialsFormat = jsonFormat2(AuthCredentials) + implicit object inetAddressFormat extends JsonFormat[InetAddress] { + override def read(json: JsValue): InetAddress = json match { + case JsString(ipString) => + Try(InetAddress.getByName(ipString)) + .getOrElse(deserializationError(s"Invalid IP Address: $ipString")) + case _ => deserializationError(s"Expected string for IP Address, got $json") + } + + override def write(obj: InetAddress): JsValue = + JsString(obj.getHostAddress) + } + class EnumJsonFormat[T](mapping: (String, T)*) extends RootJsonFormat[T] { private val map = mapping.toMap diff --git a/src/test/scala/xyz/driver/core/JsonTest.scala b/src/test/scala/xyz/driver/core/JsonTest.scala index 26e3796..a45025a 100644 --- a/src/test/scala/xyz/driver/core/JsonTest.scala +++ b/src/test/scala/xyz/driver/core/JsonTest.scala @@ -1,5 +1,7 @@ package xyz.driver.core +import java.net.InetAddress + import eu.timepit.refined.collection.NonEmpty import eu.timepit.refined.numeric.Positive import eu.timepit.refined.refineMV @@ -198,4 +200,21 @@ class JsonTest extends FlatSpec with Matchers { val parsedRefinedNumber = jsonFormat.read(writtenJson) parsedRefinedNumber should be(referenceRefinedNumber) } + + "InetAddress format" should "read and write correct JSON" in { + val address = InetAddress.getByName("127.0.0.1") + val json = inetAddressFormat.write(address) + + json shouldBe JsString("127.0.0.1") + + val parsed = inetAddressFormat.read(json) + parsed shouldBe address + } + + it should "throw a DeserializationException for an invalid IP Address" in { + assertThrows[DeserializationException] { + val invalidAddress = JsString("foobar") + inetAddressFormat.read(invalidAddress) + } + } } -- cgit v1.2.3