-
Notifications
You must be signed in to change notification settings - Fork 73
/
KMongoUtil.kt
334 lines (305 loc) · 13 KB
/
KMongoUtil.kt
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
/*
* Copyright (C) 2016/2022 Litote
*
* 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 org.litote.kmongo.util
import com.mongodb.DBObjectCodecProvider
import com.mongodb.DBRefCodecProvider
import com.mongodb.DocumentToDBRefTransformer
import com.mongodb.client.gridfs.codecs.GridFSFileCodecProvider
import com.mongodb.client.model.BsonField
import com.mongodb.client.model.DeleteManyModel
import com.mongodb.client.model.DeleteOneModel
import com.mongodb.client.model.Filters
import com.mongodb.client.model.InsertOneModel
import com.mongodb.client.model.ReplaceOneModel
import com.mongodb.client.model.ReplaceOptions
import com.mongodb.client.model.UpdateManyModel
import com.mongodb.client.model.UpdateOneModel
import com.mongodb.client.model.UpdateOptions
import com.mongodb.client.model.WriteModel
import com.mongodb.client.model.geojson.codecs.GeoJsonCodecProvider
import org.bson.BsonBoolean
import org.bson.BsonDocument
import org.bson.BsonDocumentWriter
import org.bson.BsonDouble
import org.bson.BsonInt32
import org.bson.BsonInt64
import org.bson.BsonObjectId
import org.bson.BsonString
import org.bson.BsonValue
import org.bson.Document
import org.bson.codecs.BsonArrayCodec
import org.bson.codecs.BsonCodecProvider
import org.bson.codecs.BsonValueCodecProvider
import org.bson.codecs.DecoderContext
import org.bson.codecs.DocumentCodecProvider
import org.bson.codecs.Encoder
import org.bson.codecs.EncoderContext
import org.bson.codecs.IterableCodecProvider
import org.bson.codecs.JsonObjectCodecProvider
import org.bson.codecs.MapCodecProvider
import org.bson.codecs.ValueCodecProvider
import org.bson.codecs.configuration.CodecRegistries
import org.bson.codecs.configuration.CodecRegistry
import org.bson.codecs.jsr310.Jsr310CodecProvider
import org.bson.conversions.Bson
import org.bson.json.JsonReader
import org.bson.types.ObjectId
import org.litote.kmongo.Id
import org.litote.kmongo.MongoOperator.addToSet
import org.litote.kmongo.MongoOperator.bit
import org.litote.kmongo.MongoOperator.currentDate
import org.litote.kmongo.MongoOperator.group
import org.litote.kmongo.MongoOperator.inc
import org.litote.kmongo.MongoOperator.max
import org.litote.kmongo.MongoOperator.min
import org.litote.kmongo.MongoOperator.mul
import org.litote.kmongo.MongoOperator.pop
import org.litote.kmongo.MongoOperator.pull
import org.litote.kmongo.MongoOperator.pullAll
import org.litote.kmongo.MongoOperator.push
import org.litote.kmongo.MongoOperator.rename
import org.litote.kmongo.MongoOperator.set
import org.litote.kmongo.MongoOperator.setOnInsert
import org.litote.kmongo.MongoOperator.unset
import org.litote.kmongo.id.IdGenerator
import org.litote.kmongo.id.StringId
import org.litote.kmongo.id.WrappedObjectId
import org.litote.kmongo.service.ClassMappingType
import java.util.regex.Matcher
import java.util.regex.Pattern
import kotlin.LazyThreadSafetyMode.PUBLICATION
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
import kotlin.reflect.full.isSubclassOf
/**
* Internal utility methods
*/
object KMongoUtil {
const val EMPTY_JSON: String = "{}"
private val SPACE_REPLACE_PATTERN = Pattern.compile("\\\$\\s+")
private val QUOTE_REPLACE_MATCHER = Matcher.quoteReplacement("\$")
private val UPDATE_OPERATORS =
listOf(
inc, mul, rename, setOnInsert, set, unset, min, max, currentDate,
addToSet, pop, pull, push, pullAll,
bit
).map { it.toString() }
private val internalDefaultRegistry: CodecRegistry by lazy(PUBLICATION) {
ClassMappingType.codecRegistry(defaultCodecRegistry)
}
val defaultCodecRegistry: CodecRegistry by lazy(PUBLICATION) {
CodecRegistries.fromProviders(
listOf(
ValueCodecProvider(),
BsonValueCodecProvider(),
DBRefCodecProvider(),
DBObjectCodecProvider(),
DocumentCodecProvider(DocumentToDBRefTransformer()),
IterableCodecProvider(DocumentToDBRefTransformer()),
MapCodecProvider(DocumentToDBRefTransformer()),
GeoJsonCodecProvider(),
GridFSFileCodecProvider(),
Jsr310CodecProvider(),
JsonObjectCodecProvider(),
BsonCodecProvider()
)
)
}
fun generateNewIdForIdClass(idClass: KClass<out Any>): Any =
when {
idClass == ObjectId::class -> ObjectId.get()
idClass == String::class -> ObjectId.get().toString()
idClass == WrappedObjectId::class -> WrappedObjectId<Any>(ObjectId.get())
idClass == StringId::class -> StringId<Any>(ObjectId.get().toString())
idClass.isSubclassOf(Id::class) -> IdGenerator.defaultGenerator.generateNewId<Any>()
else -> {
error("generation for id property type not supported : $idClass")
}
}
fun toBson(json: String): BsonDocument = if (json == EMPTY_JSON) BsonDocument() else BsonDocument.parse(json)
fun <T : Any> toBson(json: String, type: KClass<T>): BsonDocument =
generateIfAbsentAndMayBeMoveId(toBson(json), type)
private fun <T : Any> generateIfAbsentAndMayBeMoveId(document: BsonDocument, type: KClass<T>): BsonDocument {
if (!document.containsKey("_id")) {
val idProperty = ClassMappingType.findIdProperty(type)
if (idProperty != null) {
val idValue = document.get(idProperty.name)
if (idValue == null) {
val toString = idProperty.returnType.toString()
if (toString.startsWith(ObjectId::class.qualifiedName!!)) {
document.put("_id", BsonObjectId(ObjectId.get()))
} else if (toString.startsWith(String::class.qualifiedName!!)) {
document.put("_id", BsonString(ObjectId.get().toString()))
} else {
error("generation for id property type not supported : $idProperty")
}
} else {
document.put("_id", idValue)
}
if (idProperty.name != "_id") {
document.remove(idProperty.name)
}
}
}
return document
}
fun toBsonList(json: Array<out String>, codecRegistry: CodecRegistry): List<Bson> =
if (json.size == 1 && isJsonArray(json[0])) {
BsonArrayCodec(codecRegistry).decode(JsonReader(json[0]), DecoderContext.builder().build())
.map { it as BsonDocument }
} else {
json.map { toBson(it) }
}
fun filterIdToBson(
obj: Any,
filterNullProperties: Boolean = !ObjectMappingConfiguration.serializeNull
): BsonDocument =
ClassMappingType.filterIdToBson(obj, filterNullProperties)
fun formatJson(json: String): String {
return SPACE_REPLACE_PATTERN.matcher(json).replaceAll(QUOTE_REPLACE_MATCHER)
}
fun toExtendedJson(obj: Any): String =
if (obj is Bson) {
obj.toBsonDocument(
Document::class.java,
internalDefaultRegistry
).toJson()
} else {
ClassMappingType.toExtendedJson(obj)
}
private fun isJsonArray(json: String) = json.trim().startsWith('[')
fun idFilterQuery(id: Any): Bson = Filters.eq("_id", id)
private fun containsUpdateOperator(map: Map<*, *>): Boolean = UPDATE_OPERATORS.any { map.contains(it) }
fun toBsonModifier(obj: Any, updateOnlyNotNullProperties: Boolean = false): Bson =
when (obj) {
is Bson -> obj
is BsonField -> error("BsonField must be used only for $group operations")
is String -> toBson(obj)
else -> setModifier(obj, updateOnlyNotNullProperties)
}
fun setModifier(obj: Any, updateOnlyNotNullProperties: Boolean = false): Bson {
return if (obj is Map<*, *> && containsUpdateOperator(obj)) {
toBson(toExtendedJson(obj))
} else {
SimpleExpression("$set", filterIdToBson(obj, updateOnlyNotNullProperties))
}
}
fun extractId(obj: Any, clazz: KClass<*>): Any {
//check map
if (obj is Map<*, *>) {
return obj["_id"] ?: error("_id is null")
}
val idProperty = ClassMappingType.findIdProperty(clazz)
if (idProperty == null) {
throw IllegalArgumentException("$obj has to contain _id field")
} else {
@Suppress("UNCHECKED_CAST")
return ClassMappingType.getIdValue(idProperty as KProperty1<Any, Any>, obj) ?: error("id is null")
}
}
fun <T : Any> toWriteModel(
json: Array<out String>,
codecRegistry: CodecRegistry,
type: KClass<T>
): List<WriteModel<BsonDocument>> =
if (json.size == 1 && isJsonArray(json[0])) {
BsonArrayCodec(codecRegistry).decode(JsonReader(json[0]), DecoderContext.builder().build())
.map { toWriteModel(it as BsonDocument, type) }
} else {
json.map { toWriteModel(toBson(it), type) }
}
private fun <T : Any> toWriteModel(bson: BsonDocument, type: KClass<T>): WriteModel<BsonDocument> {
if (bson.containsKey("insertOne")) {
return InsertOneModel(generateIfAbsentAndMayBeMoveId(bson.getDocument("insertOne"), type))
} else if (bson.containsKey("updateOne")) {
val updateOne = bson.getDocument("updateOne")
return UpdateOneModel(
updateOne.getDocument("filter"),
updateOne.getDocument("update"),
UpdateOptions().upsert(updateOne.getBoolean("upsert", BsonBoolean.FALSE).value)
)
} else if (bson.containsKey("updateMany")) {
val updateMany = bson.getDocument("updateMany")
return UpdateManyModel(
updateMany.getDocument("filter"),
updateMany.getDocument("update"),
UpdateOptions().upsert(updateMany.getBoolean("upsert", BsonBoolean.FALSE).value)
)
} else if (bson.containsKey("replaceOne")) {
val replaceOne = bson.getDocument("replaceOne")
return ReplaceOneModel(
replaceOne.getDocument("filter"),
replaceOne.getDocument("replacement"),
ReplaceOptions().upsert(replaceOne.getBoolean("upsert", BsonBoolean.FALSE).value)
)
} else if (bson.containsKey("deleteOne")) {
val deleteOne = bson.getDocument("deleteOne")
return DeleteOneModel(
deleteOne.getDocument("filter")
)
} else if (bson.containsKey("deleteMany")) {
val deleteMany = bson.getDocument("deleteMany")
return DeleteManyModel(
deleteMany.getDocument("filter")
)
} else {
throw IllegalArgumentException("unknown write model : $bson")
}
}
fun defaultCollectionName(clazz: KClass<*>): String =
CollectionNameFormatter.defaultCollectionNameBuilder.invoke(clazz)
fun getIdValue(value: Any): Any? {
//check map
if (value is Map<*, *>) {
return value["_id"]
}
val idProperty = ClassMappingType.findIdProperty(value.javaClass.kotlin)
@Suppress("UNCHECKED_CAST")
return if (idProperty == null) null else ClassMappingType.getIdValue(
idProperty as KProperty1<Any, Any>,
value
)
}
fun <TItem : Any> encodeValue(writer: BsonDocumentWriter, value: TItem?, codecRegistry: CodecRegistry) {
when (value) {
null -> writer.writeNull()
is Bson -> @Suppress("UNCHECKED_CAST")
(codecRegistry.get(BsonDocument::class.java) as Encoder<Any>).encode(
writer,
value.toBsonDocument(BsonDocument::class.java, codecRegistry),
EncoderContext.builder().build()
)
else -> @Suppress("UNCHECKED_CAST")
(codecRegistry.get<TItem>(value::class.java as Class<TItem>) as Encoder<TItem>).encode(
writer,
value,
EncoderContext.builder().build()
)
}
}
fun getIdBsonValue(idValue: Any?): BsonValue? {
return when (idValue) {
null -> null
is ObjectId -> BsonObjectId(idValue)
is String -> BsonString(idValue)
is Double -> BsonDouble(idValue)
is Int -> BsonInt32(idValue)
is Long -> BsonInt64(idValue)
//TODO direct mapping
else -> toBson(toExtendedJson(idValue))
}
}
}