diff --git a/.idea/libraries/assertJ.xml b/.idea/libraries/assertJ.xml new file mode 100644 index 000000000000..aba65818e34c --- /dev/null +++ b/.idea/libraries/assertJ.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/dev/assertj-core-2.1.0-javadoc.jar b/lib/dev/assertj-core-2.1.0-javadoc.jar new file mode 100644 index 000000000000..1494765c49f9 Binary files /dev/null and b/lib/dev/assertj-core-2.1.0-javadoc.jar differ diff --git a/lib/dev/assertj-core-2.1.0-sources.jar b/lib/dev/assertj-core-2.1.0-sources.jar new file mode 100644 index 000000000000..2de88ef396ee Binary files /dev/null and b/lib/dev/assertj-core-2.1.0-sources.jar differ diff --git a/lib/dev/assertj-core-2.1.0.jar b/lib/dev/assertj-core-2.1.0.jar new file mode 100644 index 000000000000..a3cf390f3ad7 Binary files /dev/null and b/lib/dev/assertj-core-2.1.0.jar differ diff --git a/lib/dev/assertj-guava-2.0.0-javadoc.jar b/lib/dev/assertj-guava-2.0.0-javadoc.jar new file mode 100644 index 000000000000..181229c44ace Binary files /dev/null and b/lib/dev/assertj-guava-2.0.0-javadoc.jar differ diff --git a/lib/dev/assertj-guava-2.0.0-sources.jar b/lib/dev/assertj-guava-2.0.0-sources.jar new file mode 100644 index 000000000000..1361dbfeadae Binary files /dev/null and b/lib/dev/assertj-guava-2.0.0-sources.jar differ diff --git a/lib/dev/assertj-guava-2.0.0.jar b/lib/dev/assertj-guava-2.0.0.jar new file mode 100644 index 000000000000..ebd86f013691 Binary files /dev/null and b/lib/dev/assertj-guava-2.0.0.jar differ diff --git a/lib/dev/hamcrest-junit-2.0.0.0-javadoc.jar b/lib/dev/hamcrest-junit-2.0.0.0-javadoc.jar deleted file mode 100644 index 054d64049fc5..000000000000 Binary files a/lib/dev/hamcrest-junit-2.0.0.0-javadoc.jar and /dev/null differ diff --git a/lib/dev/hamcrest-junit-2.0.0.0-sources.jar b/lib/dev/hamcrest-junit-2.0.0.0-sources.jar deleted file mode 100644 index 527776c732b6..000000000000 Binary files a/lib/dev/hamcrest-junit-2.0.0.0-sources.jar and /dev/null differ diff --git a/lib/dev/hamcrest-junit-2.0.0.0.jar b/lib/dev/hamcrest-junit-2.0.0.0.jar deleted file mode 100644 index 3585300bc814..000000000000 Binary files a/lib/dev/hamcrest-junit-2.0.0.0.jar and /dev/null differ diff --git a/lib/dev/java-hamcrest-2.0.0.0-javadoc.jar b/lib/dev/java-hamcrest-2.0.0.0-javadoc.jar deleted file mode 100644 index 962248eaa16d..000000000000 Binary files a/lib/dev/java-hamcrest-2.0.0.0-javadoc.jar and /dev/null differ diff --git a/lib/dev/java-hamcrest-2.0.0.0-sources.jar b/lib/dev/java-hamcrest-2.0.0.0-sources.jar deleted file mode 100644 index b32eeb734648..000000000000 Binary files a/lib/dev/java-hamcrest-2.0.0.0-sources.jar and /dev/null differ diff --git a/lib/dev/java-hamcrest-2.0.0.0.jar b/lib/dev/java-hamcrest-2.0.0.0.jar deleted file mode 100644 index 7310af1b3a41..000000000000 Binary files a/lib/dev/java-hamcrest-2.0.0.0.jar and /dev/null differ diff --git a/platform/configuration-store-impl/configuration-store-impl.iml b/platform/configuration-store-impl/configuration-store-impl.iml index 0701429b8c4d..b5409cccb90a 100644 --- a/platform/configuration-store-impl/configuration-store-impl.iml +++ b/platform/configuration-store-impl/configuration-store-impl.iml @@ -13,7 +13,7 @@ - + diff --git a/platform/configuration-store-impl/testSrc/ModuleStoreRenameTest.kt b/platform/configuration-store-impl/testSrc/ModuleStoreRenameTest.kt index 371ff8c9fa09..58a1fe73b39e 100644 --- a/platform/configuration-store-impl/testSrc/ModuleStoreRenameTest.kt +++ b/platform/configuration-store-impl/testSrc/ModuleStoreRenameTest.kt @@ -21,11 +21,7 @@ import com.intellij.testFramework.fixtures.ModuleFixture import com.intellij.testFramework.runInEdtAndWait import com.intellij.util.Function import com.intellij.util.SmartList -import org.hamcrest.CoreMatchers.equalTo -import org.hamcrest.CoreMatchers.not -import org.hamcrest.MatcherAssert.assertThat -import org.hamcrest.collection.IsEmptyCollection.empty -import org.hamcrest.io.FileMatchers.anExistingFile +import org.assertj.core.api.Assertions.assertThat import org.junit.Rule import org.junit.Test import org.junit.rules.ExternalResource @@ -61,8 +57,7 @@ class ModuleStoreRenameTest { override fun before() { module.getMessageBus().connect().subscribe(ProjectTopics.MODULES, object : ModuleAdapter() { override fun modulesRenamed(project: Project, modules: MutableList, oldNameProvider: Function) { - assertThat(modules.size(), equalTo(1)) - assertThat(modules.get(0), equalTo(module)) + assertThat(modules).containsOnly(module) oldModuleNames.add(oldNameProvider.`fun`(module)) } }) @@ -87,13 +82,13 @@ class ModuleStoreRenameTest { runInEdtAndWait { module.saveStore() } val storage = module.stateStore.getStateStorageManager().getStateStorage(StoragePathMacros.MODULE_FILE, RoamingType.PER_USER) as FileBasedStorage val oldFile = storage.getFile() - assertThat(oldFile, anExistingFile()) + assertThat(oldFile).isFile() val oldName = module.getName() val newName = "foo" module.change { renameModule(module, newName) } assertRename(newName, oldFile) - assertThat(oldModuleNames, equalTo(listOf(oldName))) + assertThat(oldModuleNames).containsOnly(oldName) } // project view @@ -101,13 +96,13 @@ class ModuleStoreRenameTest { runInEdtAndWait { module.saveStore() } var storage = module.stateStore.getStateStorageManager().getStateStorage(StoragePathMacros.MODULE_FILE, RoamingType.PER_USER) as FileBasedStorage val oldFile = storage.getFile() - assertThat(oldFile, anExistingFile()) + assertThat(oldFile).isFile() val oldName = module.getName() val newName = "foo" runInEdtAndWait { runWriteAction { LocalFileSystem.getInstance().refreshAndFindFileByIoFile(oldFile)!!.rename(null, "$newName${ModuleFileType.DOT_DEFAULT_EXTENSION}") } } assertRename(newName, oldFile) - assertThat(oldModuleNames, equalTo(listOf(oldName))) + assertThat(oldModuleNames).containsOnly(oldName) } // we cannot test external rename yet, because it is not supported - ModuleImpl doesn't support delete and create events (in case of external change we don't get move event, but get "delete old" and "create new") @@ -115,13 +110,14 @@ class ModuleStoreRenameTest { private fun assertRename(newName: String, oldFile: File) { val storageManager = moduleFixture.getModule().stateStore.getStateStorageManager() val newFile = (storageManager.getStateStorage(StoragePathMacros.MODULE_FILE, RoamingType.PER_USER) as FileBasedStorage).getFile() - assertThat(newFile.getName(), equalTo("$newName${ModuleFileType.DOT_DEFAULT_EXTENSION}")) - assertThat(oldFile, not(anExistingFile())) - assertThat(oldFile, not(equalTo(newFile))) - assertThat(newFile, anExistingFile()) + assertThat(newFile.getName()).isEqualTo("$newName${ModuleFileType.DOT_DEFAULT_EXTENSION}") + assertThat(oldFile) + .doesNotExist() + .isNotEqualTo(newFile) + assertThat(newFile).isFile() // ensure that macro value updated - assertThat(storageManager.expandMacros(StoragePathMacros.MODULE_FILE), equalTo(newFile.systemIndependentPath)) + assertThat(storageManager.expandMacros(StoragePathMacros.MODULE_FILE)).isEqualTo(newFile.systemIndependentPath) } public Test fun `rename module parent virtual dir`() { @@ -135,9 +131,9 @@ class ModuleStoreRenameTest { val newFile = File(parentVirtualDir.getPath(), module.getName() + ModuleFileType.DOT_DEFAULT_EXTENSION) try { - assertThat(newFile, anExistingFile()) + assertThat(newFile).isFile() assertRename(module.getName(), oldFile) - assertThat(oldModuleNames, empty()) + assertThat(oldModuleNames).isEmpty() } finally { runInEdtAndWait { runWriteAction { parentVirtualDir.delete(this) } } diff --git a/platform/configuration-store-impl/testSrc/ModuleStoreTest.kt b/platform/configuration-store-impl/testSrc/ModuleStoreTest.kt index 5a32d3eac2f8..42e10e2594dc 100644 --- a/platform/configuration-store-impl/testSrc/ModuleStoreTest.kt +++ b/platform/configuration-store-impl/testSrc/ModuleStoreTest.kt @@ -13,10 +13,7 @@ import com.intellij.openapi.util.io.parentSystemIndependentPath import com.intellij.openapi.util.io.systemIndependentPath import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.* -import org.hamcrest.CoreMatchers.equalTo -import org.hamcrest.MatcherAssert.assertThat -import org.hamcrest.core.StringStartsWith.startsWith -import org.hamcrest.io.FileMatchers.anExistingFile +import org.assertj.core.api.Assertions.assertThat import org.junit.ClassRule import org.junit.Rule import org.junit.Test @@ -56,18 +53,17 @@ import java.io.File projectRule.project.runInStoreLoadMode { moduleFile.loadModule().useAndDispose { - assertThat(getOptionValue("foo"), equalTo("bar")) + assertThat(getOptionValue("foo")).isEqualTo("bar") setOption("foo", "not bar") saveStore() } moduleFile.loadModule().useAndDispose { - assertThat(getOptionValue("foo"), equalTo("not bar")) + assertThat(getOptionValue("foo")).isEqualTo("not bar") setOption("foo", "not bar") saveStore() - } } } @@ -79,13 +75,13 @@ import java.io.File moduleFile.createModule().useAndDispose { ModuleRootModificationUtil.addContentRoot(this, moduleFile.parentSystemIndependentPath) saveStore() - assertThat(moduleFile, anExistingFile()) - assertThat(moduleFile.readText(), startsWith("\n")) + assertThat(moduleFile).isFile() + assertThat(moduleFile.readText()).startsWith("\n") ClasspathStorage.setStorageType(ModuleRootManager.getInstance(this), "eclipse") saveStore() - assertThat(moduleFile.readText(), equalTo(""" -""")) + assertThat(moduleFile).hasContent(""" +""") } } } diff --git a/platform/configuration-store-impl/testSrc/ProjectStoreTest.kt b/platform/configuration-store-impl/testSrc/ProjectStoreTest.kt index e8c05625954b..41ef1a3ada2e 100644 --- a/platform/configuration-store-impl/testSrc/ProjectStoreTest.kt +++ b/platform/configuration-store-impl/testSrc/ProjectStoreTest.kt @@ -28,10 +28,7 @@ import com.intellij.testFramework.ProjectRule import com.intellij.testFramework.RuleChain import com.intellij.testFramework.TemporaryDirectory import com.intellij.testFramework.runInEdtAndWait -import org.hamcrest.CoreMatchers.equalTo -import org.hamcrest.MatcherAssert.assertThat -import org.hamcrest.core.StringStartsWith.startsWith -import org.hamcrest.io.FileMatchers.anExistingFile +import org.assertj.core.api.Assertions.assertThat import org.intellij.lang.annotations.Language import org.junit.ClassRule import org.junit.Rule @@ -115,7 +112,7 @@ class ProjectStoreTest { project.getBaseDir().refresh(false, true) (ProjectManager.getInstance() as StoreAwareProjectManager).flushChangedAlarm() - assertThat(testComponent.getState(), equalTo(TestState("newValue"))) + assertThat(testComponent.getState()).isEqualTo(TestState("newValue")) } } @@ -128,16 +125,16 @@ class ProjectStoreTest { private fun test(project: Project): TestComponent { val testComponent = TestComponent() project.stateStore.initComponent(testComponent, true) - assertThat(testComponent.getState(), equalTo(TestState("customValue"))) + assertThat(testComponent.getState()).isEqualTo(TestState("customValue")) testComponent.getState()!!.value = "foo" project.saveStore() val file = File(project.stateStore.getStateStorageManager().expandMacros(StoragePathMacros.PROJECT_FILE)) - assertThat(file, anExistingFile()) + assertThat(file).isFile() // test exact string - xml prolog, line separators, indentation and so on must be exactly the same // todo get rid of default component states here - assertThat(file.readText(), startsWith(iprFileContent.replace("customValue", "foo").replace("", ""))) + assertThat(file.readText()).startsWith(iprFileContent.replace("customValue", "foo").replace("", "")) return testComponent } diff --git a/platform/configuration-store-impl/testSrc/SchemeManagerTest.kt b/platform/configuration-store-impl/testSrc/SchemeManagerTest.kt index 5644cc85001b..b40b22d07bb8 100644 --- a/platform/configuration-store-impl/testSrc/SchemeManagerTest.kt +++ b/platform/configuration-store-impl/testSrc/SchemeManagerTest.kt @@ -34,14 +34,7 @@ import com.intellij.util.xmlb.annotations.Attribute import com.intellij.util.xmlb.annotations.Tag import com.intellij.util.xmlb.annotations.Transient import gnu.trove.THashMap -import org.hamcrest.CoreMatchers.equalTo -import org.hamcrest.CoreMatchers.not -import org.hamcrest.CoreMatchers.notNullValue -import org.hamcrest.CoreMatchers.sameInstance -import org.hamcrest.MatcherAssert.assertThat -import org.hamcrest.collection.IsMapContaining.hasKey -import org.hamcrest.io.FileMatchers.anExistingDirectory -import org.hamcrest.io.FileMatchers.anExistingFile +import org.assertj.core.api.Assertions.assertThat import org.jdom.Element import org.junit.ClassRule import org.junit.Rule @@ -90,8 +83,7 @@ class SchemeManagerTest { val manager = createAndLoad("options1") val scheme = manager.findSchemeByName("first") - assertThat(scheme, notNullValue()) - assert(scheme != null) + assertThat(scheme).isNotNull() scheme!!.setName("renamed") manager.save() @@ -102,11 +94,11 @@ class SchemeManagerTest { val manager = createAndLoad("options1") val first = manager.findSchemeByName("first") - assertThat(first, notNullValue()) + assertThat(first).isNotNull() assert(first != null) first!!.setName("2") val second = manager.findSchemeByName("second") - assertThat(second, notNullValue()) + assertThat(second).isNotNull() assert(second != null) second!!.setName("1") manager.save() @@ -118,7 +110,7 @@ class SchemeManagerTest { val manager = createAndLoad("options1") val firstScheme = manager.findSchemeByName("first") - assertThat(firstScheme, notNullValue()) + assertThat(firstScheme).isNotNull() assert(firstScheme != null) firstScheme!!.setName("first_renamed") manager.save() @@ -137,7 +129,7 @@ class SchemeManagerTest { public Test fun testDeleteAndCreateSchemeWithTheSameName() { val manager = createAndLoad("options1") val firstScheme = manager.findSchemeByName("first") - assertThat(firstScheme, notNullValue()) + assertThat(firstScheme).isNotNull() manager.removeScheme(firstScheme!!) manager.addScheme(TestScheme("first")) @@ -150,7 +142,7 @@ class SchemeManagerTest { val scheme = TestScheme("first") manager.addNewScheme(scheme, false) - assertThat("first2", equalTo(scheme.getName())) + assertThat("first2").isEqualTo(scheme.getName()) } fun TestScheme.save(file: File) { @@ -170,43 +162,42 @@ class SchemeManagerTest { override fun getSchemeExtension() = ".icls" }, RoamingType.PER_USER, null, dir) schemesManager.loadSchemes() - assertThat(schemesManager.getAllSchemes(), equalTo(listOf(scheme))) + assertThat(schemesManager.getAllSchemes()).containsOnly(scheme) - assertThat(File(dir, "1.icls"), anExistingFile()) - assertThat(File(dir, "1.xml"), anExistingFile()) + assertThat(File(dir, "1.icls")).isFile() + assertThat(File(dir, "1.xml")).isFile() scheme.data = "newTrue" schemesManager.save() - assertThat(File(dir, "1.icls"), anExistingFile()) - assertThat(File(dir, "1.xml"), not(anExistingFile())) + assertThat(File(dir, "1.icls")).isFile() + assertThat(File(dir, "1.xml")).doesNotExist() } public Test fun setSchemes() { val dir = tempDirManager.newDirectory() val schemeManager = createSchemeManager(dir) schemeManager.loadSchemes() - assertThat(schemeManager.getAllSchemes().isEmpty(), equalTo(true)) + assertThat(schemeManager.getAllSchemes()).isEmpty() val scheme = TestScheme("s1") schemeManager.setSchemes(listOf(scheme)) val schemes = schemeManager.getAllSchemes() - assertThat(schemes.size(), equalTo(1)) - assertThat(schemes.get(0), sameInstance(scheme)) + assertThat(schemes).containsOnly(scheme) - assertThat(File(dir, "s1.xml"), not(anExistingFile())) + assertThat(File(dir, "s1.xml")).doesNotExist() scheme.data = "newTrue" schemeManager.save() - assertThat(File(dir, "s1.xml"), anExistingFile()) + assertThat(File(dir, "s1.xml")).isFile() schemeManager.setSchemes(emptyList()) schemeManager.save() - assertThat(dir, not(anExistingFile())) + assertThat(dir).doesNotExist() } public Test fun `save only if scheme differs from bundled`() { @@ -216,35 +207,31 @@ class SchemeManagerTest { val bundledPath = "/bundledSchemes/default" schemeManager.loadBundledScheme(bundledPath, this, converter) var schemes = schemeManager.getAllSchemes() - assertThat(schemes.size(), equalTo(1)) val customScheme = TestScheme("default") - assertThat(schemes.get(0), equalTo(customScheme)) + assertThat(schemes).containsOnly(customScheme) schemeManager.save() - assertThat(dir, not(anExistingFile())) + assertThat(dir).doesNotExist() schemeManager.save() schemeManager.setSchemes(listOf(customScheme)) - assertThat(dir, not(anExistingFile())) + assertThat(dir).doesNotExist() schemes = schemeManager.getAllSchemes() - assertThat(schemes.size(), equalTo(1)) - assertThat(schemes.get(0), sameInstance(customScheme)) + assertThat(schemes).containsOnly(customScheme) customScheme.data = "foo" schemeManager.save() - val schemeFile = File(dir, "default.xml") - assertThat(schemeFile, anExistingFile()) + assertThat(File(dir, "default.xml")).isFile() schemeManager = createSchemeManager(dir) schemeManager.loadBundledScheme(bundledPath, this, converter) schemeManager.loadSchemes() schemes = schemeManager.getAllSchemes() - assertThat(schemes.get(0), equalTo(customScheme)) + assertThat(schemes).containsOnly(customScheme) } - public Test fun `don't remove dir if no schemes but at least one non-hidden file exists`() { val dir = tempDirManager.newDirectory() val schemeManager = createSchemeManager(dir) @@ -255,7 +242,7 @@ class SchemeManagerTest { schemeManager.save() val schemeFile = File(dir, "s1.xml") - assertThat(schemeFile.exists(), equalTo(true)) + assertThat(schemeFile).isFile() schemeManager.setSchemes(emptyList()) @@ -263,8 +250,8 @@ class SchemeManagerTest { schemeManager.save() - assertThat(schemeFile.exists(), equalTo(false)) - assertThat(dir.exists(), equalTo(true)) + assertThat(schemeFile).doesNotExist() + assertThat(dir).isDirectory() } public Test fun `remove empty directory only if some file was deleted`() { @@ -272,45 +259,44 @@ class SchemeManagerTest { val schemeManager = createSchemeManager(dir) schemeManager.loadSchemes() - assertThat(dir.mkdirs(), equalTo(true)) + assertThat(dir.mkdirs()).isTrue() schemeManager.save() - assertThat(dir, anExistingDirectory()) + assertThat(dir).isDirectory() schemeManager.addScheme(TestScheme("test")) schemeManager.save() - assertThat(dir, anExistingDirectory()) + assertThat(dir).isDirectory() schemeManager.setSchemes(emptyList()) schemeManager.save() - assertThat(dir, not(anExistingDirectory())) + assertThat(dir).doesNotExist() } public Test fun rename() { val dir = tempDirManager.newDirectory() val schemeManager = createSchemeManager(dir) schemeManager.loadSchemes() - assertThat(schemeManager.getAllSchemes().isEmpty(), equalTo(true)) + assertThat(schemeManager.getAllSchemes()).isEmpty() val scheme = TestScheme("s1") schemeManager.setSchemes(listOf(scheme)) val schemes = schemeManager.getAllSchemes() - assertThat(schemes.size(), equalTo(1)) - assertThat(schemes.get(0), sameInstance(scheme)) + assertThat(schemes).containsOnly(scheme) - assertThat(File(dir, "s1.xml").exists(), equalTo(false)) + assertThat(File(dir, "s1.xml")).doesNotExist() scheme.data = "newTrue" schemeManager.save() - assertThat(File(dir, "s1.xml").exists(), equalTo(true)) + assertThat(File(dir, "s1.xml")).isFile() scheme.setName("s2") schemeManager.save() - assertThat(File(dir, "s1.xml").exists(), equalTo(false)) - assertThat(File(dir, "s2.xml").exists(), equalTo(true)) + assertThat(File(dir, "s1.xml")).doesNotExist() + assertThat(File(dir, "s2.xml")).isFile() } public Test fun `path must not contains ROOT_CONFIG macro`() { @@ -369,13 +355,13 @@ private fun checkSchemes(baseDir: File, expected: String, ignoreDeleted: Boolean for (file in files) { val fileName = FileUtil.getNameWithoutExtension(file) if ("--deleted" == fileName && ignoreDeleted) { - assertThat>(fileToSchemeMap, hasKey(fileName)) + assertThat(fileToSchemeMap).containsKey(fileName) } } } for (file in fileToSchemeMap.keySet()) { - assertThat(File(baseDir, "$file.xml").isFile(), equalTo(true)) + assertThat(File(baseDir, "$file.xml")).isFile() } if (files != null) { @@ -383,7 +369,7 @@ private fun checkSchemes(baseDir: File, expected: String, ignoreDeleted: Boolean for (file in files) { val fileName = FileUtil.getNameWithoutExtension(file) val scheme = schemesProcessor.readScheme(JDOMUtil.load(file), true) - assertThat(fileToSchemeMap.get(fileName), equalTo(scheme!!.getName())) + assertThat(fileToSchemeMap.get(fileName)).isEqualTo(scheme!!.getName()) } } } diff --git a/platform/util/src/com/intellij/util/xmlb/XmlSerializerImpl.java b/platform/util/src/com/intellij/util/xmlb/XmlSerializerImpl.java index b82610c350fa..eb766d847869 100644 --- a/platform/util/src/com/intellij/util/xmlb/XmlSerializerImpl.java +++ b/platform/util/src/com/intellij/util/xmlb/XmlSerializerImpl.java @@ -29,6 +29,7 @@ import java.lang.ref.SoftReference; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; +import java.lang.reflect.WildcardType; import java.util.Collection; import java.util.Date; import java.util.List; @@ -88,6 +89,9 @@ class XmlSerializerImpl { Type bound = ((TypeVariable)type).getBounds()[0]; return bound instanceof Class ? (Class)bound : (Class)((ParameterizedType)bound).getRawType(); } + else if (type instanceof WildcardType) { + return (Class)((WildcardType) type).getUpperBounds()[0]; + } else { return (Class)((ParameterizedType)type).getRawType(); } diff --git a/platform/util/testSrc/com/intellij/util/xmlb/XmlSerializerTest.java b/platform/util/testSrc/com/intellij/util/xmlb/XmlSerializerTest.java deleted file mode 100644 index 7e5fe1f646af..000000000000 --- a/platform/util/testSrc/com/intellij/util/xmlb/XmlSerializerTest.java +++ /dev/null @@ -1,1448 +0,0 @@ -/* - * Copyright 2000-2015 JetBrains s.r.o. - * - * 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 com.intellij.util.xmlb; - -import com.intellij.openapi.util.JDOMExternalizableStringList; -import com.intellij.openapi.util.JDOMUtil; -import com.intellij.openapi.util.Ref; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.util.SmartList; -import com.intellij.util.xmlb.annotations.AbstractCollection; -import com.intellij.util.xmlb.annotations.*; -import gnu.trove.THashMap; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; -import org.intellij.lang.annotations.Language; -import org.jdom.Element; -import org.jdom.JDOMException; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.io.IOException; -import java.util.*; -import java.util.concurrent.atomic.AtomicReference; - -/** - * @author mike - */ -public class XmlSerializerTest extends TestCase { - private static final String XML_PREFIX = ""; - - public static class EmptyBean { - } - - public void testEmptyBeanSerialization() { - doSerializerTest("", new EmptyBean()); - } - - @Tag("Bean") - public static class EmptyBeanWithCustomName { - } - - public void testEmptyBeanSerializationWithCustomName() { - doSerializerTest("", new EmptyBeanWithCustomName()); - } - - public static class BeanWithPublicFields implements Comparable { - public int INT_V = 1; - public String STRING_V = "hello"; - - public BeanWithPublicFields(final int INT_V, final String STRING_V) { - this.INT_V = INT_V; - this.STRING_V = STRING_V; - } - - public BeanWithPublicFields() { - } - - @Override - public int compareTo(final BeanWithPublicFields o) { - return STRING_V.compareTo(o.STRING_V); - } - } - - public void testPublicFieldSerialization() { - BeanWithPublicFields bean = new BeanWithPublicFields(); - - doSerializerTest( - "\n" + - " ", bean); - - bean.INT_V = 2; - bean.STRING_V = "bye"; - - doSerializerTest( - "\n" + - " ", bean); - } - - - public static class BeanWithPublicFieldsDescendant extends BeanWithPublicFields { - public String NEW_S = "foo"; - } - - public void testPublicFieldSerializationWithInheritance() { - BeanWithPublicFieldsDescendant bean = new BeanWithPublicFieldsDescendant(); - - doSerializerTest( - "\n" + - " ", - bean); - - bean.INT_V = 2; - bean.STRING_V = "bye"; - bean.NEW_S = "bar"; - - doSerializerTest( - "\n" + - " ", - bean); - } - - public static class BeanWithSubBean { - public EmptyBeanWithCustomName BEAN1 = new EmptyBeanWithCustomName(); - public BeanWithPublicFields BEAN2 = new BeanWithPublicFields(); - } - - public void testSubBeanSerialization() { - BeanWithSubBean bean = new BeanWithSubBean(); - doSerializerTest( - "\n" + - " \n" + - " \n" + - "", - bean); - bean.BEAN2.INT_V = 2; - bean.BEAN2.STRING_V = "bye"; - - doSerializerTest( - "\n" + - " \n" + - " \n" + - "", - bean); - } - - public void testSubBeanSerializationAndSkipDefaults() { - BeanWithSubBean bean = new BeanWithSubBean(); - doSerializerTest( - "", - bean, new SkipDefaultsSerializationFilter()); - } - - public final static class BeanWithEquals { - public String STRING_V = "hello"; - - public BeanWithEquals() { - } - - @Override - public boolean equals(Object o) { - // any instance of this class is equal - return this == o || (o != null && getClass() == o.getClass()); - } - } - - public static class BeanWithSubBeanWithEquals { - public EmptyBeanWithCustomName BEAN1 = new EmptyBeanWithCustomName(); - public BeanWithEquals BEAN2 = new BeanWithEquals(); - } - - public void testSubBeanWithEqualsSerializationAndSkipDefaults() { - BeanWithSubBeanWithEquals bean = new BeanWithSubBeanWithEquals(); - SkipDefaultsSerializationFilter filter = new SkipDefaultsSerializationFilter(); - doSerializerTest( - "", - bean, filter); - - bean.BEAN2.STRING_V = "new"; - doSerializerTest( - "", - bean, filter); - } - - public void testNullFieldValue() { - BeanWithPublicFields bean1 = new BeanWithPublicFields(); - - doSerializerTest( - "\n" + - " ", - bean1); - - bean1.STRING_V = null; - - doSerializerTest( - "\n" + - " ", bean1); - - BeanWithSubBean bean2 = new BeanWithSubBean(); - bean2.BEAN1 = null; - bean2.BEAN2 = null; - - doSerializerTest( - "\n" + - " ", bean2); - - } - - public static class BeanWithList { - public List VALUES = new ArrayList(Arrays.asList("a", "b", "c")); - } - - public void testListSerialization() { - BeanWithList bean = new BeanWithList(); - - doSerializerTest( - "\n" + - " \n" + - "", - bean); - - bean.VALUES = new ArrayList(Arrays.asList("1", "2", "3")); - - doSerializerTest( - "\n" + - " \n" + - "", - bean); - } - - public static class BeanWithSet { - public Set VALUES = new LinkedHashSet(Arrays.asList("a", "b", "w")); - } - - public void testSetSerialization() { - BeanWithSet bean = new BeanWithSet(); - doSerializerTest( - "\n" + - " \n" + - "", - bean); - bean.VALUES = new LinkedHashSet(Arrays.asList("1", "2", "3")); - - doSerializerTest( - "\n" + - " \n" + - "", - bean); - } - - public static class BeanWithMap { - public Map VALUES = new LinkedHashMap(); - - { - VALUES.put("a", "1"); - VALUES.put("b", "2"); - VALUES.put("c", "3"); - } - } - - public void testMapSerialization() { - BeanWithMap bean = new BeanWithMap(); - doSerializerTest( - "\n" + - " \n" + - "", - bean); - bean.VALUES.clear(); - bean.VALUES.put("1", "a"); - bean.VALUES.put("2", "b"); - bean.VALUES.put("3", "c"); - - doSerializerTest( - "\n" + - " \n" + - "", - bean); - } - - - public static class BeanWithMapWithAnnotations { - @Property(surroundWithTag = false) - @MapAnnotation( - surroundWithTag = false, - entryTagName = "option", - keyAttributeName = "name", - valueAttributeName = "value" - ) - public Map VALUES = new LinkedHashMap(); - - { - VALUES.put("a", "1"); - VALUES.put("b", "2"); - VALUES.put("c", "3"); - } - } - - public void testMapSerializationWithAnnotations() { - BeanWithMapWithAnnotations bean = new BeanWithMapWithAnnotations(); - doSerializerTest( - "\n" + - " ", - bean); - bean.VALUES.clear(); - bean.VALUES.put("1", "a"); - bean.VALUES.put("2", "b"); - bean.VALUES.put("3", "c"); - - doSerializerTest( - "\n" + - " ", - bean); - } - - - public static class BeanWithMapWithBeanValue { - public Map VALUES = new LinkedHashMap(); - } - - public void testMapWithBeanValue() { - BeanWithMapWithBeanValue bean = new BeanWithMapWithBeanValue(); - - bean.VALUES.put("a", new BeanWithProperty("James")); - bean.VALUES.put("b", new BeanWithProperty("Bond")); - bean.VALUES.put("c", new BeanWithProperty("Bill")); - - doSerializerTest( - "\n" + - " \n" + - "", - bean); - } - - - public static class BeanWithMapWithBeanValue2 { - @MapAnnotation(surroundWithTag = false, surroundKeyWithTag = false, surroundValueWithTag = false) - public Map values = new THashMap(); - } - - - public void testMapWithBeanValueUsingSkipDefaultsFilter() { - BeanWithMapWithBeanValue2 bean = new BeanWithMapWithBeanValue2(); - doSerializerTest( - "", - bean, new SkipDefaultsSerializationFilter()); - } - - public static class BeanWithOption { - @OptionTag("path") - public String PATH; - } - - public void testOptionTag() { - BeanWithOption bean = new BeanWithOption(); - bean.PATH = "123"; - doSerializerTest("\n" + - " ", bean); - } - - public static class BeanWithCustomizedOption { - @OptionTag(tag = "setting", nameAttribute = "key", valueAttribute = "saved") - public String PATH; - } - - public void testCustomizedOptionTag() { - BeanWithCustomizedOption bean = new BeanWithCustomizedOption(); - bean.PATH = "123"; - doSerializerTest("\n" + - " \n" + - "", bean); - } - - public static class BeanWithProperty { - private String name = "James"; - - public BeanWithProperty() { - } - - public BeanWithProperty(final String name) { - this.name = name; - } - - public String getName() { - return name; - } - - - public void setName(String name) { - this.name = name; - } - } - - public void testPropertySerialization() { - BeanWithProperty bean = new BeanWithProperty(); - - doSerializerTest( - "\n" + - " ", - bean); - - bean.setName("Bond"); - - doSerializerTest( - "\n" + - " ", bean); - } - - public static class BeanWithFieldWithTagAnnotation { - @Tag("name") - public String STRING_V = "hello"; - } - - public void testParallelDeserialization() throws InterruptedException { - final Element e = new Element("root").addContent(new Element("name").setText("x")); - XmlSerializer.deserialize(e, BeanWithArray.class);//to initialize XmlSerializerImpl.ourBindings - Thread[] threads = new Thread[5]; - final AtomicReference exc = new AtomicReference(); - for (int i = 0; i < threads.length; i++) { - threads[i] = new Thread("XmlSerializerTest#testParallelDeserialization-" + i) { - @Override - public void run() { - try { - for (int j = 0; j < 10; j++) { - BeanWithFieldWithTagAnnotation bean = XmlSerializer.deserialize(e, BeanWithFieldWithTagAnnotation.class); - assertNotNull(bean); - assertEquals("x", bean.STRING_V); - } - } - catch (AssertionFailedError e) { - exc.set(e); - } - } - }; - } - for (Thread thread : threads) { - thread.start(); - } - for (Thread thread : threads) { - thread.join(); - } - AssertionFailedError error = exc.get(); - if (error != null) { - throw error; - } - } - - public void testFieldWithTagAnnotation() { - BeanWithFieldWithTagAnnotation bean = new BeanWithFieldWithTagAnnotation(); - - doSerializerTest( - "\n" + - " hello\n" + - "", - bean); - - bean.STRING_V = "bye"; - - doSerializerTest( - "\n" + - " bye\n" + - "", bean); - } - - public void testEscapeCharsInTagText() { - BeanWithFieldWithTagAnnotation bean = new BeanWithFieldWithTagAnnotation(); - bean.STRING_V = "a\nb\"<"; - - doSerializerTest( - "\n" + - " a\nb"<\n" + - "", bean); - } - - public void testEscapeCharsInAttributeValue() { - final BeanWithPropertiesBoundToAttribute bean = new BeanWithPropertiesBoundToAttribute(); - bean.name = "a\nb\"<"; - doSerializerTest("", bean); - } - - public void testShuffledDeserialize() { - BeanWithPublicFields bean = new BeanWithPublicFields(); - bean.INT_V = 987; - bean.STRING_V = "1234"; - - Element element = serialize(bean, null); - - Element node = element.getChildren().get(0); - element.removeContent(node); - element.addContent(node); - - bean = XmlSerializer.deserialize(element, bean.getClass()); - assert bean != null; - assertEquals(987, bean.INT_V); - assertEquals("1234", bean.STRING_V); - } - - public void testFilterSerializer() { - BeanWithPublicFields bean = new BeanWithPublicFields(); - assertSerializer(bean, - "\n" + - " ", - new SerializationFilter() { - @Override - public boolean accepts(@NotNull Accessor accessor, @NotNull Object bean) { - return accessor.getName().startsWith("I"); - } - }); - } - - public static class BeanWithArray { - public String[] ARRAY_V = new String[] {"a", "b"}; - } - - public void testArray() { - BeanWithArray bean = new BeanWithArray(); - doSerializerTest( - "\n" + - " \n" + - "", bean); - - bean.ARRAY_V = new String[] {"1", "2", "3", ""}; - doSerializerTest( - "\n" + - " \n" + - "", bean); - } - - public static class BeanWithTransient { - @Transient - public int INT_V = 1; - - @Transient - public String getValue() { - return "foo"; - } - } - public void testTransient() { - final BeanWithTransient bean = new BeanWithTransient(); - doSerializerTest("", bean); - } - - public static class BeanWithArrayWithoutTagName { - @AbstractCollection(surroundWithTag = false) - public String[] V = new String[]{"a"}; - } - - public void testArrayAnnotationWithoutTagNAmeGivesError() { - final BeanWithArrayWithoutTagName bean = new BeanWithArrayWithoutTagName(); - - try { - doSerializerTest("", bean); - } - catch (XmlSerializationException e) { - return; - } - - fail("No Exception"); - } - - public static class BeanWithArrayWithElementTagName { - @AbstractCollection(elementTag = "vvalue", elementValueAttribute = "v") - public String[] V = new String[]{"a", "b"}; - } - public void testArrayAnnotationWithElementTag() { - final BeanWithArrayWithElementTagName bean = new BeanWithArrayWithElementTagName(); - - doSerializerTest( - "\n" + - " \n" + - "", - bean); - - bean.V = new String[] {"1", "2", "3"}; - - doSerializerTest( - "\n" + - " \n" + - "", bean); - } - - public static class BeanWithArrayWithoutTag { - @AbstractCollection(elementTag = "vvalue", elementValueAttribute = "v", surroundWithTag = false) - public String[] V = new String[]{"a", "b"}; - public int INT_V = 1; - } - public void testArrayWithoutTag() { - final BeanWithArrayWithoutTag bean = new BeanWithArrayWithoutTag(); - - doSerializerTest( - "\n" + - " \n" + - " ", bean); - - bean.V = new String[] {"1", "2", "3"}; - - doSerializerTest( - "\n" + - " \n" + - " ", bean); - } - - - public static class BeanWithPropertyWithoutTagOnPrimitiveValue { - @Property(surroundWithTag = false) - public int INT_V = 1; - } - public void testPropertyWithoutTagWithPrimitiveType() { - final BeanWithPropertyWithoutTagOnPrimitiveValue bean = new BeanWithPropertyWithoutTagOnPrimitiveValue(); - - try { - doSerializerTest("hello", bean); - } - catch (XmlSerializationException e) { - return; - } - - fail("No Exception"); - } - - public static class BeanWithPropertyWithoutTag { - @Property(surroundWithTag = false) - public BeanWithPublicFields BEAN1 = new BeanWithPublicFields(); - public int INT_V = 1; - } - public void testPropertyWithoutTag() { - final BeanWithPropertyWithoutTag bean = new BeanWithPropertyWithoutTag(); - - doSerializerTest( - "\n" + - " \n" + - " \n" + - " ", - bean); - - bean.INT_V = 2; - bean.BEAN1.STRING_V = "junk"; - - doSerializerTest( - "\n" + - " \n" + - " \n" + - " ", bean); - } - - - public static class BeanWithArrayWithoutAllsTag { - @Property(surroundWithTag = false) - @AbstractCollection(elementTag = "vvalue", elementValueAttribute = "v", surroundWithTag = false) - public String[] V = new String[]{"a", "b"}; - - public int INT_V = 1; - } - - public void testArrayWithoutAllTags() { - final BeanWithArrayWithoutAllsTag bean = new BeanWithArrayWithoutAllsTag(); - - doSerializerTest( - "\n" + - " \n" + - " \n" + - " ", bean); - - bean.INT_V = 2; - bean.V = new String[] {"1", "2", "3"}; - - doSerializerTest( - "\n" + - " \n" + - " \n" + - " \n" + - " ", bean); - } - - public static class BeanWithArrayWithoutAllsTag2 { - @Property(surroundWithTag = false) - @AbstractCollection(elementTag = "vvalue", elementValueAttribute = "", surroundWithTag = false) - public String[] V = new String[]{"a", "b"}; - public int INT_V = 1; - } - public void testArrayWithoutAllTags2() { - final BeanWithArrayWithoutAllsTag2 bean = new BeanWithArrayWithoutAllsTag2(); - - doSerializerTest( - "\n" + - " a\n" + - " b\n" + - " ", bean); - - bean.INT_V = 2; - bean.V = new String[] {"1", "2", "3"}; - - doSerializerTest( - "\n" + - " 1\n" + - " 2\n" + - " 3\n" + - " ", bean); - } - - public void testDeserializeFromFormattedXML() throws Exception { - String xml = "\n" + - " "; - - BeanWithArrayWithoutAllsTag bean = XmlSerializer.deserialize(JDOMUtil.loadDocument(xml).getRootElement(), BeanWithArrayWithoutAllsTag.class); - - assertEquals(2, bean.INT_V); - assertEquals("[1, 2, 3]", Arrays.asList(bean.V).toString()); - } - - - public static class BeanWithPolymorphicArray { - @AbstractCollection(elementTypes = {BeanWithPublicFields.class, BeanWithPublicFieldsDescendant.class}) - public BeanWithPublicFields[] V = new BeanWithPublicFields[] {}; - } - - public void testPolymorphicArray() { - final BeanWithPolymorphicArray bean = new BeanWithPolymorphicArray(); - - doSerializerTest( - "\n" + - " \n" + - "", bean); - - bean.V = new BeanWithPublicFields[] {new BeanWithPublicFields(), new BeanWithPublicFieldsDescendant(), new BeanWithPublicFields()}; - - doSerializerTest( - "\n" + - " \n" + - "", bean); - } - - - public static class BeanWithPropertiesBoundToAttribute { - @Attribute( "count") - public int COUNT = 3; - @Attribute("name") - public String name = "James"; - @Attribute("occupation") - public String occupation; - } - public void testBeanWithPrimitivePropertyBoundToAttribute() { - final BeanWithPropertiesBoundToAttribute bean = new BeanWithPropertiesBoundToAttribute(); - - doSerializerTest("", bean); - - bean.COUNT = 10; - bean.name = "Bond"; - - doSerializerTest("", bean); - } - - - public static class BeanWithPropertyFilter { - @Property( - filter = PropertyFilterTest.class - ) - public String STRING_V = "hello"; - } - public static class PropertyFilterTest implements SerializationFilter { - @Override - public boolean accepts(@NotNull Accessor accessor, @NotNull Object bean) { - return !accessor.read(bean).equals("skip"); - } - } - public void testPropertyFilter() { - BeanWithPropertyFilter bean = new BeanWithPropertyFilter(); - - doSerializerTest( - "\n" + - " ", bean); - - bean.STRING_V = "bye"; - - doSerializerTest( - "\n" + - " ", bean); - - bean.STRING_V = "skip"; - - assertSerializer(bean, "", null); - } - - public static class BeanWithJDOMElement { - public String STRING_V = "hello"; - @Tag("actions") - public org.jdom.Element actions; - } - - public void testSerializeJDOMElementField() { - BeanWithJDOMElement element = new BeanWithJDOMElement(); - element.STRING_V = "a"; - element.actions = new Element("x").addContent(new Element("a")).addContent(new Element("b")); - assertSerializer(element, "\n" + - " ", null); - - element.actions = null; - assertSerializer(element, "\n" + - " ", null); - } - - public void testDeserializeJDOMElementField() throws Exception { - - - final BeanWithJDOMElement bean = XmlSerializer.deserialize(JDOMUtil.loadDocument( - "" - ).getRootElement(), BeanWithJDOMElement.class); - - - assertEquals("bye", bean.STRING_V); - assertNotNull(bean.actions); - assertEquals(2, bean.actions.getChildren("action").size()); - } - - public static class BeanWithJDOMElementArray { - public String STRING_V = "hello"; - @Tag("actions") - public org.jdom.Element[] actions; - } - - public void testJDOMElementArrayField() throws Exception { - String text = "\n" + - " "; - final BeanWithJDOMElementArray bean = XmlSerializer.deserialize(JDOMUtil.loadDocument(text - ).getRootElement(), BeanWithJDOMElementArray.class); - - - assertEquals("bye", bean.STRING_V); - assertNotNull(bean.actions); - assertEquals(2, bean.actions.length); - assertEquals(2, bean.actions[0].getChildren().size()); - assertEquals(1, bean.actions[1].getChildren().size()); - - assertSerializer(bean, text, null); - - bean.actions = null; - String newText = "\n" + - " "; - doSerializerTest(newText, bean); - - bean.actions = new Element[0]; - doSerializerTest(newText, bean); - } - - public static class BeanWithTextAnnotation { - public int INT_V = 1; - @Text - public String STRING_V = "hello"; - - public BeanWithTextAnnotation(final int INT_V, final String STRING_V) { - this.INT_V = INT_V; - this.STRING_V = STRING_V; - } - - public BeanWithTextAnnotation() { - } - } - - public void testTextAnnotation() { - BeanWithTextAnnotation bean = new BeanWithTextAnnotation(); - - doSerializerTest( - "\n" + - " ", bean); - - bean.INT_V = 2; - bean.STRING_V = "bye"; - - doSerializerTest( - "\n" + - " ", bean); - } - - - public static enum TestEnum { - VALUE_1, - VALUE_2, - VALUE_3; - } - - public static class BeanWithEnum { - public TestEnum FLD = TestEnum.VALUE_1; - } - - public void testEnums() { - BeanWithEnum bean = new BeanWithEnum(); - - doSerializerTest( - "\n" + " ", bean); - - bean.FLD = TestEnum.VALUE_3; - - doSerializerTest( - "\n" + " ", bean); - } - - public static class BeanWithSetKeysInMap { - public Map, String> myMap = new LinkedHashMap, String>(); - } - - public void testSetKeysInMap() { - final BeanWithSetKeysInMap bean = new BeanWithSetKeysInMap(); - bean.myMap.put(new LinkedHashSet(Arrays.asList("a", "b", "c")), "letters"); - bean.myMap.put(new LinkedHashSet(Arrays.asList("1", "2", "3")), "numbers"); - - BeanWithSetKeysInMap bb = doSerializerTest( - "\n" + - " \n" + - "", - bean); - - for (Collection collection : bb.myMap.keySet()) { - assertTrue(collection instanceof Set); - } - } - - public static class ConversionFromTextToAttributeBean { - @Property(surroundWithTag = false) - public ConditionBean myConditionBean = new ConditionBean(); - } - @Tag("condition") - public static class ConditionBean { - @Attribute("expression") - public String myNewCondition; - @Text - public String myOldCondition; - } - - public void testConversionFromTextToAttribute() { - ConversionFromTextToAttributeBean bean = new ConversionFromTextToAttributeBean(); - bean.myConditionBean.myOldCondition = "2+2"; - doSerializerTest("\n" + - " 2+2\n" + - "", bean); - - bean = new ConversionFromTextToAttributeBean(); - bean.myConditionBean.myNewCondition = "2+2"; - doSerializerTest("\n" + - " \n" + - "", bean); - } - - public void testDeserializeInto() throws Exception { - BeanWithPublicFields bean = new BeanWithPublicFields(); - bean.STRING_V = "zzz"; - - String xml = ""; - XmlSerializer.deserializeInto(bean, JDOMUtil.loadDocument(xml).getRootElement()); - - assertEquals(999, bean.INT_V); - assertEquals("zzz", bean.STRING_V); - } - - public static class BeanWithMapWithoutSurround { - @Tag("map") - @MapAnnotation(surroundWithTag = false, entryTagName = "pair", surroundKeyWithTag = false, surroundValueWithTag = false) - public Map MAP = new LinkedHashMap(); - } - - public void testMapWithNotSurroundingKeyAndValue() { - BeanWithMapWithoutSurround bean = new BeanWithMapWithoutSurround(); - - bean.MAP.put(new BeanWithPublicFields(1, "a"), new BeanWithTextAnnotation(2, "b")); - bean.MAP.put(new BeanWithPublicFields(3, "c"), new BeanWithTextAnnotation(4, "d")); - bean.MAP.put(new BeanWithPublicFields(5, "e"), new BeanWithTextAnnotation(6, "f")); - - doSerializerTest( - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "", - bean); - } - - public static class BeanWithMapAtTopLevel { - @Property(surroundWithTag = false) - @MapAnnotation(surroundWithTag = false, surroundKeyWithTag = false, surroundValueWithTag = false) - public Map map = new LinkedHashMap(); - - public String option; - } - - public void testMapAtTopLevel() { - BeanWithMapAtTopLevel bean = new BeanWithMapAtTopLevel(); - bean.map.put("a", "b"); - bean.option = "xxx"; - doSerializerTest("\n" + - " \n" + - " ", bean); - } - - private static class BeanWithConverter { - private static class MyConverter extends Converter> { - @Nullable - @Override - public Ref fromString(@NotNull String value) { - return Ref.create(value); - } - - @NotNull - @Override - public String toString(@NotNull Ref o) { - return StringUtil.notNullize(o.get()); - } - } - - @Attribute(converter = MyConverter.class) - public Ref foo; - - @OptionTag(converter = MyConverter.class) - public Ref bar; - } - - public void testConverter() { - BeanWithConverter bean = new BeanWithConverter(); - doSerializerTest("\n" + - " ", bean); - - bean.foo = Ref.create("testValue"); - doSerializerTest("\n" + - " ", bean); - - bean.foo = Ref.create(); - bean.bar = Ref.create("testValue2"); - doSerializerTest("\n" + - " ", bean); - } - - public void testConverterUsingSkipDefaultsFilter() { - BeanWithConverter bean = new BeanWithConverter(); - doSerializerTest("", bean, new SkipDefaultsSerializationFilter()); - - bean.foo = Ref.create("testValue"); - doSerializerTest("", bean, new SkipDefaultsSerializationFilter()); - - bean.foo = Ref.create(); - bean.bar = Ref.create("testValue2"); - doSerializerTest("\n" + - " ", bean); - } - - private static class BeanWithDefaultAttributeName { - @Attribute - public String getFoo() { - return "foo"; - } - - public void setFoo(@SuppressWarnings("UnusedParameters") String value) { - } - } - - public void testDefaultAttributeName() { - BeanWithDefaultAttributeName bean = new BeanWithDefaultAttributeName(); - doSerializerTest("", bean); - } - - static class Bean2 { - @Attribute - public String ab; - - @Attribute - public String module; - - @Attribute - public String ac; - } - - public void testOrdered() throws IOException, JDOMException { - Bean2 bean = new Bean2(); - bean.module = "module"; - bean.ab = "ab"; - doSerializerTest("", bean, new SkipDefaultsSerializationFilter()); - - checkSmartSerialization(new Bean2(), ""); - checkSmartSerialization(new Bean2(), ""); - checkSmartSerialization(new Bean2(), ""); - checkSmartSerialization(new Bean2(), ""); - checkSmartSerialization(new Bean2(), ""); - } - - @SuppressWarnings("deprecation") - @Tag("b") - static class Bean3 { - public JDOMExternalizableStringList list = new JDOMExternalizableStringList(); - } - - @Tag("b") - static class Bean4 { - @CollectionBean - public final List list = new SmartList(); - } - - @SuppressWarnings("deprecation") - public void testJDOMExternalizableStringList() throws IOException, JDOMException { - Bean3 bean = new Bean3(); - bean.list.add("one"); - bean.list.add("two"); - bean.list.add("three"); - doSerializerTest("\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "", bean, new SkipDefaultsSerializationFilter()); - } - - public void testCollectionBean() throws IOException, JDOMException { - Bean4 bean = new Bean4(); - bean.list.add("one"); - bean.list.add("two"); - bean.list.add("three"); - doSerializerTest("\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "", bean, new SkipDefaultsSerializationFilter()); - } - - public void testCollectionBeanReadJDOMExternalizableStringList() throws IOException, JDOMException { - @SuppressWarnings("deprecation") - JDOMExternalizableStringList list = new JDOMExternalizableStringList(); - list.add("one"); - list.add("two"); - list.add("three"); - - Element value = new Element("value"); - list.writeExternal(value); - Bean4 o = XmlSerializer.deserialize(new Element("state").addContent(new Element("option").setAttribute("name", "myList").addContent(value)), Bean4.class); - assertSerializer(o, "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "", "Deserialization failure", new SkipDefaultsSerializationFilter()); - } - - private static void checkSmartSerialization(@NotNull Bean2 bean, @NotNull String serialized) throws IOException, JDOMException { - SmartSerializer serializer = new SmartSerializer(); - serializer.readExternal(bean, JDOMUtil.loadDocument(serialized).getRootElement()); - Element serializedState = new Element("Bean2"); - serializer.writeExternal(bean, serializedState); - assertEquals(serialized, JDOMUtil.writeElement(serializedState)); - } - - //--------------------------------------------------------------------------------------------------- - private static Element assertSerializer(Object bean, String expected, SerializationFilter filter) { - return assertSerializer(bean, expected, "Serialization failure", filter); - } - - private static T doSerializerTest(@Language("XML") String expectedText, T bean) { - return doSerializerTest(expectedText, bean, null); - } - - private static T doSerializerTest(@Language("XML") String expectedText, T bean, @Nullable SerializationFilter filter) { - Element element = assertSerializer(bean, expectedText, filter); - - //test deserializer - @SuppressWarnings("unchecked") - Class aClass = (Class)bean.getClass(); - T o = XmlSerializer.deserialize(element, aClass); - assertSerializer(o, expectedText, "Deserialization failure", filter); - return o; - } - - private static Element assertSerializer(Object bean, String expectedText, String message, SerializationFilter filter) throws XmlSerializationException { - Element element = serialize(bean, filter); - String actualString = JDOMUtil.writeElement(element, "\n").trim(); - if (!expectedText.startsWith(XML_PREFIX)) { - if (actualString.startsWith(XML_PREFIX)) actualString = actualString.substring(XML_PREFIX.length()).trim(); - } - - assertEquals(message, expectedText, actualString); - return element; - } - - public static class BeanWithMapWithSetValue { - @MapAnnotation(entryTagName = "entry-tag", keyAttributeName = "key-attr", surroundWithTag = false) - public Map> myValues = new LinkedHashMap>(); - } - - public void testBeanWithMapWithSetValue() { - BeanWithMapWithSetValue bean = new BeanWithMapWithSetValue(); - - bean.myValues.put("a", new LinkedHashSet(Arrays.asList("first1", "second1"))); - bean.myValues.put("b", new LinkedHashSet(Arrays.asList("first2", "second2"))); - - doSerializerTest( - "\n" + - " \n" + - "", - bean); - } - - private static Element serialize(Object bean, SerializationFilter filter) { - return XmlSerializer.serialize(bean, filter); - } -} \ No newline at end of file diff --git a/platform/util/testSrc/com/intellij/util/xmlb/XmlSerializerTest.kt b/platform/util/testSrc/com/intellij/util/xmlb/XmlSerializerTest.kt new file mode 100644 index 000000000000..9b9e426eaad0 --- /dev/null +++ b/platform/util/testSrc/com/intellij/util/xmlb/XmlSerializerTest.kt @@ -0,0 +1,1004 @@ +/* + * Copyright 2000-2015 JetBrains s.r.o. + * + * 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 com.intellij.util.xmlb + +import com.intellij.openapi.util.JDOMExternalizableStringList +import com.intellij.openapi.util.JDOMUtil +import com.intellij.openapi.util.Ref +import com.intellij.openapi.util.text.StringUtil +import com.intellij.util.SmartList +import com.intellij.util.xmlb.annotations.* +import gnu.trove.THashMap +import junit.framework.AssertionFailedError +import junit.framework.TestCase +import org.assertj.core.api.Assertions.assertThat +import org.intellij.lang.annotations.Language +import org.jdom.Element +import org.jdom.JDOMException +import org.junit.Test +import java.io.IOException +import java.util.ArrayList +import java.util.Arrays +import java.util.LinkedHashMap +import java.util.LinkedHashSet +import java.util.concurrent.atomic.AtomicReference + +public class XmlSerializerTest { + public @Test fun EmptyBeanSerialization() { + @Tag("bean") + class EmptyBean + + doSerializerTest("", EmptyBean()) + } + + @Tag("Bean") + class EmptyBeanWithCustomName + + public @Test fun EmptyBeanSerializationWithCustomName() { + doSerializerTest("", EmptyBeanWithCustomName()) + } + + open class BeanWithPublicFields(var INT_V: Int = 1, var STRING_V: String? = "hello") : Comparable { + override fun compareTo(other: BeanWithPublicFields) = StringUtil.compare(STRING_V, other.STRING_V, false) + } + + public @Test fun PublicFieldSerialization() { + val bean = BeanWithPublicFields() + + doSerializerTest("\n" + " ", bean) + + bean.INT_V = 2 + bean.STRING_V = "bye" + + doSerializerTest("\n" + " ", bean) + } + + + class BeanWithPublicFieldsDescendant(var NEW_S: String = "foo") : BeanWithPublicFields() + + @Test fun publicFieldSerializationWithInheritance() { + val bean = BeanWithPublicFieldsDescendant() + + doSerializerTest(""" + """, bean) + + bean.INT_V = 2 + bean.STRING_V = "bye" + bean.NEW_S = "bar" + + doSerializerTest(""" + """, bean) + } + + class BeanWithSubBean { + public var BEAN1: EmptyBeanWithCustomName? = EmptyBeanWithCustomName() + public var BEAN2: BeanWithPublicFields? = BeanWithPublicFields() + } + + @Test fun SubBeanSerialization() { + val bean = BeanWithSubBean() + doSerializerTest("\n" + " \n" + " \n" + "", bean) + bean.BEAN2!!.INT_V = 2 + bean.BEAN2!!.STRING_V = "bye" + + doSerializerTest("\n" + " \n" + " \n" + "", bean) + } + + @Test fun SubBeanSerializationAndSkipDefaults() { + val bean = BeanWithSubBean() + doSerializerTest("", bean, SkipDefaultsSerializationFilter()) + } + + class BeanWithEquals { + public var STRING_V: String = "hello" + + override fun equals(other: Any?): Boolean { + // any instance of this class is equal + return this === other || (other != null && javaClass == other.javaClass) + } + } + + class BeanWithSubBeanWithEquals { + public var BEAN1: EmptyBeanWithCustomName = EmptyBeanWithCustomName() + public var BEAN2: BeanWithEquals = BeanWithEquals() + } + + @Test fun SubBeanWithEqualsSerializationAndSkipDefaults() { + val bean = BeanWithSubBeanWithEquals() + val filter = SkipDefaultsSerializationFilter() + doSerializerTest("", bean, filter) + + bean.BEAN2.STRING_V = "new" + doSerializerTest("", bean, filter) + } + + @Test fun NullFieldValue() { + val bean1 = BeanWithPublicFields() + + doSerializerTest("\n" + " ", bean1) + + bean1.STRING_V = null + + doSerializerTest("\n" + " ", bean1) + + val bean2 = BeanWithSubBean() + bean2.BEAN1 = null + bean2.BEAN2 = null + + doSerializerTest("\n" + " ", bean2) + + } + + class BeanWithList { + public var VALUES: List = ArrayList(Arrays.asList("a", "b", "c")) + } + + @Test fun ListSerialization() { + val bean = BeanWithList() + + doSerializerTest("\n" + " \n" + "", bean) + + bean.VALUES = ArrayList(Arrays.asList("1", "2", "3")) + + doSerializerTest("\n" + " \n" + "", bean) + } + + public class BeanWithSet { + public var VALUES: Set = LinkedHashSet(Arrays.asList("a", "b", "w")) + } + + public @Test fun SetSerialization() { + val bean = BeanWithSet() + doSerializerTest("\n" + " \n" + "", bean) + bean.VALUES = LinkedHashSet(Arrays.asList("1", "2", "3")) + + doSerializerTest("\n" + " \n" + "", bean) + } + + public class BeanWithMap { + public var VALUES: MutableMap = LinkedHashMap() + + init { + VALUES.put("a", "1") + VALUES.put("b", "2") + VALUES.put("c", "3") + } + } + + public @Test fun MapSerialization() { + val bean = BeanWithMap() + doSerializerTest("\n" + " \n" + "", bean) + bean.VALUES.clear() + bean.VALUES.put("1", "a") + bean.VALUES.put("2", "b") + bean.VALUES.put("3", "c") + + doSerializerTest("\n" + " \n" + "", bean) + } + + + public class BeanWithMapWithAnnotations { + Property(surroundWithTag = false) + MapAnnotation(surroundWithTag = false, entryTagName = "option", keyAttributeName = "name", valueAttributeName = "value") + public var VALUES: MutableMap = LinkedHashMap() + + init { + VALUES.put("a", "1") + VALUES.put("b", "2") + VALUES.put("c", "3") + } + } + + public @Test fun MapSerializationWithAnnotations() { + val bean = BeanWithMapWithAnnotations() + doSerializerTest("\n" + " ", bean) + bean.VALUES.clear() + bean.VALUES.put("1", "a") + bean.VALUES.put("2", "b") + bean.VALUES.put("3", "c") + + doSerializerTest("\n" + " ", bean) + } + + + public class BeanWithMapWithBeanValue { + public var VALUES: MutableMap = LinkedHashMap() + } + + public @Test fun MapWithBeanValue() { + val bean = BeanWithMapWithBeanValue() + + bean.VALUES.put("a", BeanWithProperty("James")) + bean.VALUES.put("b", BeanWithProperty("Bond")) + bean.VALUES.put("c", BeanWithProperty("Bill")) + + doSerializerTest("\n" + " \n" + "", bean) + } + + + public class BeanWithMapWithBeanValue2 { + MapAnnotation(surroundWithTag = false, surroundKeyWithTag = false, surroundValueWithTag = false) + public var values: Map = THashMap() + } + + + public @Test fun MapWithBeanValueUsingSkipDefaultsFilter() { + val bean = BeanWithMapWithBeanValue2() + doSerializerTest("", bean, SkipDefaultsSerializationFilter()) + } + + data class BeanWithOption(@OptionTag("path") public var PATH: String? = null) + + public @Test fun OptionTag() { + val bean = BeanWithOption() + bean.PATH = "123" + doSerializerTest("\n" + " ", bean) + } + + data class BeanWithCustomizedOption(@OptionTag(tag = "setting", nameAttribute = "key", valueAttribute = "saved") public var PATH: String? = null) + + public @Test fun CustomizedOptionTag() { + val bean = BeanWithCustomizedOption() + bean.PATH = "123" + doSerializerTest("\n" + " \n" + "", bean) + } + + public class BeanWithProperty { + public var name: String = "James" + + public constructor() { + } + + public constructor(name: String) { + this.name = name + } + } + + public @Test fun PropertySerialization() { + val bean = BeanWithProperty() + + doSerializerTest("\n" + " ", bean) + + bean.name = "Bond" + + doSerializerTest("\n" + " ", bean) + } + + public class BeanWithFieldWithTagAnnotation { + Tag("name") + public var STRING_V: String = "hello" + } + + public @Test fun ParallelDeserialization() { + val e = Element("root").addContent(Element("name").setText("x")) + XmlSerializer.deserialize(e, javaClass())//to initialize XmlSerializerImpl.ourBindings + val exc = AtomicReference() + val threads = Array(5) { + Thread(Runnable { + try { + for (j in 0..9) { + val bean = XmlSerializer.deserialize(e, javaClass()) + TestCase.assertNotNull(bean) + TestCase.assertEquals("x", bean.STRING_V) + } + } + catch (e: AssertionFailedError) { + exc.set(e) + } + }, "XmlSerializerTest#testParallelDeserialization-$it") + } + for (thread in threads) { + thread.start() + } + for (thread in threads) { + thread.join() + } + exc.get()?.let { throw it } + } + + public @Test fun FieldWithTagAnnotation() { + val bean = BeanWithFieldWithTagAnnotation() + doSerializerTest("\n" + " hello\n" + "", bean) + bean.STRING_V = "bye" + doSerializerTest("\n" + " bye\n" + "", bean) + } + + public @Test fun EscapeCharsInTagText() { + val bean = BeanWithFieldWithTagAnnotation() + bean.STRING_V = "a\nb\"<" + + doSerializerTest("\n" + " a\nb"<\n" + "", bean) + } + + public @Test fun EscapeCharsInAttributeValue() { + val bean = BeanWithPropertiesBoundToAttribute() + bean.name = "a\nb\"<" + doSerializerTest("", bean) + } + + public @Test fun ShuffledDeserialize() { + var bean: BeanWithPublicFields? = BeanWithPublicFields() + bean!!.INT_V = 987 + bean.STRING_V = "1234" + + val element = serialize(bean, null) + + val node = element.getChildren().get(0) + element.removeContent(node) + element.addContent(node) + + bean = XmlSerializer.deserialize(element, bean.javaClass) + assert(bean != null) + TestCase.assertEquals(987, bean!!.INT_V) + TestCase.assertEquals("1234", bean.STRING_V) + } + + public @Test fun FilterSerializer() { + val bean = BeanWithPublicFields() + assertSerializer(bean, "\n" + " ", object : SerializationFilter { + override fun accepts(accessor: Accessor, bean: Any) = accessor.getName().startsWith("I") + }) + } + + data class BeanWithArray(public var ARRAY_V: Array = arrayOf("a", "b")) + + public @Test fun Array() { + val bean = BeanWithArray() + doSerializerTest("\n" + " \n" + "", bean) + + bean.ARRAY_V = arrayOf("1", "2", "3", "") + doSerializerTest("\n" + " \n" + "", bean) + } + + public @Test fun Transient() { + @Tag("bean") + class Bean { + public var INT_V: Int = 1 + @Transient + get + + public @Transient fun getValue(): String = "foo" + } + + doSerializerTest("", Bean()) + } + + public class BeanWithArrayWithoutTagName { + AbstractCollection(surroundWithTag = false) + public var V: Array = arrayOf("a") + } + + public @Test fun ArrayAnnotationWithoutTagNAmeGivesError() { + val bean = BeanWithArrayWithoutTagName() + + try { + doSerializerTest("", bean) + } + catch (e: XmlSerializationException) { + return + } + + + TestCase.fail("No Exception") + } + + @Test fun arrayAnnotationWithElementTag() { + @Tag("bean") class Bean { + @AbstractCollection(elementTag = "vvalue", elementValueAttribute = "v") + var v = arrayOf("a", "b") + } + + val bean = Bean() + + doSerializerTest(""" + +""", bean) + + bean.v = arrayOf("1", "2", "3") + + doSerializerTest("\n" + " \n" + "", bean) + } + + @Test fun arrayWithoutTag() { + @Tag("bean") + class Bean { + @AbstractCollection(elementTag = "vvalue", elementValueAttribute = "v", surroundWithTag = false) + var v = arrayOf("a", "b") + var INT_V = 1 + } + + val bean = Bean() + + doSerializerTest(""" + +""", bean) + + bean.v = arrayOf("1", "2", "3") + + doSerializerTest(""" + +""", bean) + } + + @Test fun PropertyWithoutTagWithPrimitiveType() { + @Tag("bean") + class BeanWithPropertyWithoutTagOnPrimitiveValue { + @Property(surroundWithTag = false) + var INT_V = 1 + } + + val bean = BeanWithPropertyWithoutTagOnPrimitiveValue() + try { + doSerializerTest("hello", bean) + } + catch (e: XmlSerializationException) { + return + } + + TestCase.fail("No Exception") + } + + @Test fun PropertyWithoutTag() { + @Tag("bean") + class BeanWithPropertyWithoutTag { + @Property(surroundWithTag = false) + var BEAN1 = BeanWithPublicFields() + var INT_V = 1 + } + + val bean = BeanWithPropertyWithoutTag() + + doSerializerTest(""" + """, bean) + + bean.INT_V = 2 + bean.BEAN1.STRING_V = "junk" + + doSerializerTest(""" + """, bean) + } + + @Tag("bean") + class BeanWithArrayWithoutAllsTag { + @Property(surroundWithTag = false) + @AbstractCollection(elementTag = "vvalue", elementValueAttribute = "v", surroundWithTag = false) + var v = arrayOf("a", "b") + + var INT_V = 1 + } + + @Test fun arrayWithoutAllTags() { + val bean = BeanWithArrayWithoutAllsTag() + + doSerializerTest(""" + """, bean) + + bean.INT_V = 2 + bean.v = arrayOf("1", "2", "3") + + doSerializerTest(""" + """, bean) + } + + @Test fun arrayWithoutAllTags2() { + @Tag("bean") + class BeanWithArrayWithoutAllTag2 { + @Property(surroundWithTag = false) + @AbstractCollection(elementTag = "vvalue", elementValueAttribute = "", surroundWithTag = false) + var v = arrayOf("a", "b") + var INT_V = 1 + } + + val bean = BeanWithArrayWithoutAllTag2() + + doSerializerTest(""" + """, bean) + + bean.INT_V = 2 + bean.v = arrayOf("1", "2", "3") + + doSerializerTest("\n" + " 1\n" + " 2\n" + " 3\n" + " ", bean) + } + + @Test fun DeserializeFromFormattedXML() { + val xml = "\n" + " " + + val bean = XmlSerializer.deserialize(JDOMUtil.loadDocument(xml).getRootElement(), javaClass()) + + assertThat(2).isEqualTo(bean.INT_V) + assertThat("[1, 2, 3]").isEqualTo(Arrays.asList(*bean.v).toString()) + } + + @Test fun polymorphicArray() { + @Tag("bean") + class BeanWithPolymorphicArray { + @AbstractCollection(elementTypes = arrayOf(BeanWithPublicFields::class, BeanWithPublicFieldsDescendant::class)) + var v = arrayOf() + } + + val bean = BeanWithPolymorphicArray() + + doSerializerTest("\n" + " \n" + "", bean) + + bean.v = arrayOf(BeanWithPublicFields(), BeanWithPublicFieldsDescendant(), BeanWithPublicFields()) + + doSerializerTest(""" + +""", bean) + } + + class BeanWithPropertiesBoundToAttribute { + @Attribute("count") + var COUNT = 3 + @Attribute("name") + var name = "James" + @Attribute("occupation") + var occupation: String? = null + } + + public @Test fun BeanWithPrimitivePropertyBoundToAttribute() { + val bean = BeanWithPropertiesBoundToAttribute() + + doSerializerTest("", bean) + + bean.COUNT = 10 + bean.name = "Bond" + + doSerializerTest("", bean) + } + + + class BeanWithPropertyFilter { + Property(filter = PropertyFilterTest::class) + public var STRING_V: String = "hello" + } + + class PropertyFilterTest : SerializationFilter { + override fun accepts(accessor: Accessor, bean: Any): Boolean { + return accessor.read(bean) != "skip" + } + } + + @Test fun PropertyFilter() { + val bean = BeanWithPropertyFilter() + + doSerializerTest("\n" + " ", bean) + + bean.STRING_V = "bye" + + doSerializerTest("\n" + " ", bean) + + bean.STRING_V = "skip" + + assertSerializer(bean, "", null) + } + + class BeanWithJDOMElement { + public var STRING_V: String = "hello" + Tag("actions") + public var actions: org.jdom.Element? = null + } + + @Test fun SerializeJDOMElementField() { + val element = BeanWithJDOMElement() + element.STRING_V = "a" + element.actions = Element("x").addContent(Element("a")).addContent(Element("b")) + assertSerializer(element, "\n" + " \n" + " \n" + " \n" + "", null) + + element.actions = null + assertSerializer(element, "\n" + " ", null) + } + + throws(Exception::class) + public @Test fun DeserializeJDOMElementField() { + + + val bean = XmlSerializer.deserialize(JDOMUtil.loadDocument("").getRootElement(), javaClass()) + + + TestCase.assertEquals("bye", bean.STRING_V) + TestCase.assertNotNull(bean.actions) + TestCase.assertEquals(2, bean.actions!!.getChildren("action").size()) + } + + class BeanWithJDOMElementArray { + public var STRING_V: String = "hello" + Tag("actions") + public var actions: Array? = null + } + + @Test fun JDOMElementArrayField() { + val text = "\n" + " " + val bean = XmlSerializer.deserialize(JDOMUtil.loadDocument(text).getRootElement(), javaClass()) + + + TestCase.assertEquals("bye", bean.STRING_V) + TestCase.assertNotNull(bean.actions) + TestCase.assertEquals(2, bean.actions!!.size()) + TestCase.assertEquals(2, bean.actions!![0].getChildren().size()) + TestCase.assertEquals(1, bean.actions!![1].getChildren().size()) + + assertSerializer(bean, text, null) + + bean.actions = null + val newText = "\n" + " " + doSerializerTest(newText, bean) + + bean.actions = emptyArray() + doSerializerTest(newText, bean) + } + + class BeanWithTextAnnotation { + public var INT_V: Int = 1 + Text + public var STRING_V: String = "hello" + + public constructor(INT_V: Int, STRING_V: String) { + this.INT_V = INT_V + this.STRING_V = STRING_V + } + + public constructor() { + } + } + + @Test fun TextAnnotation() { + val bean = BeanWithTextAnnotation() + + doSerializerTest("\n" + " ", bean) + + bean.INT_V = 2 + bean.STRING_V = "bye" + + doSerializerTest("\n" + " ", bean) + } + + class BeanWithEnum { + enum class TestEnum { + VALUE_1, + VALUE_2, + VALUE_3 + } + + var FLD = TestEnum.VALUE_1 + } + + @Test fun Enums() { + val bean = BeanWithEnum() + + doSerializerTest("\n" + " ", bean) + + bean.FLD = BeanWithEnum.TestEnum.VALUE_3 + + doSerializerTest("\n" + " ", bean) + } + + @Test fun SetKeysInMap() { + @Tag("bean") + class BeanWithSetKeysInMap { + var myMap = LinkedHashMap, String>() + } + + val bean = BeanWithSetKeysInMap() + bean.myMap.put(LinkedHashSet(Arrays.asList("a", "b", "c")), "letters") + bean.myMap.put(LinkedHashSet(Arrays.asList("1", "2", "3")), "numbers") + + val bb = doSerializerTest("\n" + " \n" + "", bean) + + for (collection in bb.myMap.keySet()) { + assertThat(collection).isInstanceOf(javaClass>()) + } + } + + @Test fun ConversionFromTextToAttribute() { + @Tag("condition") + class ConditionBean { + @Attribute("expression") + var newCondition: String? = null + @Text + var oldCondition: String? = null + } + + @Tag("bean") + class Bean { + @Property(surroundWithTag = false) + var conditionBean = ConditionBean() + } + + var bean = Bean() + bean.conditionBean.oldCondition = "2+2" + doSerializerTest("\n 2+2\n", bean) + + bean = Bean() + bean.conditionBean.newCondition = "2+2" + doSerializerTest("\n \n" + "", bean) + } + + public @Test fun deserializeInto() { + val bean = BeanWithPublicFields() + bean.STRING_V = "zzz" + + val xml = "" + XmlSerializer.deserializeInto(bean, JDOMUtil.loadDocument(xml).getRootElement()) + + TestCase.assertEquals(999, bean.INT_V) + TestCase.assertEquals("zzz", bean.STRING_V) + } + + @Test fun mapWithNotSurroundingKeyAndValue() { + @Tag("bean") + class Bean { + @Tag("map") + @MapAnnotation(surroundWithTag = false, entryTagName = "pair", surroundKeyWithTag = false, surroundValueWithTag = false) + var MAP = LinkedHashMap() + } + + val bean = Bean() + + bean.MAP.put(BeanWithPublicFields(1, "a"), BeanWithTextAnnotation(2, "b")) + bean.MAP.put(BeanWithPublicFields(3, "c"), BeanWithTextAnnotation(4, "d")) + bean.MAP.put(BeanWithPublicFields(5, "e"), BeanWithTextAnnotation(6, "f")) + + doSerializerTest("\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "", bean) + } + + public @Test fun MapAtTopLevel() { + @Tag("bean") + class BeanWithMapAtTopLevel { + @Property(surroundWithTag = false) + @MapAnnotation(surroundWithTag = false, surroundKeyWithTag = false, surroundValueWithTag = false) + var map = LinkedHashMap() + + var option: String? = null + } + + val bean = BeanWithMapAtTopLevel() + bean.map.put("a", "b") + bean.option = "xxx" + doSerializerTest(""" + """, bean) + } + + private class BeanWithConverter { + private class MyConverter : Converter>() { + override fun fromString(value: String): Ref? { + return Ref.create(value) + } + + override fun toString(o: Ref): String { + return StringUtil.notNullize(o.get()) + } + } + + @Attribute(converter = MyConverter::class) + var foo: Ref? = null + + @OptionTag(converter = MyConverter::class) + var bar: Ref? = null + } + + public @Test fun Converter() { + val bean = BeanWithConverter() + doSerializerTest("\n" + " ", bean) + + bean.foo = Ref.create("testValue") + doSerializerTest("\n" + " ", bean) + + bean.foo = Ref.create() + bean.bar = Ref.create("testValue2") + doSerializerTest("\n" + " ", bean) + } + + public @Test fun ConverterUsingSkipDefaultsFilter() { + val bean = BeanWithConverter() + doSerializerTest("", bean, SkipDefaultsSerializationFilter()) + + bean.foo = Ref.create("testValue") + doSerializerTest("", bean, SkipDefaultsSerializationFilter()) + + bean.foo = Ref.create() + bean.bar = Ref.create("testValue2") + doSerializerTest("\n" + " ", bean) + } + + private class BeanWithDefaultAttributeName { + Attribute + public fun getFoo(): String { + return "foo" + } + + public fun setFoo(value: String) { + } + } + + public @Test fun DefaultAttributeName() { + val bean = BeanWithDefaultAttributeName() + doSerializerTest("", bean) + } + + class Bean2 { + Attribute + var ab: String? = null + + Attribute + var module: String? = null + + Attribute + var ac: String? = null + } + + throws(IOException::class, JDOMException::class) + public @Test fun Ordered() { + val bean = Bean2() + bean.module = "module" + bean.ab = "ab" + doSerializerTest("", bean, SkipDefaultsSerializationFilter()) + + checkSmartSerialization(Bean2(), "") + checkSmartSerialization(Bean2(), "") + checkSmartSerialization(Bean2(), "") + checkSmartSerialization(Bean2(), "") + checkSmartSerialization(Bean2(), "") + } + + @Tag("b") + class Bean3 { + @suppress("DEPRECATED_SYMBOL_WITH_MESSAGE") + public var list: JDOMExternalizableStringList = JDOMExternalizableStringList() + } + + Tag("b") + class Bean4 { + @CollectionBean + val list = SmartList() + } + + public @Test fun testJDOMExternalizableStringList() { + val bean = Bean3() + bean.list.add("one") + bean.list.add("two") + bean.list.add("three") + doSerializerTest("\n" + " \n" + " \n" + " \n" + " \n" + " \n" + "", bean, SkipDefaultsSerializationFilter()) + } + + @Test fun CollectionBean() { + val bean = Bean4() + bean.list.add("one") + bean.list.add("two") + bean.list.add("three") + doSerializerTest("\n" + " \n" + " \n" + " \n" + " \n" + " \n" + "", bean, SkipDefaultsSerializationFilter()) + } + + @Test fun CollectionBeanReadJDOMExternalizableStringList() { + @suppress("DEPRECATED_SYMBOL_WITH_MESSAGE") + val list = JDOMExternalizableStringList() + list.add("one") + list.add("two") + list.add("three") + + val value = Element("value") + list.writeExternal(value) + val o = XmlSerializer.deserialize(Element("state").addContent(Element("option").setAttribute("name", "myList").addContent(value)), javaClass()) + assertSerializer(o, "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + "", SkipDefaultsSerializationFilter()) + } + + @Test fun beanWithMapWithSetValue() { + @Tag("bean") + class BeanWithMapWithSetValue { + @MapAnnotation(entryTagName = "entry-tag", keyAttributeName = "key-attr", surroundWithTag = false) + var myValues = LinkedHashMap>() + } + + val bean = BeanWithMapWithSetValue() + + bean.myValues.put("a", LinkedHashSet(Arrays.asList("first1", "second1"))) + bean.myValues.put("b", LinkedHashSet(Arrays.asList("first2", "second2"))) + + doSerializerTest("\n" + " \n" + "", bean) + } + + companion object { + private val XML_PREFIX = "" + + private fun checkSmartSerialization(bean: Bean2, serialized: String) { + val serializer = SmartSerializer() + serializer.readExternal(bean, JDOMUtil.loadDocument(serialized).getRootElement()) + val serializedState = Element("Bean2") + serializer.writeExternal(bean, serializedState) + TestCase.assertEquals(serialized, JDOMUtil.writeElement(serializedState)) + } + + private fun doSerializerTest(Language("XML") expectedText: String, bean: T, filter: SerializationFilter? = null): T { + val element = assertSerializer(bean, expectedText, filter) + + //test deserializer + val o = XmlSerializer.deserialize(element, bean.javaClass) + assertSerializer(o, expectedText, filter, "Deserialization failure") + return o + } + + private fun assertSerializer(bean: Any, expected: String, filter: SerializationFilter?, description: String = "Serialization failure"): Element { + val element = XmlSerializer.serialize(bean, filter) + var actual = JDOMUtil.writeElement(element, "\n").trim() + if (!expected.startsWith(XML_PREFIX) && actual.startsWith(XML_PREFIX)) { + actual = actual.substring(XML_PREFIX.length()).trim() + } + + assertThat(actual).`as`(description).isEqualTo(expected) + return element + } + + private fun serialize(bean: Any, filter: SerializationFilter?) = XmlSerializer.serialize(bean, filter) + } +} \ No newline at end of file diff --git a/platform/util/util.iml b/platform/util/util.iml index 119eaca9e79c..e5b509a6f928 100644 --- a/platform/util/util.iml +++ b/platform/util/util.iml @@ -24,6 +24,8 @@ + +