2c336253ddd33afdfcf9c9d14b72799b09b51e34
[aquarium] / src / test / scala / gr / grnet / aquarium / converter / ConverterTest.scala
1 /*
2  * Copyright 2011-2012 GRNET S.A. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or
5  * without modification, are permitted provided that the following
6  * conditions are met:
7  *
8  *   1. Redistributions of source code must retain the above
9  *      copyright notice, this list of conditions and the following
10  *      disclaimer.
11  *
12  *   2. Redistributions in binary form must reproduce the above
13  *      copyright notice, this list of conditions and the following
14  *      disclaimer in the documentation and/or other materials
15  *      provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
18  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
21  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
24  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  *
30  * The views and conclusions contained in the software and
31  * documentation are those of the authors and should not be
32  * interpreted as representing official policies, either expressed
33  * or implied, of GRNET S.A.
34  */
35
36 package gr.grnet.aquarium.converter
37
38 import net.liftweb.json._
39 import org.junit.{Assert, Test}
40 import gr.grnet.aquarium.AquariumException
41 import gr.grnet.aquarium.converter.StdConverters.{AllConverters ⇒ Converters}
42 import com.mongodb.DBObject
43 import gr.grnet.aquarium.store.memory._
44 import gr.grnet.aquarium.util.json.JsonSupport
45 import gr.grnet.aquarium.util.Loggable
46
47 /**
48  *
49  * @author Christos KK Loverdos <loverdos@gmail.com>
50  */
51
52 case class Foo(map: Map[Int, Int])
53
54 object FooSerializer extends Serializer[Foo] {
55   val FooClass = classOf[Foo]
56
57   def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), Foo] = {
58     case (TypeInfo(FooClass, _), jValue) ⇒
59       var _map: Map[Int, Int] = Map()
60       jValue match {
61         case JObject(List(JField("map", JArray(pairs)))) ⇒
62           for(pair <- pairs) {
63             pair match {
64               case JObject(List(JField("k", JInt(k)), JField("v", JInt(v)))) ⇒
65                 pair
66                 _map = _map.updated(k.intValue(), v.intValue())
67               case _ ⇒
68                 throw new AquariumException(
69                   "While deserializing a %s from %s".format(
70                     gr.grnet.aquarium.util.shortNameOfClass(classOf[Foo]),
71                     jValue))
72             }
73           }
74
75         case _ ⇒
76           throw new AquariumException(
77             "While deserializing a %s from %s".format(
78               gr.grnet.aquarium.util.shortNameOfClass(classOf[Foo]),
79               jValue))
80       }
81       Foo(_map)
82
83     case other ⇒
84       throw new AquariumException(
85         "While desiariling a %s from %s".format(
86           gr.grnet.aquarium.util.shortNameOfClass(classOf[Foo]),
87           other))
88   }
89
90   def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
91     case Foo(map) ⇒
92       val kvs = for {
93         (k, v) <- map
94       } yield JObject(
95         List(
96           JField("k", JInt(k)),
97           JField("v", JInt(v))
98         )
99       )
100
101       JObject(List(JField("map", JArray(kvs.toList))))
102   }
103 }
104
105 class ConverterTest extends Loggable {
106   implicit val Formats = JsonConversions.Formats + FooSerializer
107
108   final val jsonIMEvent = """
109   {
110       "clientID": 3,
111       "details": {},
112       "eventType": "modify",
113       "eventVersion": "1",
114       "id": "e6b209c23894098f9b70f08315a97c7753e29ecc",
115       "isActive": false,
116       "occurredMillis": 1333369801087,
117       "receivedMillis": 1333369801087,
118       "role": "default",
119       "userID": "spapagian@grnet.gr"
120   }
121   """
122
123   @Test
124   def testJSONMapConversion: Unit = {
125     val foo = Foo(Map(1 -> 1, 2 -> 2, 3 -> 3))
126     val foo2 = JsonConversions.jsonToObject[Foo](JsonConversions.anyToJson(foo))
127
128     Assert.assertEquals(foo, foo2)
129   }
130
131   @Test
132   def testJsonText2Pretty: Unit = {
133     val json = """{
134     "x" : 1,
135     "y" : { "a": true, "b": []},
136     "z" : "once upon a time in the west"
137     }"""
138
139     val pretty  = Converters.convertEx[PrettyJsonTextFormat](json)
140   }
141
142   @Test
143   def testJsonText2Compact: Unit = {
144    val json = """{
145    "x" : 1,
146    "y" : { "a": true, "b": []},
147    "z" : "once upon a time in the west"
148    }"""
149
150    val compact = Converters.convertEx[CompactJsonTextFormat](json)
151  }
152
153   @Test
154   def testJsonText: Unit = {
155     val json = """{"x":1,"y":2}"""
156
157     val pretty  = Converters.convertEx[PrettyJsonTextFormat](json)
158     val compact = Converters.convertEx[CompactJsonTextFormat](json)
159     val jValueOfPretty  = Converters.convertEx[JValue](pretty)
160     val jValueOfCompact = Converters.convertEx[JValue](compact)
161
162     Assert.assertEquals(jValueOfPretty, jValueOfCompact)
163   }
164
165   @Test
166   def testJsonToIMEvent: Unit = {
167     Converters.convertEx[MemIMEvent](JsonTextFormat(jsonIMEvent))
168   }
169
170   @Test
171   def testJsonSupportToDBObject: Unit = {
172     val jsonSupport: JsonSupport = Converters.convertEx[MemIMEvent](JsonTextFormat(jsonIMEvent))
173
174     logger.debug("===============")
175     Converters.convertEx[DBObject](jsonSupport)
176   }
177 }