-
Notifications
You must be signed in to change notification settings - Fork 2
/
ScalaDtoQuerease.scala
297 lines (278 loc) · 11.6 KB
/
ScalaDtoQuerease.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
package org.mojoz.querease
import scala.collection.immutable.{TreeMap, Seq}
import scala.language.existentials
import scala.language.implicitConversions
import scala.language.postfixOps
import scala.reflect.ManifestFactory
import scala.util.Try
import java.util.concurrent.ConcurrentHashMap
import org.mojoz.metadata.{FieldDef, ViewDef}
import org.tresql.Column
import org.tresql.CoreTypes
import org.tresql.RowLike
class ScalaDtoQuereaseIo[-DTO <: Dto](qe: QuereaseMetadata with QuereaseResolvers) extends QuereaseIo[DTO] {
override def convertRow[B <: DTO](row: RowLike)(implicit mf: Manifest[B]): B =
rowLikeToDto(row, mf)
override def toMap[B <: DTO](dto: B): Map[String, Any] =
dto.toMap(qe)
//org.tresql.Converter[T]
implicit def rowLikeToDto[B <: DTO](r: RowLike, m: Manifest[B]): B =
m.runtimeClass.getDeclaredConstructor().newInstance().asInstanceOf[B].fill(r)(qe)
}
case class DtoSetter(
name: String,
method: java.lang.reflect.Method,
mfOpt: Manifest[_ <: Option[_]],
mfSeq: Manifest[_ <: Seq[_]],
mfDto: Manifest[_ <: Dto],
mfOth: Manifest[_],
)
private[querease] object DtoReflection {
private val cache =
new ConcurrentHashMap[Class[_ <: Dto], Map[String, DtoSetter]]
def manifest(name: String, dto: Dto, clazz: Class[_]): DtoSetter = {
def mOpt(clazz: Class[_]): Manifest[_ <: Option[_]] = {
if (classOf[Option[_]].isAssignableFrom(clazz))
ManifestFactory.classType(clazz)
else null
}
def mSeq(clazz: Class[_]): Manifest[_ <: Seq[_]] = {
if (classOf[Seq[_]].isAssignableFrom(clazz) && clazz.isAssignableFrom(classOf[List[_]]))
ManifestFactory.classType(clazz)
else null
}
def mDto(clazz: Class[_]): Manifest[_ <: Dto] = {
if (classOf[Dto].isAssignableFrom(clazz))
ManifestFactory.classType(clazz)
else null
}
def mOth(clazz: Class[_]): Manifest[_] = {
if (clazz.isPrimitive) clazz match {
case java.lang.Integer.TYPE => ManifestFactory.Int
case java.lang.Long.TYPE => ManifestFactory.Long
case java.lang.Double.TYPE => ManifestFactory.Double
case java.lang.Boolean.TYPE => ManifestFactory.Boolean
} else ManifestFactory.classType(clazz)
}
lazy val childMf =
childManifest(dto.getClass.getMethods.filter(_.getName == name).head.getGenericReturnType)
lazy val grandChildMf =
childManifest(dto.getClass.getMethods.filter(_.getName == name).head.getGenericReturnType, 2)
val mfOpt = mOpt(clazz)
val mfSeq = mfOpt match {
case null => mSeq(clazz)
case mOpt => mSeq(childMf.runtimeClass)
}
val mfDto = (mfOpt, mfSeq) match {
case (null, null) => mDto(clazz)
case (_ , null) => mDto(childMf.runtimeClass)
case (null, _) => mDto(childMf.runtimeClass)
case _ => mDto(grandChildMf.runtimeClass)
}
val mfOth = (mfOpt, mfSeq, mfDto) match {
case (null, null, null) => mOth(clazz)
case (_, null, null) => mOth(childMf.runtimeClass)
case (null, _, null) => mOth(childMf.runtimeClass)
case (_, _, null) => mOth(grandChildMf.runtimeClass)
case _ => null
}
DtoSetter(name, null, mfOpt, mfSeq, mfDto, mfOth)
}
def childManifest(t: java.lang.reflect.Type, depth: Int = 1): Manifest[_] = {
val parametrisedType = t.asInstanceOf[java.lang.reflect.ParameterizedType]
depth match {
case 1 =>
val clazz = parametrisedType.getActualTypeArguments()(0) match {
case c: Class[_] => c
case p: java.lang.reflect.ParameterizedType =>
p.getRawType.asInstanceOf[Class[_]]
case v: java.lang.reflect.TypeVariable[_] =>
v.getGenericDeclaration.asInstanceOf[Class[_]]
}
ManifestFactory.classType(clazz)
case 2 =>
parametrisedType.getActualTypeArguments()(0) match {
case p: java.lang.reflect.ParameterizedType =>
p.getActualTypeArguments()(0) match {
case cc: Class[_] => ManifestFactory.classType(cc)
}
}
}
}
def setters(dto: Dto): Map[String, DtoSetter] = {
val dtoClass = dto.getClass
cache.getOrDefault(dtoClass, {
val setters =
(for (
m <- dtoClass.getMethods
if m.getName.endsWith("_$eq") &&
!java.lang.reflect.Modifier.isFinal(m.getModifiers) &&
m.getParameterTypes.length == 1
) yield {
val name = m.getName.dropRight(4)
name -> manifest(name, dto, m.getParameterTypes()(0)).copy(method = m)
}).toMap
cache.putIfAbsent(dtoClass, setters)
setters
})
}
}
trait Dto { self =>
protected type QDto >: Null <: Dto
// populate from RowLike
def fill(r: RowLike)(implicit qe: QuereaseMetadata): this.type = {
for (i <- 0 until r.columnCount) r.column(i) match {
case c if c.name != null => set(c.name, c.isResult, r)
case _ =>
}
this
}
protected def setters = DtoReflection.setters(this)
protected def set(dbName: String, isResult: Boolean, r: RowLike)(implicit qe: QuereaseMetadata) =
(for (s <- setters.get(dbToPropName(dbName))) yield {
//declare local converter
def conv[A <: QDto]: CoreTypes.Converter[A] =
(r, m) => m.runtimeClass.getDeclaredConstructor().newInstance().asInstanceOf[A].fill(r)
val value =
(s.mfSeq, s.mfDto) match {
case (null, null) =>
r.typed(dbName)(s.mfOth).asInstanceOf[Object]
case (null, mDto) =>
val childResult = r.result(dbName)
childResult.list[QDto](mDto.asInstanceOf[Manifest[QDto]], conv).headOption.orNull.asInstanceOf[Object]
case (mSeq, null) =>
if (isResult)
r.result(dbName).map(_.typed(0)(s.mfOth)).toList.asInstanceOf[Object]
else
r(dbName) match {
case arr: java.sql.Array =>
import org.tresql._
import org.tresql.given
val tresqlResult: Result[RowLike] = arr.getResultSet
val value = tresqlResult.map(_.typed(1)(s.mfOth)).toList.asInstanceOf[Object]
arr.free()
value
case x =>
List(r.typed(dbName)(s.mfOth)).asInstanceOf[Object]
}
case (mSeq, mDto) =>
val childrenResult = r.result(dbName)
childrenResult.list[QDto](mDto.asInstanceOf[Manifest[QDto]], conv).asInstanceOf[Object]
}
if (s.mfOpt == null)
s.method.invoke(this, value)
else s.method invoke(this, Some(value))
s /*return setter used*/
}) getOrElse {
setExtras(dbName, r)
}
protected def setExtras(dbName: String, r: RowLike)(implicit qe: QuereaseMetadata): AnyRef = {
// Exception disabled because DynamicResult leaks synthetic helper columns - ignoring unknown columns
// throw new RuntimeException(s"Setter for '$dbName' not found")
null: AnyRef
}
protected def dbToPropName(name: String) = name // .toLowerCase
protected def propToDbName(name: String) = name
protected def manifest(name: String, clazz: Class[_]) =
DtoReflection.manifest(name, this, clazz)
protected def childManifest(t: java.lang.reflect.Type, depth: Int = 1): Manifest[_] = {
DtoReflection.childManifest(t, depth)
}
def toUnorderedMap(implicit qe: QuereaseMetadata): Map[String, Any] = setters.map { m =>
val propName = m._1
val propValue = getClass.getMethod(propName).invoke(this) match {
case s: Seq[_] => s.map {
case dto: Dto => dto.asInstanceOf[QDto].toMap
case x => x
}
case c: Dto => c.asInstanceOf[QDto].toMap
case Some(x) => x match {
case s: Seq[_] => s.map {
case dto: Dto => dto.asInstanceOf[QDto].toMap
case x => x
}
case c: Dto => c.asInstanceOf[QDto].toMap
case x => x
}
case x => x
}
propName -> propValue
}.filter(_._2 != None)
def toMap(implicit qe: QuereaseMetadata): Map[String, Any] =
qe.fieldOrderingOptionFromMf(ManifestFactory.classType(getClass))
.map(toMapWithOrdering).getOrElse(toUnorderedMap)
def toMapWithOrdering(fieldOrdering: Ordering[String])(implicit qe: QuereaseMetadata): Map[String, Any] =
TreeMap[String, Any]()(fieldOrdering) ++ toUnorderedMap
def containsField(fieldName: String) = setters.contains(fieldName)
def toString(implicit qe: QuereaseMetadata): String = {
val view = qe.viewDefFromMf(ManifestFactory.classType(getClass))
val fieldNames = view.fields.map(_.fieldName)
toString(fieldNames)
}
protected def toString(fieldNames: Seq[String])(implicit qe: QuereaseMetadata): String = {
def isMisleading(s: String) =
s.contains(" ") || s == "null" || s == "" || s(0).isDigit
val kv: Seq[(String, Object)] = fieldNames.map { name =>
getClass.getMethod(name).invoke(this) match {
case s: Seq[_] => name ->
("(" + (s map {
case s: String => "\"" + s + "\""
case d: Dto => d.asInstanceOf[QDto].toString
case o => o.toString
}).mkString(", ") + ")")
case s: String if isMisleading(s) => name -> ("\"" + s + "\"")
case d: Dto => name -> d.asInstanceOf[QDto].toString
case x => name -> x
}
}
s"${getClass.getName}{${kv.map(kv => kv._1 + ": " + kv._2).mkString(", ")}}"
}
protected def throwUnsupportedConversion(
value: Any, targetType: Manifest[_], fieldName: String, cause: Throwable = null): Unit = {
throw new RuntimeException(
s"Illegal value or unsupported type conversion from ${value.getClass.getName}" +
s" to ${targetType.toString} - failed to populate ${getClass.getName}.$fieldName", cause)
}
//creating dto from Map[String, Any]
def fill(values: Map[String, Any])(implicit qe: QuereaseMetadata): this.type = fill(values, emptyStringsToNull = true)(qe)
def fill(values: Map[String, Any], emptyStringsToNull: Boolean)(implicit qe: QuereaseMetadata): this.type = {
values foreach { case (name, value) =>
setters.get(name).map { case DtoSetter(_, met, mOpt, mSeq, mDto, mOth) =>
val converted = value match {
case s: String if emptyStringsToNull && s.trim == "" => null
case m: Map[String@unchecked, _] =>
if (mSeq == null && mDto != null)
mDto.runtimeClass.getConstructor().newInstance().asInstanceOf[QDto].fill(m, emptyStringsToNull)
else
throwUnsupportedConversion(value, Option(mSeq).getOrElse(mOth), name)
case s: Seq[_] =>
if (mSeq != null) {
val c = mSeq.runtimeClass
val isList = c.isAssignableFrom(classOf[List[_]])
val isVector = c.isAssignableFrom(classOf[Vector[_]])
if (classOf[Seq[_]].isAssignableFrom(c) && (isList || isVector) && mDto != null) {
val chClass = mDto.runtimeClass
val res =
s.map(o => chClass.getConstructor().newInstance().asInstanceOf[QDto]
.fill(o.asInstanceOf[Map[String, Any]], emptyStringsToNull))
if (isList) res.toList else res
} else s
} else
throwUnsupportedConversion(value, Option(mDto).getOrElse(mOth), name)
case x => x
}
val convertedObj =
if (mOpt == null) converted else Some(converted)
try met.invoke(this, convertedObj.asInstanceOf[Object]) catch {
case util.control.NonFatal(ex) =>
throwUnsupportedConversion(value, Seq(mSeq, mDto, mOth).filter(_ != null).head, name)
}
}
}
this
}
}
trait DtoWithId extends Dto {
def id: java.lang.Long
def id_=(id: java.lang.Long): Unit
}