Cleanup (formatting)
[idea/community.git] / platform / projectModel-api / src / com / intellij / configurationStore / xmlSerializer.kt
1 // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
2 @file:JvmName("XmlSerializer")
3 package com.intellij.configurationStore
4
5 import com.intellij.openapi.components.BaseState
6 import com.intellij.openapi.components.PersistentStateComponent
7 import com.intellij.util.xmlb.SerializationFilter
8 import com.intellij.util.xmlb.SkipDefaultsSerializationFilter
9 import org.jdom.Element
10 import org.jetbrains.annotations.ApiStatus
11 import java.net.URL
12 import java.util.*
13
14 @ApiStatus.Internal
15 val jdomSerializer: JdomSerializer = ServiceLoader.load(JdomSerializer::class.java, JdomSerializer::class.java.classLoader).first()
16
17 @JvmOverloads
18 fun <T : Any> serialize(obj: T, filter: SerializationFilter? = jdomSerializer.getDefaultSerializationFilter(), createElementIfEmpty: Boolean = false): Element? {
19   return jdomSerializer.serialize(obj, filter, createElementIfEmpty)
20 }
21
22 inline fun <reified T: Any> deserialize(element: Element): T = jdomSerializer.deserialize(element, T::class.java)
23
24 fun <T> Element.deserialize(clazz: Class<T>): T = jdomSerializer.deserialize(this, clazz)
25
26 fun Element.deserializeInto(bean: Any) {
27   jdomSerializer.deserializeInto(bean, this)
28 }
29
30 @JvmOverloads
31 fun <T> deserializeAndLoadState(component: PersistentStateComponent<T>, element: Element, clazz: Class<T> = ComponentSerializationUtil.getStateClass(component::class.java)) {
32   val state = jdomSerializer.deserialize(element, clazz)
33   (state as? BaseState)?.resetModificationCount()
34   component.loadState(state)
35 }
36
37 @JvmOverloads
38 fun serializeObjectInto(o: Any, target: Element, filter: SerializationFilter? = null) {
39   jdomSerializer.serializeObjectInto(o, target, filter)
40 }
41
42 fun serializeStateInto(component: PersistentStateComponent<*>, element: Element) {
43   component.state?.let {
44     jdomSerializer.serializeObjectInto(it, element)
45   }
46 }
47
48 @ApiStatus.Internal
49 interface JdomSerializer {
50   fun <T : Any> serialize(obj: T, filter: SerializationFilter?, createElementIfEmpty: Boolean = false): Element?
51
52   fun serializeObjectInto(obj: Any, target: Element, filter: SerializationFilter? = null)
53
54   fun <T> deserialize(element: Element, clazz: Class<T>): T
55
56   fun deserializeInto(obj: Any, element: Element)
57
58   fun <T> deserialize(url: URL, aClass: Class<T>): T
59
60   @ApiStatus.Internal
61   fun getDefaultSerializationFilter(): SkipDefaultsSerializationFilter
62
63   fun clearSerializationCaches()
64 }