/
Formats.scala
262 lines (222 loc) · 8.71 KB
/
Formats.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
/*
* Copyright 2009-2010 WorldWide Conferencing, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.liftweb
package json
import java.util.{Date, TimeZone}
/** Formats to use when converting JSON.
* Formats are usually configured by using an implicit parameter:
* <pre>
* implicit val formats = net.liftweb.json.DefaultFormats
* </pre>
*/
trait Formats { self: Formats =>
val dateFormat: DateFormat
val typeHints: TypeHints = NoTypeHints
val customSerializers: List[Serializer[_]] = Nil
val fieldSerializers: List[(Class[_], FieldSerializer[_])] = Nil
/**
* The name of the field in JSON where type hints are added (jsonClass by default)
*/
val typeHintFieldName = "jsonClass"
/**
* Parameter name reading strategy. By deafult 'paranamer' is used.
*/
val parameterNameReader: ParameterNameReader = Meta.ParanamerReader
/**
* Adds the specified type hints to this formats.
*/
def + (extraHints: TypeHints): Formats = new Formats {
val dateFormat = Formats.this.dateFormat
override val typeHintFieldName = self.typeHintFieldName
override val parameterNameReader = self.parameterNameReader
override val typeHints = self.typeHints + extraHints
override val customSerializers = self.customSerializers
override val fieldSerializers = self.fieldSerializers
}
/**
* Adds the specified custom serializer to this formats.
*/
def + (newSerializer: Serializer[_]): Formats = new Formats {
val dateFormat = Formats.this.dateFormat
override val typeHintFieldName = self.typeHintFieldName
override val parameterNameReader = self.parameterNameReader
override val typeHints = self.typeHints
override val customSerializers = newSerializer :: self.customSerializers
override val fieldSerializers = self.fieldSerializers
}
/**
* Adds the specified custom serializers to this formats.
*/
def ++ (newSerializers: Traversable[Serializer[_]]): Formats =
newSerializers.foldLeft(this)(_ + _)
def + [A](newSerializer: FieldSerializer[A])(implicit mf: Manifest[A]): Formats = new Formats {
val dateFormat = Formats.this.dateFormat
override val typeHintFieldName = self.typeHintFieldName
override val parameterNameReader = self.parameterNameReader
override val typeHints = self.typeHints
override val customSerializers = self.customSerializers
override val fieldSerializers = (mf.erasure, newSerializer) :: self.fieldSerializers
}
private[json] def fieldSerializer(clazz: Class[_]): Option[FieldSerializer[_]] = {
import ClassDelta._
val ord = Ordering[Int].on[(Class[_], FieldSerializer[_])](x => delta(x._1, clazz))
fieldSerializers filter (_._1.isAssignableFrom(clazz)) match {
case Nil => None
case xs => Some((xs min ord)._2)
}
}
def customSerializer(implicit format: Formats) =
customSerializers.foldLeft(Map(): PartialFunction[Any, JValue]) { (acc, x) =>
acc.orElse(x.serialize)
}
def customDeserializer(implicit format: Formats) =
customSerializers.foldLeft(Map(): PartialFunction[(TypeInfo, JValue), Any]) { (acc, x) =>
acc.orElse(x.deserialize)
}
}
/** Conversions between String and Date.
*/
trait DateFormat {
def parse(s: String): Option[Date]
def format(d: Date): String
}
trait Serializer[A] {
def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), A]
def serialize(implicit format: Formats): PartialFunction[Any, JValue]
}
/** Type hints can be used to alter the default conversion rules when converting
* Scala instances into JSON and vice versa. Type hints must be used when converting
* class which is not supported by default (for instance when class is not a case class).
* <p>
* Example:<pre>
* class DateTime(val time: Long)
*
* val hints = new ShortTypeHints(classOf[DateTime] :: Nil) {
* override def serialize: PartialFunction[Any, JObject] = {
* case t: DateTime => JObject(JField("t", JInt(t.time)) :: Nil)
* }
*
* override def deserialize: PartialFunction[(String, JObject), Any] = {
* case ("DateTime", JObject(JField("t", JInt(t)) :: Nil)) => new DateTime(t.longValue)
* }
* }
* implicit val formats = DefaultFormats.withHints(hints)
* </pre>
*/
trait TypeHints {
import ClassDelta._
val hints: List[Class[_]]
/** Return hint for given type.
*/
def hintFor(clazz: Class[_]): String
/** Return type for given hint.
*/
def classFor(hint: String): Option[Class[_]]
def containsHint_?(clazz: Class[_]) = hints exists (_ isAssignableFrom clazz)
def deserialize: PartialFunction[(String, JObject), Any] = Map()
def serialize: PartialFunction[Any, JObject] = Map()
def components: List[TypeHints] = List(this)
/**
* Adds the specified type hints to this type hints.
*/
def + (hints: TypeHints): TypeHints = CompositeTypeHints(hints.components ::: components)
private[TypeHints] case class CompositeTypeHints(override val components: List[TypeHints]) extends TypeHints {
val hints: List[Class[_]] = components.flatMap(_.hints)
/**
* Chooses most specific class.
*/
def hintFor(clazz: Class[_]): String = components.filter(_.containsHint_?(clazz))
.map(th => (th.hintFor(clazz), th.classFor(th.hintFor(clazz)).getOrElse(error("hintFor/classFor not invertible for " + th))))
.sort((x, y) => delta(x._2, clazz) - delta(y._2, clazz) < 0).head._1
def classFor(hint: String): Option[Class[_]] = hints find (hintFor(_) == hint)
override def deserialize: PartialFunction[(String, JObject), Any] = components.foldLeft[PartialFunction[(String, JObject),Any]](Map()) {
(result, cur) => result.orElse(cur.deserialize)
}
override def serialize: PartialFunction[Any, JObject] = components.foldLeft[PartialFunction[Any, JObject]](Map()) {
(result, cur) => result.orElse(cur.serialize)
}
}
}
private[json] object ClassDelta {
def delta(class1: Class[_], class2: Class[_]): Int = {
if (class1 == class2) 0
else if (class1.getInterfaces.contains(class2)) 0
else if (class2.getInterfaces.contains(class1)) 0
else if (class1.isAssignableFrom(class2)) {
1 + delta(class1, class2.getSuperclass)
}
else if (class2.isAssignableFrom(class1)) {
1 + delta(class1.getSuperclass, class2)
}
else error("Don't call delta unless one class is assignable from the other")
}
}
/** Do not use any type hints.
*/
case object NoTypeHints extends TypeHints {
val hints = Nil
def hintFor(clazz: Class[_]) = error("NoTypeHints does not provide any type hints.")
def classFor(hint: String) = None
}
/** Use short class name as a type hint.
*/
case class ShortTypeHints(hints: List[Class[_]]) extends TypeHints {
def hintFor(clazz: Class[_]) = clazz.getName.substring(clazz.getName.lastIndexOf(".")+1)
def classFor(hint: String) = hints find (hintFor(_) == hint)
}
/** Use full class name as a type hint.
*/
case class FullTypeHints(hints: List[Class[_]]) extends TypeHints {
def hintFor(clazz: Class[_]) = clazz.getName
def classFor(hint: String) = Some(Thread.currentThread.getContextClassLoader.loadClass(hint))
}
/** Default date format is UTC time.
*/
object DefaultFormats extends DefaultFormats {
val losslessDate = new ThreadLocal(new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"))
val UTC = TimeZone.getTimeZone("UTC")
}
trait DefaultFormats extends Formats {
import java.text.{ParseException, SimpleDateFormat}
val dateFormat = new DateFormat {
def parse(s: String) = try {
Some(formatter.parse(s))
} catch {
case e: ParseException => None
}
def format(d: Date) = formatter.format(d)
private def formatter = {
val f = dateFormatter
f.setTimeZone(DefaultFormats.UTC)
f
}
}
protected def dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
/** Lossless date format includes milliseconds too.
*/
def lossless = new DefaultFormats {
override def dateFormatter = DefaultFormats.losslessDate()
}
/** Default formats with given <code>TypeHint</code>s.
*/
def withHints(hints: TypeHints) = new DefaultFormats {
override val typeHints = hints
}
}
private[json] class ThreadLocal[A](init: => A) extends java.lang.ThreadLocal[A] with (() => A) {
override def initialValue = init
def apply = get
}