diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..1b267076 --- /dev/null +++ b/.gitignore @@ -0,0 +1,166 @@ +# Created by .ignore support plugin (hsz.mobi) +### Windows template +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk +### Kotlin template +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +### Linux template +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/dictionaries + +# Sensitive or high-churn files: +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.xml +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml + +# Gradle: +.idea/**/gradle.xml +.idea/**/libraries + +# CMake +cmake-build-debug/ +cmake-build-release/ + +# Mongo Explorer plugin: +.idea/**/mongoSettings.xml + +## File-based project format: +*.iws + +## Plugin-specific files: + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties +### Java template +# Compiled class file +# Log file +# BlueJ files +# Mobile Tools for Java (J2ME) +# Package Files # +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +### Gradle template +.gradle +/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Cache of project +.gradletasknamecache + +# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 +# gradle/wrapper/gradle-wrapper.properties +### macOS template +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +/.idea/* +!/.idea/codeStyles + +target/ diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 00000000..c2c4bac3 --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 00000000..79ee123c --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index 9a64bf3c..93b7dce4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,19 +1,24 @@ +sudo: false language: java jdk: - - openjdk7 - oraclejdk8 -cache: - directories: - - $HOME/.m2 +script: + - ./gradlew check after_success: - - mvn cobertura:cobertura coveralls:report + - ./gradlew cobertura coveralls env: global: - secure: VowI35vSogCpbHhqkStwHdU3A9+0g3x3v4RiE6Ps6RH5Y4E0F5mD9MzrYloRGIWpbeLgw0azRVsM2nDufUIJgogWIOnxKxi4AqSo23VKcY6z/tN0kRgIfD+QuMbRmaUU6yIXaws3xjOXCHbLsBFBHeu0pGkB9e3qiMeJatj9bDo= + # Must also set COVERALLS_REPO_TOKEN env variable in Travis CI to push Coveralls reports -# use container -sudo: false +before_cache: + - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock + - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ +cache: + directories: + - $HOME/.gradle/caches/ + - $HOME/.gradle/wrapper/ diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..e494267b --- /dev/null +++ b/build.gradle @@ -0,0 +1,154 @@ +plugins { + id 'idea' + id 'java-library' + id 'maven-publish' + id 'findbugs' + id 'com.diffplug.gradle.spotless' version '3.8.0' + id 'com.github.ben-manes.versions' version '0.17.0' + id 'com.google.protobuf' version "0.8.4" + id 'net.saliman.cobertura' version '2.5.4' + id 'com.github.kt3k.coveralls' version '2.8.2' +} + +description = 'Additional Kryo serializers for standard JDK types (e.g. currency, JDK proxies) and some for external libs (e.g. joda time, cglib proxies, wicket)' + +sourceCompatibility = JavaVersion.VERSION_1_7 +targetCompatibility = JavaVersion.VERSION_1_7 + +cobertura { + coverageFormats = [ + 'html', + 'xml' + ] +} + +tasks.withType(FindBugs) { + reports { + xml.enabled false + html.enabled true + } +} + +findbugs { + effort = "max" + reportLevel = "high" + excludeFilter = file("findbugs-exclude.xml") +} + +task sourcesJar(type: Jar) { + from sourceSets.main.allJava + classifier 'sources' +} + +task javadocJar(type: Jar, dependsOn: javadoc) { + from javadoc.destinationDir + classifier 'javadoc' + + // Add support for new doc tags + (javadoc.options as CoreJavadocOptions).with { + addMultilineStringsOption("tag").setValue([ + "apiNote:a:API Note:", + "implSpec:a:Implementation Requirements:", + "implNote:a:Implementation Note:" + ]) + } +} +sourceSets.main.java.srcDirs 'build/generated/source/proto/main/java' +sourceSets.test.java.srcDirs 'build/generated/source/proto/test/java' + +compileJava { + // Disable warnings about Sun classes (ReflectionFactory). + options.compilerArgs += [ + "-XDignore.symbol.file", + "-Xlint:unchecked" + ] + options.fork = true + options.forkOptions.executable = 'javac' +} + +protobuf { protoc { artifact = 'com.google.protobuf:protoc:3.5.1-1' } } + +publishing { + publications { + maven(MavenPublication) { + (it as MavenPublication).with { + from components['java'] + + groupId 'de.javakaffee' + artifactId 'kryo-serializers' + version '0.43-SNAPSHOT' + + artifact sourcesJar + artifact javadocJar + } + } + } +} + +test { useTestNG() } + +repositories { jcenter() } + +ext.optionalDependencies = [ + 'com.google.protobuf:protobuf-java:3.5.1', + 'joda-time:joda-time:2.9.9', + 'cglib:cglib:3.2.6', + 'org.apache.wicket:wicket-core:8.0.0-M8', + 'com.google.guava:guava:21.0', + 'com.github.andrewoma.dexx:collection:0.7' +] + +dependencies { + api 'com.esotericsoftware:kryo:4.0.1' + compileOnly optionalDependencies + + // Testing + + testImplementation 'org.testng:testng:6.14.1' + testImplementation 'junit:junit:4.12' + + testImplementation optionalDependencies + + testImplementation 'javax.servlet:javax.servlet-api:4.0.0' + testImplementation 'org.slf4j:slf4j-simple:1.8.0-beta1' + testImplementation 'org.apache.commons:commons-lang3:3.7' +} + +spotless { + enforceCheck false + java { + it.with { + licenseHeaderFile 'spotless.license' + importOrderFile 'spotless.importorder' + eclipse().configFile 'spotless.eclipseformat.xml' + trimTrailingWhitespace() + removeUnusedImports() + endWithNewline() + + // Eclipse formatter removes whitespace in a for loop without an increment. + // for(int i = 0; i < 10;) // what Eclipse does + // for(int i = 0; i < 10; ) // what I wish Eclipse did + custom 'For loop fix', { it.replace(';)', '; )') } + + ignoreErrorForPath 'build/generated/source/proto/test/java/de/javakaffee/kryoserializers/protobuf/SampleProtoAOuterClass.java' + ignoreErrorForPath 'build/generated/source/proto/test/java/de/javakaffee/kryoserializers/protobuf/SampleProtoBOuterClass.java' + ignoreErrorForPath 'build\\generated\\source\\proto\\test\\java\\de\\javakaffee\\kryoserializers\\protobuf\\SampleProtoAOuterClass.java' + ignoreErrorForPath 'build\\generated\\source\\proto\\test\\java\\de\\javakaffee\\kryoserializers\\protobuf\\SampleProtoBOuterClass.java' + } + } + groovyGradle { + it.with { + greclipse().configFile('spotless.eclipseformat.xml', 'spotless.groovyformat.prefs') + } + } + freshmark { + it.with { + target '**/*.md' + propertiesFile('gradle.properties') + } + } +} + +afterEvaluate { + check.dependsOn(tasks['cobertura']) +} diff --git a/findbugs-exclude.xml b/findbugs-exclude.xml new file mode 100644 index 00000000..2b06f2bb --- /dev/null +++ b/findbugs-exclude.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 00000000..e69de29b diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..a5fe1cb9 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..610ad4c5 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.5-all.zip diff --git a/gradlew b/gradlew new file mode 100755 index 00000000..cccdd3d5 --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..f9553162 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/lib/kryo-1.03-sources.jar b/lib/kryo-1.03-sources.jar deleted file mode 100644 index 594023f4..00000000 Binary files a/lib/kryo-1.03-sources.jar and /dev/null differ diff --git a/lib/kryo-1.03.jar b/lib/kryo-1.03.jar deleted file mode 100644 index 847a06f3..00000000 Binary files a/lib/kryo-1.03.jar and /dev/null differ diff --git a/lib/minlog-1.2.jar b/lib/minlog-1.2.jar deleted file mode 100644 index 7cc55acf..00000000 Binary files a/lib/minlog-1.2.jar and /dev/null differ diff --git a/lib/reflectasm-0.9.jar b/lib/reflectasm-0.9.jar deleted file mode 100644 index 4cfb6242..00000000 Binary files a/lib/reflectasm-0.9.jar and /dev/null differ diff --git a/pom.xml b/pom.xml deleted file mode 100644 index 7e8dda8d..00000000 --- a/pom.xml +++ /dev/null @@ -1,277 +0,0 @@ - - 4.0.0 - - - - org.sonatype.oss - oss-parent - 7 - - - de.javakaffee - kryo-serializers - 0.43-SNAPSHOT - bundle - kryo serializers - - Additional kryo (http://kryo.googlecode.com) serializers for standard jdk types (e.g. currency, jdk proxies) and some for external libs (e.g. joda time, cglib proxies, wicket). - - https://github.com/magro/kryo-serializers - - - github.com - https://github.com/magro/kryo-serializers/issues - - 2010 - - 2.0.9 - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - scm:git:git@github.com:magro/kryo-serializers.git - scm:git:git@github.com:magro/kryo-serializers.git - git@github.com:magro/kryo-serializers.git - - - - martin.grotzke - Martin Grotzke - martin.grotzke@googlecode.com - - owner - developer - - +1 - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - true - - 1.6 - 1.6 - utf-8 - - - - - - - org.apache.felix - maven-bundle-plugin - 2.4.0 - true - - - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.10.3 - - - -Xdoclint:none - - - - org.codehaus.mojo - cobertura-maven-plugin - 2.7 - - - html - xml - - - - - org.eluder.coveralls - coveralls-maven-plugin - 4.1.0 - - - - - - true - - - maven-project-info-reports-plugin - 2.3.1 - - - sunlink - - javadoc - - true - - - http://download.oracle.com/javase/6/docs/api/ - - - - - - - org.apache.maven.plugins - maven-jxr-plugin - 2.2 - - - org.codehaus.mojo - findbugs-maven-plugin - 2.3.2 - - true - Normal - Max - de.javakaffee.kryoserializers.- - false - - - - - - - UTF-8 - 1.5.8 - - - - - - org.slf4j - slf4j-api - ${slf4j.version} - test - - - junit - junit - 4.7 - test - - - - - - - - com.esotericsoftware - kryo - 4.0.0 - - - com.google.protobuf - protobuf-java - 2.6.1 - true - - - joda-time - joda-time - 1.6.2 - true - - - cglib - cglib - 3.1 - true - - - org.apache.wicket - wicket - 1.4.17 - true - - - com.google.guava - guava - 17.0 - true - - - com.github.andrewoma.dexx - collection - 0.6 - true - - - - - org.testng - testng - 6.8.21 - test - - - - - junit - junit - test - - - - - javax.servlet - servlet-api - 2.5 - test - - - - org.slf4j - slf4j-simple - ${slf4j.version} - test - - - - commons-lang - commons-lang - 2.4 - test - - - - - - - jcenter - bintray - http://jcenter.bintray.com - - - - - diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 00000000..eeb11c19 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'kryo-serializers' diff --git a/spotless.eclipseformat.xml b/spotless.eclipseformat.xml new file mode 100644 index 00000000..f130329f --- /dev/null +++ b/spotless.eclipseformat.xml @@ -0,0 +1,419 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spotless.groovyformat.prefs b/spotless.groovyformat.prefs new file mode 100644 index 00000000..da2cb796 --- /dev/null +++ b/spotless.groovyformat.prefs @@ -0,0 +1,2 @@ +groovy.formatter.remove.unnecessary.semicolons=true +groovy.formatter.longListLength=1 \ No newline at end of file diff --git a/spotless.importorder b/spotless.importorder new file mode 100644 index 00000000..bd30f3bc --- /dev/null +++ b/spotless.importorder @@ -0,0 +1,7 @@ +#Organize Import Order +5= +4=de.javakaffee +3=com +2=org +1=javax +0=java diff --git a/spotless.license b/spotless.license new file mode 100644 index 00000000..6efa9db8 --- /dev/null +++ b/spotless.license @@ -0,0 +1,16 @@ +/* + * Copyright $YEAR Martin Grotzke + * + * 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. + * + */ diff --git a/src/main/java/de/javakaffee/kryoserializers/ArraysAsListSerializer.java b/src/main/java/de/javakaffee/kryoserializers/ArraysAsListSerializer.java index 180f9fa3..ef01d621 100644 --- a/src/main/java/de/javakaffee/kryoserializers/ArraysAsListSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/ArraysAsListSerializer.java @@ -16,16 +16,16 @@ */ package de.javakaffee.kryoserializers; -import com.esotericsoftware.kryo.Kryo; -import com.esotericsoftware.kryo.Serializer; -import com.esotericsoftware.kryo.io.Input; -import com.esotericsoftware.kryo.io.Output; - import java.lang.reflect.Array; import java.lang.reflect.Field; import java.util.Arrays; import java.util.List; +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.Serializer; +import com.esotericsoftware.kryo.io.Input; +import com.esotericsoftware.kryo.io.Output; + /** * A kryo {@link Serializer} for lists created via {@link Arrays#asList(Object...)}. *

@@ -37,86 +37,86 @@ */ public class ArraysAsListSerializer extends Serializer> { - private Field _arrayField; + private Field _arrayField; - public ArraysAsListSerializer() { - try { - _arrayField = Class.forName( "java.util.Arrays$ArrayList" ).getDeclaredField( "a" ); - _arrayField.setAccessible( true ); - } catch ( final Exception e ) { - throw new RuntimeException( e ); - } - } + public ArraysAsListSerializer() { + try { + _arrayField = Class.forName("java.util.Arrays$ArrayList").getDeclaredField("a"); + _arrayField.setAccessible(true); + } catch (final Exception e) { + throw new RuntimeException(e); + } + } - @Override - public List read(final Kryo kryo, final Input input, final Class> type) { - final int length = input.readInt(true); - Class componentType = kryo.readClass( input ).getType(); - if (componentType.isPrimitive()) { - componentType = getPrimitiveWrapperClass(componentType); - } - try { - final Object items = Array.newInstance( componentType, length ); - for( int i = 0; i < length; i++ ) { - Array.set(items, i, kryo.readClassAndObject( input )); - } - return Arrays.asList( (Object[])items ); - } catch ( final Exception e ) { - throw new RuntimeException( e ); - } - } + private static Class getPrimitiveWrapperClass(final Class c) { + if (c.isPrimitive()) { + if (c.equals(Long.TYPE)) { + return Long.class; + } else if (c.equals(Integer.TYPE)) { + return Integer.class; + } else if (c.equals(Double.TYPE)) { + return Double.class; + } else if (c.equals(Float.TYPE)) { + return Float.class; + } else if (c.equals(Boolean.TYPE)) { + return Boolean.class; + } else if (c.equals(Character.TYPE)) { + return Character.class; + } else if (c.equals(Short.TYPE)) { + return Short.class; + } else if (c.equals(Byte.TYPE)) { + return Byte.class; + } + } + return c; + } - @Override - public void write(final Kryo kryo, final Output output, final List obj) { - try { - final Object[] array = (Object[]) _arrayField.get( obj ); - output.writeInt(array.length, true); - final Class componentType = array.getClass().getComponentType(); - kryo.writeClass( output, componentType ); - for( final Object item : array ) { - kryo.writeClassAndObject( output, item ); - } - } catch ( final RuntimeException e ) { - // Don't eat and wrap RuntimeExceptions because the ObjectBuffer.write... - // handles SerializationException specifically (resizing the buffer)... - throw e; - } catch ( final Exception e ) { - throw new RuntimeException( e ); - } - } + @Override + public List read(final Kryo kryo, final Input input, final Class> type) { + final int length = input.readInt(true); + Class componentType = kryo.readClass(input).getType(); + if (componentType.isPrimitive()) { + componentType = getPrimitiveWrapperClass(componentType); + } + try { + final Object items = Array.newInstance(componentType, length); + for (int i = 0; i < length; i++) { + Array.set(items, i, kryo.readClassAndObject(input)); + } + return Arrays.asList((Object[]) items); + } catch (final Exception e) { + throw new RuntimeException(e); + } + } - @Override - public List copy(Kryo kryo, List original) { - try { - final Object[] array = (Object[]) _arrayField.get(original); - kryo.reference(array); - Object[] arrayCopy = kryo.copy(array); - return Arrays.asList(arrayCopy); - } catch (final Exception e) { - throw new RuntimeException(e); - } - } + @Override + public void write(final Kryo kryo, final Output output, final List obj) { + try { + final Object[] array = (Object[]) _arrayField.get(obj); + output.writeInt(array.length, true); + final Class componentType = array.getClass().getComponentType(); + kryo.writeClass(output, componentType); + for (final Object item : array) { + kryo.writeClassAndObject(output, item); + } + } catch (final RuntimeException e) { + // Don't eat and wrap RuntimeExceptions because the ObjectBuffer.write... + // handles SerializationException specifically (resizing the buffer)... + throw e; + } catch (final Exception e) { + throw new RuntimeException(e); + } + } - private static Class getPrimitiveWrapperClass(final Class c) { - if (c.isPrimitive()) { - if (c.equals(Long.TYPE)) { - return Long.class; - } else if (c.equals(Integer.TYPE)) { - return Integer.class; - } else if (c.equals(Double.TYPE)) { - return Double.class; - } else if (c.equals(Float.TYPE)) { - return Float.class; - } else if (c.equals(Boolean.TYPE)) { - return Boolean.class; - } else if (c.equals(Character.TYPE)) { - return Character.class; - } else if (c.equals(Short.TYPE)) { - return Short.class; - } else if (c.equals(Byte.TYPE)) { - return Byte.class; - } - } - return c; - } + @Override + public List copy(Kryo kryo, List original) { + try { + final Object[] array = (Object[]) _arrayField.get(original); + kryo.reference(array); + Object[] arrayCopy = kryo.copy(array); + return Arrays.asList(arrayCopy); + } catch (final Exception e) { + throw new RuntimeException(e); + } + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/BitSetSerializer.java b/src/main/java/de/javakaffee/kryoserializers/BitSetSerializer.java index ccfed98b..5f08db96 100644 --- a/src/main/java/de/javakaffee/kryoserializers/BitSetSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/BitSetSerializer.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers; import java.util.BitSet; @@ -9,36 +25,36 @@ public class BitSetSerializer extends Serializer { - @Override - public BitSet copy(final Kryo kryo, final BitSet original) { - final BitSet result = new BitSet(); - final int length = original.length(); - for(int i = 0; i < length; i++) { - result.set(i, original.get(i)); - } - return result; - } - - @Override - public void write(final Kryo kryo, final Output output, final BitSet bitSet) { - final int len = bitSet.length(); - - output.writeInt(len, true); - - for(int i = 0; i < len; i++) { - output.writeBoolean(bitSet.get(i)); - } - } - - @Override - public BitSet read(final Kryo kryo, final Input input, final Class bitSetClass) { - final int len = input.readInt(true); - final BitSet ret = new BitSet(len); - - for(int i = 0; i < len; i++) { - ret.set(i, input.readBoolean()); - } - - return ret; - } + @Override + public BitSet copy(final Kryo kryo, final BitSet original) { + final BitSet result = new BitSet(); + final int length = original.length(); + for (int i = 0; i < length; i++) { + result.set(i, original.get(i)); + } + return result; + } + + @Override + public void write(final Kryo kryo, final Output output, final BitSet bitSet) { + final int len = bitSet.length(); + + output.writeInt(len, true); + + for (int i = 0; i < len; i++) { + output.writeBoolean(bitSet.get(i)); + } + } + + @Override + public BitSet read(final Kryo kryo, final Input input, final Class bitSetClass) { + final int len = input.readInt(true); + final BitSet ret = new BitSet(len); + + for (int i = 0; i < len; i++) { + ret.set(i, input.readBoolean()); + } + + return ret; + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/CollectionsEmptyListSerializer.java b/src/main/java/de/javakaffee/kryoserializers/CollectionsEmptyListSerializer.java index 28ef37f9..a9cdb4ff 100644 --- a/src/main/java/de/javakaffee/kryoserializers/CollectionsEmptyListSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/CollectionsEmptyListSerializer.java @@ -27,21 +27,21 @@ /** * A kryo {@link Serializer} for {@link List}s created via {@link Collections#emptyList()} * or that were just assigned the {@link Collections#EMPTY_LIST}. - * + * * @author Martin Grotzke */ public class CollectionsEmptyListSerializer extends Serializer> { - public CollectionsEmptyListSerializer() { - setImmutable(true); - } + public CollectionsEmptyListSerializer() { + setImmutable(true); + } - @Override - public List read(final Kryo kryo, final Input input, final Class> type) { - return Collections.EMPTY_LIST; - } + @Override + public List read(final Kryo kryo, final Input input, final Class> type) { + return Collections.EMPTY_LIST; + } - @Override - public void write(final Kryo kryo, final Output output, final List object) { - } + @Override + public void write(final Kryo kryo, final Output output, final List object) { + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/CollectionsEmptyMapSerializer.java b/src/main/java/de/javakaffee/kryoserializers/CollectionsEmptyMapSerializer.java index 1a121103..8cc7b0ee 100644 --- a/src/main/java/de/javakaffee/kryoserializers/CollectionsEmptyMapSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/CollectionsEmptyMapSerializer.java @@ -27,21 +27,21 @@ /** * A kryo {@link Serializer} for {@link Map}s created via {@link Collections#emptyMap()} * or that were just assigned the {@link Collections#EMPTY_MAP}. - * + * * @author Martin Grotzke */ public class CollectionsEmptyMapSerializer extends Serializer> { - public CollectionsEmptyMapSerializer() { - setImmutable(true); - } + public CollectionsEmptyMapSerializer() { + setImmutable(true); + } - @Override - public Map read(final Kryo kryo, final Input input, final Class> type) { - return Collections.EMPTY_MAP; - } + @Override + public Map read(final Kryo kryo, final Input input, final Class> type) { + return Collections.EMPTY_MAP; + } - @Override - public void write(final Kryo kryo, final Output output, final Map object) { - } + @Override + public void write(final Kryo kryo, final Output output, final Map object) { + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/CollectionsEmptySetSerializer.java b/src/main/java/de/javakaffee/kryoserializers/CollectionsEmptySetSerializer.java index 77003075..20a6eb3d 100644 --- a/src/main/java/de/javakaffee/kryoserializers/CollectionsEmptySetSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/CollectionsEmptySetSerializer.java @@ -28,21 +28,21 @@ /** * A kryo {@link Serializer} for {@link Map}s created via {@link Collections#emptySet()} * or that were just assigned the {@link Collections#EMPTY_SET}. - * + * * @author Martin Grotzke */ public class CollectionsEmptySetSerializer extends Serializer> { - public CollectionsEmptySetSerializer() { - setImmutable(true); - } + public CollectionsEmptySetSerializer() { + setImmutable(true); + } - @Override - public Set read(final Kryo kryo, final Input input, final Class> type) { - return Collections.EMPTY_SET; - } + @Override + public Set read(final Kryo kryo, final Input input, final Class> type) { + return Collections.EMPTY_SET; + } - @Override - public void write(final Kryo kryo, final Output output, final Set object) { - } + @Override + public void write(final Kryo kryo, final Output output, final Set object) { + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/CollectionsSingletonListSerializer.java b/src/main/java/de/javakaffee/kryoserializers/CollectionsSingletonListSerializer.java index 188afd56..8c012a24 100644 --- a/src/main/java/de/javakaffee/kryoserializers/CollectionsSingletonListSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/CollectionsSingletonListSerializer.java @@ -16,44 +16,44 @@ */ package de.javakaffee.kryoserializers; +import java.util.Collections; +import java.util.List; + import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; -import java.util.Collections; -import java.util.List; - /** * A kryo {@link Serializer} for {@link List}s created via {@link Collections#singletonList(Object)}. *

* Note: This serializer does not support cyclic references, if a serialized object * is part of a cycle this might cause an error during deserialization. *

- * + * * @author Martin Grotzke */ public class CollectionsSingletonListSerializer extends Serializer> { - public CollectionsSingletonListSerializer() { - } + public CollectionsSingletonListSerializer() { + } - @Override - public List read(final Kryo kryo, final Input input, final Class> type) { - final Object obj = kryo.readClassAndObject( input ); - return Collections.singletonList( obj ); - } + @Override + public List read(final Kryo kryo, final Input input, final Class> type) { + final Object obj = kryo.readClassAndObject(input); + return Collections.singletonList(obj); + } - @Override - public void write(final Kryo kryo, final Output output, final List list) { - kryo.writeClassAndObject(output, list.get( 0 )); - } + @Override + public void write(final Kryo kryo, final Output output, final List list) { + kryo.writeClassAndObject(output, list.get(0)); + } - @Override - public List copy(Kryo kryo, List original) { - Object singleton = original.get(0); - kryo.reference(singleton); - Object newSingleton = kryo.copy(singleton); - return Collections.singletonList(newSingleton); - } + @Override + public List copy(Kryo kryo, List original) { + Object singleton = original.get(0); + kryo.reference(singleton); + Object newSingleton = kryo.copy(singleton); + return Collections.singletonList(newSingleton); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/CollectionsSingletonMapSerializer.java b/src/main/java/de/javakaffee/kryoserializers/CollectionsSingletonMapSerializer.java index 02de1b06..1722228b 100644 --- a/src/main/java/de/javakaffee/kryoserializers/CollectionsSingletonMapSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/CollectionsSingletonMapSerializer.java @@ -32,28 +32,27 @@ * Note: This serializer does not support cyclic references, if a serialized object * is part of a cycle this might cause an error during deserialization. *

- * + * * @author Martin Grotzke */ public class CollectionsSingletonMapSerializer extends Serializer> { - public CollectionsSingletonMapSerializer() { - setImmutable(true); - } - - @Override - public Map read(final Kryo kryo, final Input input, final Class> type) { - final Object key = kryo.readClassAndObject( input ); - final Object value = kryo.readClassAndObject( input ); - return Collections.singletonMap( key, value ); - } - - @Override - public void write(final Kryo kryo, final Output output, final Map map) { - final Entry entry = map.entrySet().iterator().next(); - kryo.writeClassAndObject( output, entry.getKey() ); - kryo.writeClassAndObject( output, entry.getValue() ); - } - + public CollectionsSingletonMapSerializer() { + setImmutable(true); + } + + @Override + public Map read(final Kryo kryo, final Input input, final Class> type) { + final Object key = kryo.readClassAndObject(input); + final Object value = kryo.readClassAndObject(input); + return Collections.singletonMap(key, value); + } + + @Override + public void write(final Kryo kryo, final Output output, final Map map) { + final Entry entry = map.entrySet().iterator().next(); + kryo.writeClassAndObject(output, entry.getKey()); + kryo.writeClassAndObject(output, entry.getValue()); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/CollectionsSingletonSetSerializer.java b/src/main/java/de/javakaffee/kryoserializers/CollectionsSingletonSetSerializer.java index d18cca75..60793b72 100644 --- a/src/main/java/de/javakaffee/kryoserializers/CollectionsSingletonSetSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/CollectionsSingletonSetSerializer.java @@ -31,23 +31,23 @@ * Note: This serializer does not support cyclic references, if a serialized object * is part of a cycle this might cause an error during deserialization. *

- * + * * @author Martin Grotzke */ public class CollectionsSingletonSetSerializer extends Serializer> { - public CollectionsSingletonSetSerializer() { - setImmutable(true); - } + public CollectionsSingletonSetSerializer() { + setImmutable(true); + } - @Override - public Set read(final Kryo kryo, final Input input, final Class> type) { - final Object obj = kryo.readClassAndObject( input ); - return Collections.singleton( obj ); - } + @Override + public Set read(final Kryo kryo, final Input input, final Class> type) { + final Object obj = kryo.readClassAndObject(input); + return Collections.singleton(obj); + } - @Override - public void write(final Kryo kryo, final Output output, final Set set) { - kryo.writeClassAndObject( output, set.iterator().next() ); - } + @Override + public void write(final Kryo kryo, final Output output, final Set set) { + kryo.writeClassAndObject(output, set.iterator().next()); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/CompatibleFieldSerializerReflectionFactorySupport.java b/src/main/java/de/javakaffee/kryoserializers/CompatibleFieldSerializerReflectionFactorySupport.java index 5d7b1671..6f765390 100644 --- a/src/main/java/de/javakaffee/kryoserializers/CompatibleFieldSerializerReflectionFactorySupport.java +++ b/src/main/java/de/javakaffee/kryoserializers/CompatibleFieldSerializerReflectionFactorySupport.java @@ -24,25 +24,26 @@ * A {@link CompatibleFieldSerializer} specialization that uses sun's {@link sun.reflect.ReflectionFactory} to create * new instances for classes without a default constructor (via reuse of * {@link KryoReflectionFactorySupport#newInstanceFromReflectionFactory(Class)}). - * + * * @author Martin Grotzke */ @SuppressWarnings("restriction") public class CompatibleFieldSerializerReflectionFactorySupport extends CompatibleFieldSerializer { - /** - * Creates a new instance. - * @param kryo the kryo instance that is passed to {@link CompatibleFieldSerializer#CompatibleFieldSerializer(Kryo, Class)}. - * @param type the type to serialize. - */ - public CompatibleFieldSerializerReflectionFactorySupport(final Kryo kryo, final Class type) { - super( kryo, type ); - } - - @SuppressWarnings("unchecked") - @Override - public Object create(final Kryo kryo, final Input input, @SuppressWarnings("rawtypes") final Class type) { - return KryoReflectionFactorySupport.newInstanceFromReflectionFactory( type ); - } - -} \ No newline at end of file + /** + * Creates a new instance. + * + * @param kryo the kryo instance that is passed to {@link CompatibleFieldSerializer#CompatibleFieldSerializer(Kryo, Class)}. + * @param type the type to serialize. + */ + public CompatibleFieldSerializerReflectionFactorySupport(final Kryo kryo, final Class type) { + super(kryo, type); + } + + @SuppressWarnings("unchecked") + @Override + public Object create(final Kryo kryo, final Input input, @SuppressWarnings("rawtypes") final Class type) { + return KryoReflectionFactorySupport.newInstanceFromReflectionFactory(type); + } + +} diff --git a/src/main/java/de/javakaffee/kryoserializers/CopyForIterateCollectionSerializer.java b/src/main/java/de/javakaffee/kryoserializers/CopyForIterateCollectionSerializer.java index b2575822..7167c336 100644 --- a/src/main/java/de/javakaffee/kryoserializers/CopyForIterateCollectionSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/CopyForIterateCollectionSerializer.java @@ -32,15 +32,15 @@ * of concurrent modification exceptions, as even during taking the copy the * collection might be modified by another thread. *

- * + * * @author Martin Grotzke */ public class CopyForIterateCollectionSerializer extends CollectionSerializer { - - @SuppressWarnings("unchecked") - @Override - public void write( final Kryo kryo, final Output output, @SuppressWarnings("rawtypes") final Collection object ) { - super.write( kryo, output, new ArrayList(object)); - } + + @SuppressWarnings("unchecked") + @Override + public void write(final Kryo kryo, final Output output, @SuppressWarnings("rawtypes") final Collection object) { + super.write(kryo, output, new ArrayList(object)); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/CopyForIterateMapSerializer.java b/src/main/java/de/javakaffee/kryoserializers/CopyForIterateMapSerializer.java index 06474ad4..42f7c0c4 100644 --- a/src/main/java/de/javakaffee/kryoserializers/CopyForIterateMapSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/CopyForIterateMapSerializer.java @@ -33,24 +33,23 @@ * of concurrent modification exceptions, as even during taking the copy the * map might be modified by another thread. *

- * + * * @author Martin Grotzke */ public class CopyForIterateMapSerializer extends MapSerializer { - - @SuppressWarnings("unchecked") - @Override - public void write( final Kryo kryo, final Output output, @SuppressWarnings("rawtypes") final Map object ) { - final Map map; - // we only need special support for linked hash map, as SortedMaps will - // recreate correct sorting during deserialization... - if ( object instanceof LinkedHashMap ) { - map = new LinkedHashMap( object ); - } - else { - map = new HashMap( object ); - } - super.write( kryo, output, map ); - } + + @SuppressWarnings("unchecked") + @Override + public void write(final Kryo kryo, final Output output, @SuppressWarnings("rawtypes") final Map object) { + final Map map; + // we only need special support for linked hash map, as SortedMaps will + // recreate correct sorting during deserialization... + if (object instanceof LinkedHashMap) { + map = new LinkedHashMap(object); + } else { + map = new HashMap(object); + } + super.write(kryo, output, map); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/DateSerializer.java b/src/main/java/de/javakaffee/kryoserializers/DateSerializer.java index a021de41..147f21ba 100644 --- a/src/main/java/de/javakaffee/kryoserializers/DateSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/DateSerializer.java @@ -26,54 +26,54 @@ /** * A kryo {@link Serializer} for {@link Date} and subclasses. Must be registered like this: - *
- *  Kryo kryo = new Kryo() {
- *      public Serializer getDefaultSerializer(final Class clazz) {
- *          if ( Date.class.isAssignableFrom( type ) ) {
- *              return new DateSerializer( type );
- *          }
- *          return super.getDefaultSerializer( clazz );
- *      }
- *  };
- * 
- * + *
+ * Kryo kryo = new Kryo() {
+ *     public Serializer<?> getDefaultSerializer(final Class clazz) {
+ *         if ( Date.class.isAssignableFrom( type ) ) {
+ *             return new DateSerializer( type );
+ *         }
+ *         return super.getDefaultSerializer( clazz );
+ *     }
+ * };
+ * 
+ * * @author Martin Grotzke */ public class DateSerializer extends Serializer { - private final Constructor _constructor; + private final Constructor _constructor; - public DateSerializer(final Class clazz) { - try { - _constructor = clazz.getConstructor(long.class); - } catch ( final Exception e ) { - throw new RuntimeException( e ); - } - } + public DateSerializer(final Class clazz) { + try { + _constructor = clazz.getConstructor(long.class); + } catch (final Exception e) { + throw new RuntimeException(e); + } + } - /** - * {@inheritDoc} - */ - @Override - public Date read(final Kryo kryo, final Input input, final Class type) { - try { - return _constructor.newInstance(input.readLong(true)); - } catch (final Exception e) { - throw new RuntimeException( e ); - } - } + /** + * {@inheritDoc} + */ + @Override + public Date read(final Kryo kryo, final Input input, final Class type) { + try { + return _constructor.newInstance(input.readLong(true)); + } catch (final Exception e) { + throw new RuntimeException(e); + } + } - /** - * {@inheritDoc} - */ - @Override - public void write(final Kryo kryo, final Output output, final Date obj) { - output.writeLong(obj.getTime(), true); - } + /** + * {@inheritDoc} + */ + @Override + public void write(final Kryo kryo, final Output output, final Date obj) { + output.writeLong(obj.getTime(), true); + } - @Override - public Date copy(final Kryo kryo, final Date original) { - return (Date) original.clone(); - } + @Override + public Date copy(final Kryo kryo, final Date original) { + return (Date) original.clone(); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/EnumMapSerializer.java b/src/main/java/de/javakaffee/kryoserializers/EnumMapSerializer.java index d5410c22..b7c2e51f 100644 --- a/src/main/java/de/javakaffee/kryoserializers/EnumMapSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/EnumMapSerializer.java @@ -30,81 +30,81 @@ /** * A serializer for {@link EnumMap}s. - * + * * @author Martin Grotzke */ public class EnumMapSerializer extends Serializer, ?>> { - - private static final Field TYPE_FIELD; - - static { - try { - TYPE_FIELD = EnumMap.class.getDeclaredField( "keyType" ); - TYPE_FIELD.setAccessible( true ); - } catch ( final Exception e ) { - throw new RuntimeException( "The EnumMap class seems to have changed, could not access expected field.", e ); - } - } - // Workaround reference reading, this should be removed sometimes. See also - // https://groups.google.com/d/msg/kryo-users/Eu5V4bxCfws/k-8UQ22y59AJ - private static final Object FAKE_REFERENCE = new Object(); + private static final Field TYPE_FIELD; + // Workaround reference reading, this should be removed sometimes. See also + // https://groups.google.com/d/msg/kryo-users/Eu5V4bxCfws/k-8UQ22y59AJ + private static final Object FAKE_REFERENCE = new Object(); + + static { + try { + TYPE_FIELD = EnumMap.class.getDeclaredField("keyType"); + TYPE_FIELD.setAccessible(true); + } catch (final Exception e) { + throw new RuntimeException("The EnumMap class seems to have changed, could not access expected field.", e); + } + } + + @Override + @SuppressWarnings({ "unchecked", "rawtypes" }) + public EnumMap, ?> copy(final Kryo kryo, final EnumMap, ?> original) { + // Make a shallow copy to copy the private key type of the original map without using reflection. + // This will work for empty original maps as well. + final EnumMap copy = new EnumMap(original); + for (final Map.Entry entry : original.entrySet()) { + copy.put((Enum) entry.getKey(), kryo.copy(entry.getValue())); + } + return copy; + } - @Override - @SuppressWarnings({"unchecked", "rawtypes"}) - public EnumMap, ?> copy(final Kryo kryo, final EnumMap, ?> original) { - // Make a shallow copy to copy the private key type of the original map without using reflection. - // This will work for empty original maps as well. - final EnumMap copy = new EnumMap(original); - for (final Map.Entry entry : original.entrySet()) { - copy.put((Enum)entry.getKey(), kryo.copy(entry.getValue())); - } - return copy; - } + @SuppressWarnings({ "unchecked", "rawtypes" }) + private EnumMap, ?> create(final Kryo kryo, final Input input, + final Class, ?>> type) { + final Class> keyType = kryo.readClass(input).getType(); + return new EnumMap(keyType); + } - @SuppressWarnings( { "unchecked", "rawtypes" } ) - private EnumMap, ?> create(final Kryo kryo, final Input input, - final Class, ?>> type) { - final Class> keyType = kryo.readClass( input ).getType(); - return new EnumMap( keyType ); - } - - @Override - @SuppressWarnings({ "rawtypes", "unchecked" }) - public EnumMap, ?> read(final Kryo kryo, final Input input, - final Class, ?>> type) { - kryo.reference(FAKE_REFERENCE); - final EnumMap, ?> result = create(kryo, input, type); - final Class> keyType = getKeyType( result ); - final Enum[] enumConstants = keyType.getEnumConstants(); - final EnumMap rawResult = result; - final int size = input.readInt(true); - for ( int i = 0; i < size; i++ ) { - final int ordinal = input.readInt(true); - final Enum key = enumConstants[ordinal]; - final Object value = kryo.readClassAndObject( input ); - rawResult.put( key, value ); - } - return result; - } + @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) + public EnumMap, ?> read(final Kryo kryo, final Input input, + final Class, ?>> type) { + kryo.reference(FAKE_REFERENCE); + final EnumMap, ?> result = create(kryo, input, type); + final Class> keyType = getKeyType(result); + final Enum[] enumConstants = keyType.getEnumConstants(); + final EnumMap rawResult = result; + final int size = input.readInt(true); + for (int i = 0; i < size; i++) { + final int ordinal = input.readInt(true); + final Enum key = enumConstants[ordinal]; + final Object value = kryo.readClassAndObject(input); + rawResult.put(key, value); + } + return result; + } - @Override - public void write(final Kryo kryo, final Output output, final EnumMap, ?> map) { - kryo.writeClass( output, getKeyType( map ) ); - output.writeInt(map.size(), true); - for ( final Map.Entry,?> entry : map.entrySet() ) { - output.writeInt(entry.getKey().ordinal(), true); - kryo.writeClassAndObject(output, entry.getValue()); - } - if ( TRACE ) trace( "kryo", "Wrote EnumMap: " + map ); - } + @Override + public void write(final Kryo kryo, final Output output, final EnumMap, ?> map) { + kryo.writeClass(output, getKeyType(map)); + output.writeInt(map.size(), true); + for (final Map.Entry, ?> entry : map.entrySet()) { + output.writeInt(entry.getKey().ordinal(), true); + kryo.writeClassAndObject(output, entry.getValue()); + } + if (TRACE) + trace("kryo", "Wrote EnumMap: " + map); + } - @SuppressWarnings("unchecked") - private Class> getKeyType( final EnumMap map ) { - try { - return (Class>)TYPE_FIELD.get( map ); - } catch ( final Exception e ) { - throw new RuntimeException( "Could not access keys field.", e ); - } - } + @SuppressWarnings("unchecked") + private Class> getKeyType(final EnumMap map) { + try { + return (Class>) TYPE_FIELD.get(map); + } catch (final Exception e) { + throw new RuntimeException("Could not access keys field.", e); + } + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/EnumSetSerializer.java b/src/main/java/de/javakaffee/kryoserializers/EnumSetSerializer.java index deda81d6..8f0fae26 100644 --- a/src/main/java/de/javakaffee/kryoserializers/EnumSetSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/EnumSetSerializer.java @@ -29,56 +29,57 @@ /** * A serializer for {@link EnumSet}s. - * + * * @author Martin Grotzke */ -@SuppressWarnings( { "unchecked", "rawtypes" } ) +@SuppressWarnings({ "unchecked", "rawtypes" }) public class EnumSetSerializer extends Serializer>> { - - private static final Field TYPE_FIELD; - - static { - try { - TYPE_FIELD = EnumSet.class.getDeclaredField( "elementType" ); - TYPE_FIELD.setAccessible( true ); - } catch ( final Exception e ) { - throw new RuntimeException( "The EnumSet class seems to have changed, could not access expected field.", e ); - } - } - @Override - public EnumSet> copy (final Kryo kryo, final EnumSet> original) { - return original.clone(); - } + private static final Field TYPE_FIELD; + + static { + try { + TYPE_FIELD = EnumSet.class.getDeclaredField("elementType"); + TYPE_FIELD.setAccessible(true); + } catch (final Exception e) { + throw new RuntimeException("The EnumSet class seems to have changed, could not access expected field.", e); + } + } + + @Override + public EnumSet> copy(final Kryo kryo, final EnumSet> original) { + return original.clone(); + } - @Override - public EnumSet read(final Kryo kryo, final Input input, final Class>> type) { - final Class elementType = kryo.readClass( input ).getType(); - final EnumSet result = EnumSet.noneOf( elementType ); - final int size = input.readInt(true); - final Enum[] enumConstants = elementType.getEnumConstants(); - for ( int i = 0; i < size; i++ ) { - result.add( enumConstants[input.readInt(true)] ); - } - return result; - } + @Override + public EnumSet read(final Kryo kryo, final Input input, final Class>> type) { + final Class elementType = kryo.readClass(input).getType(); + final EnumSet result = EnumSet.noneOf(elementType); + final int size = input.readInt(true); + final Enum[] enumConstants = elementType.getEnumConstants(); + for (int i = 0; i < size; i++) { + result.add(enumConstants[input.readInt(true)]); + } + return result; + } - @Override - public void write(final Kryo kryo, final Output output, final EnumSet> set) { - kryo.writeClass( output, getElementType( set ) ); - output.writeInt( set.size(), true ); - for (final Enum item : set) { - output.writeInt(item.ordinal(), true); - } + @Override + public void write(final Kryo kryo, final Output output, final EnumSet> set) { + kryo.writeClass(output, getElementType(set)); + output.writeInt(set.size(), true); + for (final Enum item : set) { + output.writeInt(item.ordinal(), true); + } - if ( TRACE ) trace( "kryo", "Wrote EnumSet: " + set ); - } + if (TRACE) + trace("kryo", "Wrote EnumSet: " + set); + } - private Class> getElementType( final EnumSet> set ) { - try { - return (Class)TYPE_FIELD.get( set ); - } catch ( final Exception e ) { - throw new RuntimeException( "Could not access keys field.", e ); - } - } + private Class> getElementType(final EnumSet> set) { + try { + return (Class) TYPE_FIELD.get(set); + } catch (final Exception e) { + throw new RuntimeException("Could not access keys field.", e); + } + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/FieldAnnotationAwareSerializer.java b/src/main/java/de/javakaffee/kryoserializers/FieldAnnotationAwareSerializer.java index c7373fcc..2f5a62fa 100644 --- a/src/main/java/de/javakaffee/kryoserializers/FieldAnnotationAwareSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/FieldAnnotationAwareSerializer.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers; import static com.esotericsoftware.minlog.Log.TRACE; @@ -18,7 +34,6 @@ * A kryo {@link FieldSerializer} that allows to exclusively include or exclude fields that * are attributed with user-specific annotations. This can be for example useful when serializing beans that carry * references to a dependency injection framework. As an example for Spring: - *

*

  * {@code
  * Set> marks = new HashSet<>();
@@ -28,10 +43,10 @@
  * kryo.setDefaultSerializer(factory);
  * }
  * 
- *

+ *

* The resulting {@link Kryo} instance would ignore all fields that are annotated with Spring's {@code @Autowired} * annotation. - *

+ *

* Similarly, it is possible to created a serializer which does the opposite such that the resulting serializer * would only serialize fields that are annotated with the specified annotations. * @@ -40,150 +55,148 @@ */ public class FieldAnnotationAwareSerializer extends FieldSerializer { - /** - * A factory for creating instances of {@link FieldAnnotationAwareSerializer}. - */ - public static class Factory implements SerializerFactory { - - private final Collection> marked; - private final boolean disregarding; - - /** - * Creates a new factory. See {@link FieldAnnotationAwareSerializer#FieldAnnotationAwareSerializer( - *com.esotericsoftware.kryo.Kryo, Class, java.util.Collection, boolean)} - * for additional information on the constructor parameters. - * - * @param marked The annotations that will be considered of the resulting converter. - * @param disregarding If {@code true}, the serializer will ignore all annotated fields, - * if set to {@code false} it will exclusively look at annotated fields. - */ - public Factory(final Collection> marked, final boolean disregarding) { - this.marked = marked; - this.disregarding = disregarding; - } - - @Override - public Serializer makeSerializer(final Kryo kryo, final Class type) { - return new FieldAnnotationAwareSerializer(kryo, type, marked, disregarding); - } - } - - private final Set> marked; - - /** - * Determines whether annotated fields should be excluded from serialization. - *

- * {@code true} if annotated fields should be excluded from serialization, - * {@code false} if only annotated fields should be included from serialization. - */ - private final boolean disregarding; - - /** - * Creates a new field annotation aware serializer. - * - * @param kryo The {@link Kryo} instace. - * @param type The type of the class being serialized. - * @param marked The annotations this serializer considers for its serialization process. Be aware tha - * a serializer with {@code disregarding} set to {@code false} will never be able to - * serialize fields that are not annotated with any of these annotations since it is not - * possible to add fields to a {@link FieldSerializer} once it is created. See the - * documentation to {@link FieldAnnotationAwareSerializer#addAnnotation(Class)} and - * {@link FieldAnnotationAwareSerializer#removeAnnotation(Class)} for further information. - * @param disregarding If {@code true}, the serializer will ignore all annotated fields, - * if set to {@code false} it will exclusively look at annotated fields. - */ - public FieldAnnotationAwareSerializer(final Kryo kryo, - final Class type, - final Collection> marked, - final boolean disregarding) { - super(kryo, type); - this.disregarding = disregarding; - this.marked = new HashSet>(marked); - rebuildCachedFields(); - } - - @Override - protected void rebuildCachedFields() { - // In order to avoid rebuilding the cached fields twice, the super constructor's call - // to this method will be suppressed. This can be done by a simple check of the initialization - // state of a property of this subclass. - if (marked == null) { - return; - } - super.rebuildCachedFields(); - removeFields(); - } - - private void removeFields() { - final CachedField[] cachedFields = getFields(); - for (final CachedField cachedField : cachedFields) { - final Field field = cachedField.getField(); - if (isRemove(field)) { - if (TRACE) { - trace("kryo", String.format("Ignoring field %s tag: %s", disregarding ? "without" : "with", cachedField)); - } - super.removeField(field.getName()); - } - } - } - - private boolean isRemove(final Field field) { - return !isMarked(field) ^ disregarding; - } - - private boolean isMarked(final Field field) { - for (final Annotation annotation : field.getAnnotations()) { - final Class annotationType = annotation.annotationType(); - if (marked.contains(annotationType)) { - return true; - } - } - return false; - } - - /** - * Adds an annotation to the annotations that are considered by this serializer. - *

- * Important: This will not have an effect if the serializer was configured - * to exclusively serialize annotated fields by setting {@code disregarding} to - * {@code false}. This is similar to the contract of this serializer's superclass - * {@link FieldSerializer} which does not allow to add fields that were formerly - * removed. If this was possible, instances that were serialized before this field - * was added could not longer be properly deserialized. In order to make this contract - * break explicit, you need to create a new instance of this serializer if you want to - * include new fields to a serializer that exclusively serializes annotated fields. - * - * @param clazz The annotation class to be added. - * @return {@code true} if the method call had an effect. - */ - public boolean addAnnotation(final Class clazz) { - if (disregarding && marked.add(clazz)) { - initializeCachedFields(); - return true; - } - return false; - } - - /** - * Removes an annotation to the annotations that are considered by this serializer. - *

- * Important: This will not have an effect if the serializer was configured - * to not serialize annotated fields by setting {@code disregarding} to - * {@code true}. This is similar to the contract of this serializer's superclass - * {@link FieldSerializer} which does not allow to add fields that were formerly - * removed. If this was possible, instances that were serialized before this field - * was added could not longer be properly deserialized. In order to make this contract - * break explicit, you need to create a new instance of this serializer if you want to - * include new fields to a serializer that ignores annotated fields for serialization. - * - * @param clazz The annotation class to be removed. - * @return {@code true} if the method call had an effect. - */ - public boolean removeAnnotation(final Class clazz) { - if (!disregarding && marked.remove(clazz)) { - initializeCachedFields(); - return true; - } - return false; - } -} \ No newline at end of file + private final Set> marked; + /** + * Determines whether annotated fields should be excluded from serialization. + *

+ * {@code true} if annotated fields should be excluded from serialization, + * {@code false} if only annotated fields should be included from serialization. + */ + private final boolean disregarding; + + /** + * Creates a new field annotation aware serializer. + * + * @param kryo The {@link Kryo} instace. + * @param type The type of the class being serialized. + * @param marked The annotations this serializer considers for its serialization process. Be aware tha + * a serializer with {@code disregarding} set to {@code false} will never be able to + * serialize fields that are not annotated with any of these annotations since it is not + * possible to add fields to a {@link FieldSerializer} once it is created. See the + * documentation to {@link FieldAnnotationAwareSerializer#addAnnotation(Class)} and + * {@link FieldAnnotationAwareSerializer#removeAnnotation(Class)} for further information. + * @param disregarding If {@code true}, the serializer will ignore all annotated fields, + * if set to {@code false} it will exclusively look at annotated fields. + */ + public FieldAnnotationAwareSerializer(final Kryo kryo, final Class type, + final Collection> marked, final boolean disregarding) { + super(kryo, type); + this.disregarding = disregarding; + this.marked = new HashSet<>(marked); + rebuildCachedFields(); + } + + @Override + protected void rebuildCachedFields() { + // In order to avoid rebuilding the cached fields twice, the super constructor's call + // to this method will be suppressed. This can be done by a simple check of the initialization + // state of a property of this subclass. + if (marked == null) { + return; + } + super.rebuildCachedFields(); + removeFields(); + } + + private void removeFields() { + final CachedField[] cachedFields = getFields(); + for (final CachedField cachedField : cachedFields) { + final Field field = cachedField.getField(); + if (isRemove(field)) { + if (TRACE) { + trace("kryo", + String.format("Ignoring field %s tag: %s", disregarding ? "without" : "with", cachedField)); + } + super.removeField(field.getName()); + } + } + } + + private boolean isRemove(final Field field) { + return !isMarked(field) ^ disregarding; + } + + private boolean isMarked(final Field field) { + for (final Annotation annotation : field.getAnnotations()) { + final Class annotationType = annotation.annotationType(); + if (marked.contains(annotationType)) { + return true; + } + } + return false; + } + + /** + * Adds an annotation to the annotations that are considered by this serializer. + *

+ * Important: This will not have an effect if the serializer was configured + * to exclusively serialize annotated fields by setting {@code disregarding} to + * {@code false}. This is similar to the contract of this serializer's superclass + * {@link FieldSerializer} which does not allow to add fields that were formerly + * removed. If this was possible, instances that were serialized before this field + * was added could not longer be properly deserialized. In order to make this contract + * break explicit, you need to create a new instance of this serializer if you want to + * include new fields to a serializer that exclusively serializes annotated fields. + * + * @param clazz The annotation class to be added. + * @return {@code true} if the method call had an effect. + */ + public boolean addAnnotation(final Class clazz) { + if (disregarding && marked.add(clazz)) { + initializeCachedFields(); + return true; + } + return false; + } + + /** + * Removes an annotation to the annotations that are considered by this serializer. + *

+ * Important: This will not have an effect if the serializer was configured + * to not serialize annotated fields by setting {@code disregarding} to + * {@code true}. This is similar to the contract of this serializer's superclass + * {@link FieldSerializer} which does not allow to add fields that were formerly + * removed. If this was possible, instances that were serialized before this field + * was added could not longer be properly deserialized. In order to make this contract + * break explicit, you need to create a new instance of this serializer if you want to + * include new fields to a serializer that ignores annotated fields for serialization. + * + * @param clazz The annotation class to be removed. + * @return {@code true} if the method call had an effect. + */ + public boolean removeAnnotation(final Class clazz) { + if (!disregarding && marked.remove(clazz)) { + initializeCachedFields(); + return true; + } + return false; + } + + /** + * A factory for creating instances of {@link FieldAnnotationAwareSerializer}. + */ + public static class Factory implements SerializerFactory { + + private final Collection> marked; + private final boolean disregarding; + + /** + * Creates a new factory. See {@link FieldAnnotationAwareSerializer#FieldAnnotationAwareSerializer( + *com.esotericsoftware.kryo.Kryo, Class, java.util.Collection, boolean)} + * for additional information on the constructor parameters. + * + * @param marked The annotations that will be considered of the resulting converter. + * @param disregarding If {@code true}, the serializer will ignore all annotated fields, + * if set to {@code false} it will exclusively look at annotated fields. + */ + public Factory(final Collection> marked, final boolean disregarding) { + this.marked = marked; + this.disregarding = disregarding; + } + + @Override + public Serializer makeSerializer(final Kryo kryo, final Class type) { + return new FieldAnnotationAwareSerializer(kryo, type, marked, disregarding); + } + } +} diff --git a/src/main/java/de/javakaffee/kryoserializers/GregorianCalendarSerializer.java b/src/main/java/de/javakaffee/kryoserializers/GregorianCalendarSerializer.java index a24693d6..ddcb53a9 100644 --- a/src/main/java/de/javakaffee/kryoserializers/GregorianCalendarSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/GregorianCalendarSerializer.java @@ -35,62 +35,62 @@ * (created via Calendar.getInstance(Locale.ENGLISH)) * would take 1323 byte, this one only takes 24 byte. *

- * + * * @author Martin Grotzke */ public class GregorianCalendarSerializer extends Serializer { - private final Field _zoneField; + private final Field _zoneField; + + public GregorianCalendarSerializer() { + try { + _zoneField = Calendar.class.getDeclaredField("zone"); + _zoneField.setAccessible(true); + } catch (final Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public GregorianCalendar read(final Kryo kryo, final Input input, final Class type) { + final Calendar result = GregorianCalendar.getInstance(); + + result.setTimeInMillis(input.readLong(true)); + result.setLenient(input.readBoolean()); + result.setFirstDayOfWeek(input.readInt(true)); + result.setMinimalDaysInFirstWeek(input.readInt(true)); + + /* check if we actually need to set the timezone, as + * TimeZone.getTimeZone is synchronized, so we might prevent this + */ + final String timeZoneId = input.readString(); + if (!getTimeZone(result).getID().equals(timeZoneId)) { + result.setTimeZone(TimeZone.getTimeZone(timeZoneId)); + } - public GregorianCalendarSerializer() { - try { - _zoneField = Calendar.class.getDeclaredField( "zone" ); - _zoneField.setAccessible( true ); - } catch ( final Exception e ) { - throw new RuntimeException( e ); - } - } + return (GregorianCalendar) result; + } - @Override - public GregorianCalendar read(final Kryo kryo, final Input input, final Class type) { - final Calendar result = GregorianCalendar.getInstance(); - - result.setTimeInMillis( input.readLong( true ) ); - result.setLenient( input.readBoolean() ); - result.setFirstDayOfWeek( input.readInt( true ) ); - result.setMinimalDaysInFirstWeek( input.readInt( true ) ); - - /* check if we actually need to set the timezone, as - * TimeZone.getTimeZone is synchronized, so we might prevent this - */ - final String timeZoneId = input.readString(); - if ( !getTimeZone( result ).getID().equals( timeZoneId ) ) { - result.setTimeZone( TimeZone.getTimeZone( timeZoneId ) ); - } - - return (GregorianCalendar) result; - } + @Override + public void write(final Kryo kryo, final Output output, final GregorianCalendar calendar) { + output.writeLong(calendar.getTimeInMillis(), true); + output.writeBoolean(calendar.isLenient()); + output.writeInt(calendar.getFirstDayOfWeek(), true); + output.writeInt(calendar.getMinimalDaysInFirstWeek(), true); + output.writeString(getTimeZone(calendar).getID()); + } - @Override - public void write(final Kryo kryo, final Output output, final GregorianCalendar calendar) { - output.writeLong( calendar.getTimeInMillis(), true ); - output.writeBoolean( calendar.isLenient() ); - output.writeInt( calendar.getFirstDayOfWeek(), true ); - output.writeInt( calendar.getMinimalDaysInFirstWeek(), true ); - output.writeString( getTimeZone( calendar ).getID() ); - } - - @Override - public GregorianCalendar copy(final Kryo kryo, final GregorianCalendar original) { - return (GregorianCalendar) original.clone(); - } + @Override + public GregorianCalendar copy(final Kryo kryo, final GregorianCalendar original) { + return (GregorianCalendar) original.clone(); + } - private TimeZone getTimeZone( final Calendar obj ) { - /* access the timezone via the field, to prevent cloning of the tz */ - try { - return (TimeZone) _zoneField.get( obj ); - } catch ( final Exception e ) { - throw new RuntimeException( e ); - } - } + private TimeZone getTimeZone(final Calendar obj) { + /* access the timezone via the field, to prevent cloning of the tz */ + try { + return (TimeZone) _zoneField.get(obj); + } catch (final Exception e) { + throw new RuntimeException(e); + } + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/JdkProxySerializer.java b/src/main/java/de/javakaffee/kryoserializers/JdkProxySerializer.java index f3c74432..0245b92f 100644 --- a/src/main/java/de/javakaffee/kryoserializers/JdkProxySerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/JdkProxySerializer.java @@ -26,36 +26,36 @@ /** * A serializer for jdk proxies (proxies created via java.lang.reflect.Proxy.newProxyInstance). - * + * * @author Martin Grotzke */ public class JdkProxySerializer extends Serializer { - @Override - public Object read(final Kryo kryo, final Input input, final Class type) { - final InvocationHandler invocationHandler = (InvocationHandler) kryo.readClassAndObject( input ); - final Class[] interfaces = kryo.readObject( input, Class[].class ); - final ClassLoader classLoader = kryo.getClassLoader(); - try { - return Proxy.newProxyInstance( classLoader, interfaces, invocationHandler ); - } catch( final RuntimeException e ) { - System.err.println( getClass().getName()+ ".read:\n" + - "Could not create proxy using classLoader " + classLoader + "," + - " have invocationhandler.classloader: " + invocationHandler.getClass().getClassLoader() + - " have contextclassloader: " + Thread.currentThread().getContextClassLoader() ); - throw e; - } - } + @Override + public Object read(final Kryo kryo, final Input input, final Class type) { + final InvocationHandler invocationHandler = (InvocationHandler) kryo.readClassAndObject(input); + final Class[] interfaces = kryo.readObject(input, Class[].class); + final ClassLoader classLoader = kryo.getClassLoader(); + try { + return Proxy.newProxyInstance(classLoader, interfaces, invocationHandler); + } catch (final RuntimeException e) { + System.err.println( + getClass().getName() + ".read:\n" + "Could not create proxy using classLoader " + classLoader + "," + + " have invocationhandler.classloader: " + invocationHandler.getClass().getClassLoader() + + " have contextclassloader: " + Thread.currentThread().getContextClassLoader()); + throw e; + } + } - @Override - public void write(final Kryo kryo, final Output output, final Object obj) { - kryo.writeClassAndObject( output, Proxy.getInvocationHandler( obj ) ); - kryo.writeObject( output, obj.getClass().getInterfaces() ); - } + @Override + public void write(final Kryo kryo, final Output output, final Object obj) { + kryo.writeClassAndObject(output, Proxy.getInvocationHandler(obj)); + kryo.writeObject(output, obj.getClass().getInterfaces()); + } - @Override - public Object copy(final Kryo kryo, final Object original) { - return Proxy.newProxyInstance( kryo.getClassLoader(), original.getClass().getInterfaces(), - Proxy.getInvocationHandler(original) ); - } + @Override + public Object copy(final Kryo kryo, final Object original) { + return Proxy.newProxyInstance(kryo.getClassLoader(), original.getClass().getInterfaces(), + Proxy.getInvocationHandler(original)); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/KryoReflectionFactorySupport.java b/src/main/java/de/javakaffee/kryoserializers/KryoReflectionFactorySupport.java index 4c20ed31..20f27d37 100644 --- a/src/main/java/de/javakaffee/kryoserializers/KryoReflectionFactorySupport.java +++ b/src/main/java/de/javakaffee/kryoserializers/KryoReflectionFactorySupport.java @@ -20,91 +20,95 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import sun.reflect.ReflectionFactory; - import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.serializers.FieldSerializer; +import sun.reflect.ReflectionFactory; + /** * A {@link Kryo} specialization that uses sun's {@link ReflectionFactory} to create * new instance for classes without a default constructor. - * + * * @author Martin Grotzke */ -@SuppressWarnings("restriction") +@SuppressWarnings({ "restriction", "sunapi" }) public class KryoReflectionFactorySupport extends Kryo { - private static final ReflectionFactory REFLECTION_FACTORY = ReflectionFactory.getReflectionFactory(); - private static final Object[] INITARGS = new Object[0]; - - private static final Map, Constructor> _constructors = new ConcurrentHashMap, Constructor>(); + private static final ReflectionFactory REFLECTION_FACTORY = ReflectionFactory.getReflectionFactory(); + private static final Object[] INITARGS = new Object[0]; + + private static final Map, Constructor> _constructors = + new ConcurrentHashMap, Constructor>(); + + private static Object newInstanceFrom(final Constructor constructor) { + try { + return constructor.newInstance(INITARGS); + } catch (final Exception e) { + throw new RuntimeException(e); + } + } - @Override - public Serializer getDefaultSerializer(@SuppressWarnings("rawtypes") final Class type) { - final Serializer result = super.getDefaultSerializer(type); - if(result instanceof FieldSerializer) { - // don't ignore synthetic fields so that inner classes work (see KryoTest.testInnerClass) - ((FieldSerializer) result).setIgnoreSyntheticFields(false); - } - return result; - } + @SuppressWarnings("unchecked") + public static T newInstanceFromReflectionFactory(final Class type) { + Constructor constructor = _constructors.get(type); + if (constructor == null) { + constructor = newConstructorForSerialization(type); + _constructors.put(type, constructor); + } + return (T) newInstanceFrom(constructor); + } - /** - * {@inheritDoc} - */ - @Override - @SuppressWarnings( "unchecked" ) - public T newInstance( final Class type ) { - if (type == null) { throw new IllegalArgumentException("type cannot be null."); } - Constructor constructor = _constructors.get( type ); - if ( constructor == null ) { - constructor = getNoArgsConstructor( type ); - if ( constructor == null ) { - constructor = newConstructorForSerialization( type ); - } - _constructors.put( type, constructor ); - } - return (T) newInstanceFrom( constructor ); - } + private static Constructor newConstructorForSerialization(final Class type) { + try { + final Constructor constructor = + REFLECTION_FACTORY.newConstructorForSerialization(type, Object.class.getDeclaredConstructor()); + constructor.setAccessible(true); + return constructor; + } catch (final Exception e) { + throw new RuntimeException(e); + } + } - private static Object newInstanceFrom( final Constructor constructor ) { - try { - return constructor.newInstance( INITARGS ); - } catch ( final Exception e ) { - throw new RuntimeException( e ); - } - } + private static Constructor getNoArgsConstructor(final Class type) { + final Constructor[] constructors = type.getConstructors(); + for (final Constructor constructor : constructors) { + if (constructor.getParameterTypes().length == 0) { + constructor.setAccessible(true); + return constructor; + } + } + return null; + } - @SuppressWarnings( "unchecked" ) - public static T newInstanceFromReflectionFactory( final Class type ) { - Constructor constructor = _constructors.get( type ); - if ( constructor == null ) { - constructor = newConstructorForSerialization( type ); - _constructors.put( type, constructor ); - } - return (T) newInstanceFrom( constructor ); - } + @Override + public Serializer getDefaultSerializer(@SuppressWarnings("rawtypes") final Class type) { + final Serializer result = super.getDefaultSerializer(type); + if (result instanceof FieldSerializer) { + // don't ignore synthetic fields so that inner classes work (see KryoTest.testInnerClass) + ((FieldSerializer) result).setIgnoreSyntheticFields(false); + } + return result; + } - private static Constructor newConstructorForSerialization( final Class type ) { - try { - final Constructor constructor = REFLECTION_FACTORY.newConstructorForSerialization( type, Object.class.getDeclaredConstructor( new Class[0] ) ); - constructor.setAccessible( true ); - return constructor; - } catch ( final Exception e ) { - throw new RuntimeException( e ); - } - } + /** + * {@inheritDoc} + */ + @Override + @SuppressWarnings("unchecked") + public T newInstance(final Class type) { + if (type == null) { + throw new IllegalArgumentException("type cannot be null."); + } + Constructor constructor = _constructors.get(type); + if (constructor == null) { + constructor = getNoArgsConstructor(type); + if (constructor == null) { + constructor = newConstructorForSerialization(type); + } + _constructors.put(type, constructor); + } + return (T) newInstanceFrom(constructor); + } - private static Constructor getNoArgsConstructor( final Class type ) { - final Constructor[] constructors = type.getConstructors(); - for ( final Constructor constructor : constructors ) { - if ( constructor.getParameterTypes().length == 0 ) { - constructor.setAccessible( true ); - return constructor; - } - } - return null; - } - -} \ No newline at end of file +} diff --git a/src/main/java/de/javakaffee/kryoserializers/RegexSerializer.java b/src/main/java/de/javakaffee/kryoserializers/RegexSerializer.java index a8857bb1..22e1cb14 100644 --- a/src/main/java/de/javakaffee/kryoserializers/RegexSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/RegexSerializer.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers; import java.util.regex.Pattern; @@ -9,26 +25,26 @@ /** * Kryo {@link Serializer} for regex {@link Pattern}s. - * + * * @author Martin Grotzke * @author serverperformance */ public class RegexSerializer extends Serializer { - public RegexSerializer() { - setImmutable(true); - } + public RegexSerializer() { + setImmutable(true); + } - @Override - public void write(final Kryo kryo, final Output output, final Pattern pattern) { - output.writeString(pattern.pattern()); - output.writeInt(pattern.flags(), true); - } + @Override + public void write(final Kryo kryo, final Output output, final Pattern pattern) { + output.writeString(pattern.pattern()); + output.writeInt(pattern.flags(), true); + } - @Override - public Pattern read(final Kryo kryo, final Input input, final Class patternClass) { - String regex = input.readString(); - int flags = input.readInt(true); - return Pattern.compile(regex, flags); - } + @Override + public Pattern read(final Kryo kryo, final Input input, final Class patternClass) { + String regex = input.readString(); + int flags = input.readInt(true); + return Pattern.compile(regex, flags); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/SubListSerializers.java b/src/main/java/de/javakaffee/kryoserializers/SubListSerializers.java index 562ae074..0c784a51 100644 --- a/src/main/java/de/javakaffee/kryoserializers/SubListSerializers.java +++ b/src/main/java/de/javakaffee/kryoserializers/SubListSerializers.java @@ -31,218 +31,229 @@ * An instance of a serializer can be obtained via {@link #createFor(Class)}, which * just returns null if the given type is not supported by these * serializers. - * + * * @author Martin Grotzke */ public class SubListSerializers { - static Class getClass(final String className) { - try { - return Class.forName(className); - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - static Class getClassOrNull(final String className) { - try { - return Class.forName(className); - } catch (final Exception e) { - return null; - } - } - - // Workaround reference reading, this should be removed sometimes. See also - // https://groups.google.com/d/msg/kryo-users/Eu5V4bxCfws/k-8UQ22y59AJ - private static final Object FAKE_REFERENCE = new Object(); - - /** - * Obtain a serializer for the given sublist type. If the type is not supported - * null is returned. - * @param type the class of the sublist. - * @return a serializer instance or null. - */ - @SuppressWarnings("rawtypes") - public static Serializer> createFor(final Class type) { - if (ArrayListSubListSerializer.canSerialize(type)) - return new ArrayListSubListSerializer(); - if (JavaUtilSubListSerializer.canSerialize(type)) - return new JavaUtilSubListSerializer(); - return null; - } - - /** - * Adds appropriate sublist serializers as default serializers. - */ - public static Kryo addDefaultSerializers(Kryo kryo) { - ArrayListSubListSerializer.addDefaultSerializer(kryo); - JavaUtilSubListSerializer.addDefaultSerializer(kryo); - return kryo; - } - - /** - * Supports sublists created via {@link ArrayList#subList(int, int)} since java7 (oracle jdk, - * represented by java.util.ArrayList$SubList). - */ - public static class ArrayListSubListSerializer extends Serializer> { - - public static final Class SUBLIST_CLASS = SubListSerializers.getClassOrNull("java.util.ArrayList$SubList"); - - private Field _parentField; - private Field _parentOffsetField; - private Field _sizeField; - - public ArrayListSubListSerializer() { - try { - final Class clazz = Class.forName("java.util.ArrayList$SubList"); - _parentField = clazz.getDeclaredField("parent"); - _parentOffsetField = clazz.getDeclaredField( "parentOffset" ); - _sizeField = clazz.getDeclaredField( "size" ); - _parentField.setAccessible( true ); - _parentOffsetField.setAccessible( true ); - _sizeField.setAccessible( true ); - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - /** - * Can be used to determine, if the given type can be handled by this serializer. - * - * @param type - * the class to check. - * @return true if the given class can be serialized/deserialized by this serializer. - */ - public static boolean canSerialize(final Class type) { - return SUBLIST_CLASS != null && SUBLIST_CLASS.isAssignableFrom(type); - } - - public static Kryo addDefaultSerializer(Kryo kryo) { - if(SUBLIST_CLASS != null) kryo.addDefaultSerializer(SUBLIST_CLASS, new ArrayListSubListSerializer()); - return kryo; - } - - @Override - public List read(final Kryo kryo, final Input input, final Class> clazz) { - kryo.reference(FAKE_REFERENCE); - final List list = (List) kryo.readClassAndObject(input); - final int fromIndex = input.readInt(true); - final int toIndex = input.readInt(true); - return list.subList(fromIndex, toIndex); - } - - @Override - public void write(final Kryo kryo, final Output output, final List obj) { - try { - kryo.writeClassAndObject(output, _parentField.get(obj)); - final int parentOffset = _parentOffsetField.getInt( obj ); - final int fromIndex = parentOffset; - output.writeInt(fromIndex, true); - final int toIndex = fromIndex + _sizeField.getInt( obj ); - output.writeInt(toIndex, true); - } catch (final RuntimeException e) { - // Don't eat and wrap RuntimeExceptions because the ObjectBuffer.write... - // handles SerializationException specifically (resizing the buffer)... - throw e; - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - @Override - public List copy(final Kryo kryo, final List original) { - kryo.reference(FAKE_REFERENCE); - try { - final List list = (List) _parentField.get(original); - final int parentOffset = _parentOffsetField.getInt( original ); - final int fromIndex = parentOffset; - final int toIndex = fromIndex + _sizeField.getInt( original ); - return kryo.copy(list).subList(fromIndex, toIndex); - } catch(final Exception e) { - throw new RuntimeException(e); - } - } - } - - /** - * Supports sublists created via {@link AbstractList#subList(int, int)}, e.g. LinkedList. - * In oracle jdk such sublists are represented by java.util.SubList. - */ - public static class JavaUtilSubListSerializer extends Serializer> { - - public static final Class SUBLIST_CLASS = SubListSerializers.getClassOrNull("java.util.SubList"); - - private Field _listField; - private Field _offsetField; - private Field _sizeField; - - public JavaUtilSubListSerializer() { - try { - final Class clazz = Class.forName("java.util.SubList"); - _listField = clazz.getDeclaredField("l"); - _offsetField = clazz.getDeclaredField("offset"); - _sizeField = clazz.getDeclaredField("size"); - _listField.setAccessible(true); - _offsetField.setAccessible(true); - _sizeField.setAccessible(true); - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - /** - * Can be used to determine, if the given type can be handled by this serializer. - * - * @param type - * the class to check. - * @return true if the given class can be serialized/deserialized by this serializer. - */ - public static boolean canSerialize(final Class type) { - return SUBLIST_CLASS != null && SUBLIST_CLASS.isAssignableFrom(type); - } - - public static Kryo addDefaultSerializer(Kryo kryo) { - if(SUBLIST_CLASS != null) kryo.addDefaultSerializer(SUBLIST_CLASS, new JavaUtilSubListSerializer()); - return kryo; - } - - @Override - public List read(final Kryo kryo, final Input input, final Class> clazz) { - kryo.reference(FAKE_REFERENCE); - final List list = (List) kryo.readClassAndObject(input); - final int fromIndex = input.readInt(true); - final int toIndex = input.readInt(true); - return list.subList(fromIndex, toIndex); - } - - @Override - public void write(final Kryo kryo, final Output output, final List obj) { - try { - kryo.writeClassAndObject(output, _listField.get(obj)); - final int fromIndex = _offsetField.getInt(obj); - output.writeInt(fromIndex, true); - final int toIndex = fromIndex + _sizeField.getInt(obj); - output.writeInt(toIndex, true); - } catch (final RuntimeException e) { - // Don't eat and wrap RuntimeExceptions because the ObjectBuffer.write... - // handles SerializationException specifically (resizing the buffer)... - throw e; - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - @Override - public List copy(final Kryo kryo, final List obj) { - kryo.reference(FAKE_REFERENCE); - try { - final List list = (List) _listField.get(obj); - final int fromIndex = _offsetField.getInt(obj); - final int toIndex = fromIndex + _sizeField.getInt(obj); - return kryo.copy(list).subList(fromIndex, toIndex); - } catch(final Exception e) { - throw new RuntimeException(e); - } - } - } + // Workaround reference reading, this should be removed sometimes. See also + // https://groups.google.com/d/msg/kryo-users/Eu5V4bxCfws/k-8UQ22y59AJ + private static final Object FAKE_REFERENCE = new Object(); + + static Class getClass(final String className) { + try { + return Class.forName(className); + } catch (final Exception e) { + throw new RuntimeException(e); + } + } + + static Class getClassOrNull(final String className) { + try { + return Class.forName(className); + } catch (final Exception e) { + return null; + } + } + + /** + * Obtain a serializer for the given sublist type. If the type is not supported + * null is returned. + * + * @param type the class of the sublist. + * @return a serializer instance or null. + */ + @SuppressWarnings("rawtypes") + public static Serializer> createFor(final Class type) { + if (ArrayListSubListSerializer.canSerialize(type)) + return new ArrayListSubListSerializer(); + if (JavaUtilSubListSerializer.canSerialize(type)) + return new JavaUtilSubListSerializer(); + return null; + } + + /** + * Adds appropriate sublist serializers as default serializers. + * + * @param kryo the {@code Kryo} to add default serializers to. + * @return the input {@code Kryo} + */ + public static Kryo addDefaultSerializers(Kryo kryo) { + ArrayListSubListSerializer.addDefaultSerializer(kryo); + JavaUtilSubListSerializer.addDefaultSerializer(kryo); + return kryo; + } + + private static List subListRead(Kryo kryo, Input input) { + kryo.reference(FAKE_REFERENCE); + final List list = (List) kryo.readClassAndObject(input); + final int fromIndex = input.readInt(true); + final int toIndex = input.readInt(true); + return list.subList(fromIndex, toIndex); + } + + private static List subListCopy(Kryo kryo, List originalList, int parentOffset, int size) { + final int toIndex = parentOffset + size; + return kryo.copy(originalList).subList(parentOffset, toIndex); + } + + private static void subListWrite(Kryo kryo, Output output, Object originalList, int fromIndex, int size) { + try { + kryo.writeClassAndObject(output, originalList); + output.writeInt(fromIndex, true); + final int toIndex = fromIndex + size; + output.writeInt(toIndex, true); + } catch (final RuntimeException e) { + // Don't eat and wrap RuntimeExceptions because the ObjectBuffer.write... + // handles SerializationException specifically (resizing the buffer)... + throw e; + } catch (final Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Supports sublists created via {@link ArrayList#subList(int, int)} since java7 (oracle jdk, + * represented by java.util.ArrayList$SubList). + */ + public static class ArrayListSubListSerializer extends Serializer> { + + public static final Class SUBLIST_CLASS = SubListSerializers.getClassOrNull("java.util.ArrayList$SubList"); + + private Field _parentField; + private Field _parentOffsetField; + private Field _sizeField; + + public ArrayListSubListSerializer() { + try { + final Class clazz = Class.forName("java.util.ArrayList$SubList"); + _parentField = clazz.getDeclaredField("parent"); + _parentOffsetField = clazz.getDeclaredField("parentOffset"); + _sizeField = clazz.getDeclaredField("size"); + _parentField.setAccessible(true); + _parentOffsetField.setAccessible(true); + _sizeField.setAccessible(true); + } catch (final Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Can be used to determine, if the given type can be handled by this serializer. + * + * @param type the class to check. + * @return true if the given class can be serialized/deserialized by this serializer. + */ + public static boolean canSerialize(final Class type) { + return SUBLIST_CLASS != null && SUBLIST_CLASS.isAssignableFrom(type); + } + + public static Kryo addDefaultSerializer(Kryo kryo) { + if (SUBLIST_CLASS != null) + kryo.addDefaultSerializer(SUBLIST_CLASS, new ArrayListSubListSerializer()); + return kryo; + } + + @Override + public List read(final Kryo kryo, final Input input, final Class> clazz) { + return subListRead(kryo, input); + } + + @Override + public void write(final Kryo kryo, final Output output, final List obj) { + try { + subListWrite(kryo, output, _parentField.get(obj), _parentOffsetField.getInt(obj), + _sizeField.getInt(obj)); + } catch (final RuntimeException e) { + // Don't eat and wrap RuntimeExceptions because the ObjectBuffer.write... + // handles SerializationException specifically (resizing the buffer)... + throw e; + } catch (final Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public List copy(final Kryo kryo, final List original) { + kryo.reference(FAKE_REFERENCE); + try { + return subListCopy(kryo, (List) _parentField.get(original), _parentOffsetField.getInt(original), + _sizeField.getInt(original)); + } catch (final Exception e) { + throw new RuntimeException(e); + } + } + } + + /** + * Supports sublists created via {@link AbstractList#subList(int, int)}, e.g. LinkedList. + * In oracle jdk such sublists are represented by java.util.SubList. + */ + public static class JavaUtilSubListSerializer extends Serializer> { + + public static final Class SUBLIST_CLASS = SubListSerializers.getClassOrNull("java.util.SubList"); + + private Field _listField; + private Field _offsetField; + private Field _sizeField; + + public JavaUtilSubListSerializer() { + try { + final Class clazz = Class.forName("java.util.SubList"); + _listField = clazz.getDeclaredField("l"); + _offsetField = clazz.getDeclaredField("offset"); + _sizeField = clazz.getDeclaredField("size"); + _listField.setAccessible(true); + _offsetField.setAccessible(true); + _sizeField.setAccessible(true); + } catch (final Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Can be used to determine, if the given type can be handled by this serializer. + * + * @param type the class to check. + * @return true if the given class can be serialized/deserialized by this serializer. + */ + public static boolean canSerialize(final Class type) { + return SUBLIST_CLASS != null && SUBLIST_CLASS.isAssignableFrom(type); + } + + public static Kryo addDefaultSerializer(Kryo kryo) { + if (SUBLIST_CLASS != null) + kryo.addDefaultSerializer(SUBLIST_CLASS, new JavaUtilSubListSerializer()); + return kryo; + } + + @Override + public List read(final Kryo kryo, final Input input, final Class> clazz) { + return subListRead(kryo, input); + } + + @Override + public void write(final Kryo kryo, final Output output, final List obj) { + try { + subListWrite(kryo, output, _listField.get(obj), _offsetField.getInt(obj), _sizeField.getInt(obj)); + } catch (final RuntimeException e) { + // Don't eat and wrap RuntimeExceptions because the ObjectBuffer.write... + // handles SerializationException specifically (resizing the buffer)... + throw e; + } catch (final Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public List copy(final Kryo kryo, final List obj) { + kryo.reference(FAKE_REFERENCE); + try { + return subListCopy(kryo, (List) _listField.get(obj), _offsetField.getInt(obj), + _sizeField.getInt(obj)); + } catch (final Exception e) { + throw new RuntimeException(e); + } + } + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/SynchronizedCollectionsSerializer.java b/src/main/java/de/javakaffee/kryoserializers/SynchronizedCollectionsSerializer.java index d749c38b..2a19d004 100644 --- a/src/main/java/de/javakaffee/kryoserializers/SynchronizedCollectionsSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/SynchronizedCollectionsSerializer.java @@ -17,20 +17,7 @@ package de.javakaffee.kryoserializers; import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeMap; -import java.util.TreeSet; +import java.util.*; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; @@ -40,157 +27,154 @@ /** * A kryo {@link Serializer} for synchronized {@link Collection}s and {@link Map}s * created via {@link Collections}. - * + * * @author Martin Grotzke */ public class SynchronizedCollectionsSerializer extends Serializer { - - private static final Field SOURCE_COLLECTION_FIELD; - private static final Field SOURCE_MAP_FIELD; - - static { - try { - SOURCE_COLLECTION_FIELD = Class.forName("java.util.Collections$SynchronizedCollection" ) - .getDeclaredField( "c" ); - SOURCE_COLLECTION_FIELD.setAccessible( true ); - - SOURCE_MAP_FIELD = Class.forName("java.util.Collections$SynchronizedMap" ) - .getDeclaredField( "m" ); - SOURCE_MAP_FIELD.setAccessible( true ); - } catch ( final Exception e ) { - throw new RuntimeException( "Could not access source collection" + - " field in java.util.Collections$SynchronizedCollection.", e ); - } - } - - @Override - public Object read(final Kryo kryo, final Input input, final Class clazz) { - final int ordinal = input.readInt( true ); - final SynchronizedCollection collection = SynchronizedCollection.values()[ordinal]; - final Object sourceCollection = kryo.readClassAndObject( input ); - return collection.create( sourceCollection ); - } - - @Override - public void write(final Kryo kryo, final Output output, final Object object) { - try { - final SynchronizedCollection collection = SynchronizedCollection.valueOfType( object.getClass() ); - // the ordinal could be replaced by s.th. else (e.g. a explicitely managed "id") - output.writeInt( collection.ordinal(), true ); - kryo.writeClassAndObject( output, collection.sourceCollectionField.get( object ) ); - } catch ( final RuntimeException e ) { - // Don't eat and wrap RuntimeExceptions because the ObjectBuffer.write... - // handles SerializationException specifically (resizing the buffer)... - throw e; - } catch ( final Exception e ) { - throw new RuntimeException( e ); - } - } - - @Override - public Object copy(Kryo kryo, Object original) { - try { - final SynchronizedCollection collection = SynchronizedCollection.valueOfType( original.getClass() ); - Object sourceCollectionCopy = kryo.copy(collection.sourceCollectionField.get(original)); - return collection.create( sourceCollectionCopy ); - } catch ( final RuntimeException e ) { - // Don't eat and wrap RuntimeExceptions - throw e; - } catch ( final Exception e ) { - throw new RuntimeException( e ); - } - } - - private static enum SynchronizedCollection { - COLLECTION( Collections.synchronizedCollection( Arrays.asList( "" ) ).getClass(), SOURCE_COLLECTION_FIELD ){ - @Override - public Object create( final Object sourceCollection ) { - return Collections.synchronizedCollection( (Collection) sourceCollection ); - } - }, - RANDOM_ACCESS_LIST( Collections.synchronizedList( new ArrayList() ).getClass(), SOURCE_COLLECTION_FIELD ){ - @Override - public Object create( final Object sourceCollection ) { - return Collections.synchronizedList( (List) sourceCollection ); - } - }, - LIST( Collections.synchronizedList( new LinkedList() ).getClass(), SOURCE_COLLECTION_FIELD ){ - @Override - public Object create( final Object sourceCollection ) { - return Collections.synchronizedList( (List) sourceCollection ); - } - }, - SET( Collections.synchronizedSet( new HashSet() ).getClass(), SOURCE_COLLECTION_FIELD ){ - @Override - public Object create( final Object sourceCollection ) { - return Collections.synchronizedSet( (Set) sourceCollection ); - } - }, - SORTED_SET( Collections.synchronizedSortedSet( new TreeSet() ).getClass(), SOURCE_COLLECTION_FIELD ){ - @Override - public Object create( final Object sourceCollection ) { - return Collections.synchronizedSortedSet( (SortedSet) sourceCollection ); - } - }, - MAP( Collections.synchronizedMap( new HashMap() ).getClass(), SOURCE_MAP_FIELD ) { - - @Override - public Object create( final Object sourceCollection ) { - return Collections.synchronizedMap( (Map) sourceCollection ); - } - - }, - SORTED_MAP( Collections.synchronizedSortedMap( new TreeMap() ).getClass(), SOURCE_MAP_FIELD ) { - @Override - public Object create( final Object sourceCollection ) { - return Collections.synchronizedSortedMap( (SortedMap) sourceCollection ); - } - }; - - private final Class type; - private final Field sourceCollectionField; - - private SynchronizedCollection( final Class type, final Field sourceCollectionField ) { - this.type = type; - this.sourceCollectionField = sourceCollectionField; - } - - /** - * @param sourceCollection - */ - public abstract Object create( Object sourceCollection ); - - static SynchronizedCollection valueOfType( final Class type ) { - for( final SynchronizedCollection item : values() ) { - if ( item.type.equals( type ) ) { - return item; - } - } - throw new IllegalArgumentException( "The type " + type + " is not supported." ); - } - - } - - /** - * Creates a new {@link SynchronizedCollectionsSerializer} and registers its serializer - * for the several synchronized Collections that can be created via {@link Collections}, - * including {@link Map}s. - * - * @param kryo the {@link Kryo} instance to set the serializer on. - * - * @see Collections#synchronizedCollection(Collection) - * @see Collections#synchronizedList(List) - * @see Collections#synchronizedSet(Set) - * @see Collections#synchronizedSortedSet(SortedSet) - * @see Collections#synchronizedMap(Map) - * @see Collections#synchronizedSortedMap(SortedMap) - */ - public static void registerSerializers( final Kryo kryo ) { - final SynchronizedCollectionsSerializer serializer = new SynchronizedCollectionsSerializer(); - SynchronizedCollection.values(); - for ( final SynchronizedCollection item : SynchronizedCollection.values() ) { - kryo.register( item.type, serializer ); - } - } + + private static final Field SOURCE_COLLECTION_FIELD; + private static final Field SOURCE_MAP_FIELD; + + static { + try { + SOURCE_COLLECTION_FIELD = + Class.forName("java.util.Collections$SynchronizedCollection").getDeclaredField("c"); + SOURCE_COLLECTION_FIELD.setAccessible(true); + + SOURCE_MAP_FIELD = Class.forName("java.util.Collections$SynchronizedMap").getDeclaredField("m"); + SOURCE_MAP_FIELD.setAccessible(true); + } catch (final Exception e) { + throw new RuntimeException( + "Could not access source collection" + " field in java.util.Collections$SynchronizedCollection.", + e); + } + } + + /** + * Creates a new {@link SynchronizedCollectionsSerializer} and registers its serializer + * for the several synchronized Collections that can be created via {@link Collections}, + * including {@link Map}s. + * + * @param kryo the {@link Kryo} instance to set the serializer on. + * @see Collections#synchronizedCollection(Collection) + * @see Collections#synchronizedList(List) + * @see Collections#synchronizedSet(Set) + * @see Collections#synchronizedSortedSet(SortedSet) + * @see Collections#synchronizedMap(Map) + * @see Collections#synchronizedSortedMap(SortedMap) + */ + public static void registerSerializers(final Kryo kryo) { + final SynchronizedCollectionsSerializer serializer = new SynchronizedCollectionsSerializer(); + for (final SynchronizedCollection item : SynchronizedCollection.values()) { + kryo.register(item.type, serializer); + } + } + + @Override + public Object read(final Kryo kryo, final Input input, final Class clazz) { + final int ordinal = input.readInt(true); + final SynchronizedCollection collection = SynchronizedCollection.values()[ordinal]; + final Object sourceCollection = kryo.readClassAndObject(input); + return collection.create(sourceCollection); + } + + @Override + public void write(final Kryo kryo, final Output output, final Object object) { + try { + final SynchronizedCollection collection = SynchronizedCollection.valueOfType(object.getClass()); + // the ordinal could be replaced by s.th. else (e.g. a explicitely managed "id") + output.writeInt(collection.ordinal(), true); + kryo.writeClassAndObject(output, collection.sourceCollectionField.get(object)); + } catch (final RuntimeException e) { + // Don't eat and wrap RuntimeExceptions because the ObjectBuffer.write... + // handles SerializationException specifically (resizing the buffer)... + throw e; + } catch (final Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public Object copy(Kryo kryo, Object original) { + try { + final SynchronizedCollection collection = SynchronizedCollection.valueOfType(original.getClass()); + Object sourceCollectionCopy = kryo.copy(collection.sourceCollectionField.get(original)); + return collection.create(sourceCollectionCopy); + } catch (final RuntimeException e) { + // Don't eat and wrap RuntimeExceptions + throw e; + } catch (final Exception e) { + throw new RuntimeException(e); + } + } + + private static enum SynchronizedCollection { + COLLECTION(Collections.synchronizedCollection(Arrays.asList("")).getClass(), SOURCE_COLLECTION_FIELD) { + @Override + public Object create(final Object sourceCollection) { + return Collections.synchronizedCollection((Collection) sourceCollection); + } + }, + RANDOM_ACCESS_LIST(Collections.synchronizedList(new ArrayList()).getClass(), SOURCE_COLLECTION_FIELD) { + @Override + public Object create(final Object sourceCollection) { + return Collections.synchronizedList((List) sourceCollection); + } + }, + LIST(Collections.synchronizedList(new LinkedList()).getClass(), SOURCE_COLLECTION_FIELD) { + @Override + public Object create(final Object sourceCollection) { + return Collections.synchronizedList((List) sourceCollection); + } + }, + SET(Collections.synchronizedSet(new HashSet()).getClass(), SOURCE_COLLECTION_FIELD) { + @Override + public Object create(final Object sourceCollection) { + return Collections.synchronizedSet((Set) sourceCollection); + } + }, + SORTED_SET(Collections.synchronizedSortedSet(new TreeSet()).getClass(), SOURCE_COLLECTION_FIELD) { + @Override + public Object create(final Object sourceCollection) { + return Collections.synchronizedSortedSet((SortedSet) sourceCollection); + } + }, + MAP(Collections.synchronizedMap(new HashMap()).getClass(), SOURCE_MAP_FIELD) { + @Override + public Object create(final Object sourceCollection) { + return Collections.synchronizedMap((Map) sourceCollection); + } + + }, + SORTED_MAP(Collections.synchronizedSortedMap(new TreeMap()).getClass(), SOURCE_MAP_FIELD) { + @Override + public Object create(final Object sourceCollection) { + return Collections.synchronizedSortedMap((SortedMap) sourceCollection); + } + }; + + private final Class type; + private final Field sourceCollectionField; + + private SynchronizedCollection(final Class type, final Field sourceCollectionField) { + this.type = type; + this.sourceCollectionField = sourceCollectionField; + } + + static SynchronizedCollection valueOfType(final Class type) { + for (final SynchronizedCollection item : values()) { + if (item.type.equals(type)) { + return item; + } + } + throw new IllegalArgumentException("The type " + type + " is not supported."); + } + + /** + * @param sourceCollection + */ + public abstract Object create(Object sourceCollection); + + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/URISerializer.java b/src/main/java/de/javakaffee/kryoserializers/URISerializer.java index 612ccc85..cd405301 100644 --- a/src/main/java/de/javakaffee/kryoserializers/URISerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/URISerializer.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers; import java.net.URI; @@ -9,17 +25,17 @@ public class URISerializer extends Serializer { - public URISerializer() { - setImmutable(true); - } + public URISerializer() { + setImmutable(true); + } - @Override - public void write(final Kryo kryo, final Output output, final URI uri) { - output.writeString(uri.toString()); - } + @Override + public void write(final Kryo kryo, final Output output, final URI uri) { + output.writeString(uri.toString()); + } - @Override - public URI read(final Kryo kryo, final Input input, final Class uriClass) { - return URI.create(input.readString()); - } + @Override + public URI read(final Kryo kryo, final Input input, final Class uriClass) { + return URI.create(input.readString()); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/UUIDSerializer.java b/src/main/java/de/javakaffee/kryoserializers/UUIDSerializer.java index fa0ef92b..9d0ef492 100644 --- a/src/main/java/de/javakaffee/kryoserializers/UUIDSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/UUIDSerializer.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers; import java.util.UUID; @@ -9,17 +25,18 @@ public class UUIDSerializer extends Serializer { - public UUIDSerializer() { - setImmutable(true); - } + public UUIDSerializer() { + setImmutable(true); + } - @Override - public void write(final Kryo kryo, final Output output, final UUID uuid) { - output.writeLong(uuid.getMostSignificantBits()); - output.writeLong(uuid.getLeastSignificantBits()); - } + @Override + public void write(final Kryo kryo, final Output output, final UUID uuid) { + output.writeLong(uuid.getMostSignificantBits()); + output.writeLong(uuid.getLeastSignificantBits()); + } - @Override public UUID read(final Kryo kryo, final Input input, final Class uuidClass) { - return new UUID(input.readLong(), input.readLong()); - } + @Override + public UUID read(final Kryo kryo, final Input input, final Class uuidClass) { + return new UUID(input.readLong(), input.readLong()); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/UnicodeBlockSerializer.java b/src/main/java/de/javakaffee/kryoserializers/UnicodeBlockSerializer.java index 58d958b3..db0e2e55 100644 --- a/src/main/java/de/javakaffee/kryoserializers/UnicodeBlockSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/UnicodeBlockSerializer.java @@ -1,16 +1,30 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers; -import com.esotericsoftware.kryo.Kryo; -import com.esotericsoftware.kryo.Serializer; -import com.esotericsoftware.kryo.io.Input; -import com.esotericsoftware.kryo.io.Output; - import java.lang.Character.UnicodeBlock; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.IdentityHashMap; -import java.util.logging.Level; -import java.util.logging.Logger; + +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.Serializer; +import com.esotericsoftware.kryo.io.Input; +import com.esotericsoftware.kryo.io.Output; /** * A kryo {@link Serializer} for fields of type {@link UnicodeBlock}, which is effectively but not @@ -19,54 +33,54 @@ * @author Chris Hennick */ public class UnicodeBlockSerializer extends Serializer { - private static final IdentityHashMap BLOCK_NAMES - = new IdentityHashMap(); - static { - // Reflectively look up the instances and their names, which are in UnicodeBlock's static - // fields (necessary since UnicodeBlock isn't an actual enum) - for (Field field : UnicodeBlock.class.getDeclaredFields()) { - if (Modifier.isStatic(field.getModifiers())) { - try { - // For some reason, UnicodeBlock constants aren't already accessible, even - // though they're public! WTF? - field.setAccessible(true); - Object value = field.get(null); - if (value instanceof UnicodeBlock) { - BLOCK_NAMES.put((UnicodeBlock) value, field.getName()); - } - } catch (IllegalAccessException e) { - // Should never happen - throw new InternalError(); - } - } - } - } + private static final IdentityHashMap BLOCK_NAMES = + new IdentityHashMap(); + + static { + // Reflectively look up the instances and their names, which are in UnicodeBlock's static + // fields (necessary since UnicodeBlock isn't an actual enum) + for (Field field : UnicodeBlock.class.getDeclaredFields()) { + if (Modifier.isStatic(field.getModifiers())) { + try { + // For some reason, UnicodeBlock constants aren't already accessible, even + // though they're public! WTF? + field.setAccessible(true); + Object value = field.get(null); + if (value instanceof UnicodeBlock) { + BLOCK_NAMES.put((UnicodeBlock) value, field.getName()); + } + } catch (IllegalAccessException e) { + // Should never happen + throw new InternalError(); + } + } + } + } - public UnicodeBlockSerializer() { - super(); - } + public UnicodeBlockSerializer() { + super(); + } - /** - * {@inheritDoc} - */ - @Override - public void write(final Kryo kryo, final Output output, final UnicodeBlock obj) { - output.writeAscii(BLOCK_NAMES.get(obj)); - } + /** + * {@inheritDoc} + */ + @Override + public void write(final Kryo kryo, final Output output, final UnicodeBlock obj) { + output.writeAscii(BLOCK_NAMES.get(obj)); + } - /** - * Returns {@code original}; see {@link com.esotericsoftware.kryo.serialize.EnumSerializer#copy} - * for why we behave this way. - */ - @Override - public UnicodeBlock copy(final Kryo kryo, final UnicodeBlock original) { - return original; - } + /** + * Returns {@code original}; see {@link com.esotericsoftware.kryo.serializers.DefaultSerializers.EnumSerializer#copy} + * for why we behave this way. + */ + @Override + public UnicodeBlock copy(final Kryo kryo, final UnicodeBlock original) { + return original; + } - @Override - public UnicodeBlock read(final Kryo kryo, final Input input, - final Class unicodeBlockClass) { - String name = input.readString(); - return (name == null) ? null : UnicodeBlock.forName(name); - } + @Override + public UnicodeBlock read(final Kryo kryo, final Input input, final Class unicodeBlockClass) { + String name = input.readString(); + return (name == null) ? null : UnicodeBlock.forName(name); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/UnmodifiableCollectionsSerializer.java b/src/main/java/de/javakaffee/kryoserializers/UnmodifiableCollectionsSerializer.java index 51e1ad7c..dca78f26 100644 --- a/src/main/java/de/javakaffee/kryoserializers/UnmodifiableCollectionsSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/UnmodifiableCollectionsSerializer.java @@ -17,20 +17,7 @@ package de.javakaffee.kryoserializers; import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeMap; -import java.util.TreeSet; +import java.util.*; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; @@ -40,158 +27,155 @@ /** * A kryo {@link Serializer} for unmodifiable {@link Collection}s and {@link Map}s * created via {@link Collections}. - * + * * @author Martin Grotzke */ public class UnmodifiableCollectionsSerializer extends Serializer { - - private static final Field SOURCE_COLLECTION_FIELD; - private static final Field SOURCE_MAP_FIELD; - - static { - try { - SOURCE_COLLECTION_FIELD = Class.forName("java.util.Collections$UnmodifiableCollection" ) - .getDeclaredField( "c" ); - SOURCE_COLLECTION_FIELD.setAccessible( true ); - - - SOURCE_MAP_FIELD = Class.forName("java.util.Collections$UnmodifiableMap" ) - .getDeclaredField( "m" ); - SOURCE_MAP_FIELD.setAccessible( true ); - } catch ( final Exception e ) { - throw new RuntimeException( "Could not access source collection" + - " field in java.util.Collections$UnmodifiableCollection.", e ); - } - } - - @Override - public Object read(final Kryo kryo, final Input input, final Class clazz) { - final int ordinal = input.readInt( true ); - final UnmodifiableCollection unmodifiableCollection = UnmodifiableCollection.values()[ordinal]; - final Object sourceCollection = kryo.readClassAndObject( input ); - return unmodifiableCollection.create( sourceCollection ); - } - - @Override - public void write(final Kryo kryo, final Output output, final Object object) { - try { - final UnmodifiableCollection unmodifiableCollection = UnmodifiableCollection.valueOfType( object.getClass() ); - // the ordinal could be replaced by s.th. else (e.g. a explicitely managed "id") - output.writeInt( unmodifiableCollection.ordinal(), true ); - kryo.writeClassAndObject( output, unmodifiableCollection.sourceCollectionField.get( object ) ); - } catch ( final RuntimeException e ) { - // Don't eat and wrap RuntimeExceptions because the ObjectBuffer.write... - // handles SerializationException specifically (resizing the buffer)... - throw e; - } catch ( final Exception e ) { - throw new RuntimeException( e ); - } - } - - @Override - public Object copy(Kryo kryo, Object original) { - try { - final UnmodifiableCollection unmodifiableCollection = UnmodifiableCollection.valueOfType( original.getClass() ); - Object sourceCollectionCopy = kryo.copy(unmodifiableCollection.sourceCollectionField.get(original)); - return unmodifiableCollection.create( sourceCollectionCopy ); - } catch ( final RuntimeException e ) { - // Don't eat and wrap RuntimeExceptions - throw e; - } catch ( final Exception e ) { - throw new RuntimeException( e ); - } - } - - private static enum UnmodifiableCollection { - COLLECTION( Collections.unmodifiableCollection( Arrays.asList( "" ) ).getClass(), SOURCE_COLLECTION_FIELD ){ - @Override - public Object create( final Object sourceCollection ) { - return Collections.unmodifiableCollection( (Collection) sourceCollection ); - } - }, - RANDOM_ACCESS_LIST( Collections.unmodifiableList( new ArrayList() ).getClass(), SOURCE_COLLECTION_FIELD ){ - @Override - public Object create( final Object sourceCollection ) { - return Collections.unmodifiableList( (List) sourceCollection ); - } - }, - LIST( Collections.unmodifiableList( new LinkedList() ).getClass(), SOURCE_COLLECTION_FIELD ){ - @Override - public Object create( final Object sourceCollection ) { - return Collections.unmodifiableList( (List) sourceCollection ); - } - }, - SET( Collections.unmodifiableSet( new HashSet() ).getClass(), SOURCE_COLLECTION_FIELD ){ - @Override - public Object create( final Object sourceCollection ) { - return Collections.unmodifiableSet( (Set) sourceCollection ); - } - }, - SORTED_SET( Collections.unmodifiableSortedSet( new TreeSet() ).getClass(), SOURCE_COLLECTION_FIELD ){ - @Override - public Object create( final Object sourceCollection ) { - return Collections.unmodifiableSortedSet( (SortedSet) sourceCollection ); - } - }, - MAP( Collections.unmodifiableMap( new HashMap() ).getClass(), SOURCE_MAP_FIELD ) { - - @Override - public Object create( final Object sourceCollection ) { - return Collections.unmodifiableMap( (Map) sourceCollection ); - } - - }, - SORTED_MAP( Collections.unmodifiableSortedMap( new TreeMap() ).getClass(), SOURCE_MAP_FIELD ) { - @Override - public Object create( final Object sourceCollection ) { - return Collections.unmodifiableSortedMap( (SortedMap) sourceCollection ); - } - }; - - private final Class type; - private final Field sourceCollectionField; - - private UnmodifiableCollection( final Class type, final Field sourceCollectionField ) { - this.type = type; - this.sourceCollectionField = sourceCollectionField; - } - - /** - * @param sourceCollection - */ - public abstract Object create( Object sourceCollection ); - - static UnmodifiableCollection valueOfType( final Class type ) { - for( final UnmodifiableCollection item : values() ) { - if ( item.type.equals( type ) ) { - return item; - } - } - throw new IllegalArgumentException( "The type " + type + " is not supported." ); - } - - } - - /** - * Creates a new {@link UnmodifiableCollectionsSerializer} and registers its serializer - * for the several unmodifiable Collections that can be created via {@link Collections}, - * including {@link Map}s. - * - * @param kryo the {@link Kryo} instance to set the serializer on. - * - * @see Collections#unmodifiableCollection(Collection) - * @see Collections#unmodifiableList(List) - * @see Collections#unmodifiableSet(Set) - * @see Collections#unmodifiableSortedSet(SortedSet) - * @see Collections#unmodifiableMap(Map) - * @see Collections#unmodifiableSortedMap(SortedMap) - */ - public static void registerSerializers( final Kryo kryo ) { - final UnmodifiableCollectionsSerializer serializer = new UnmodifiableCollectionsSerializer(); - UnmodifiableCollection.values(); - for ( final UnmodifiableCollection item : UnmodifiableCollection.values() ) { - kryo.register( item.type, serializer ); - } - } + + private static final Field SOURCE_COLLECTION_FIELD; + private static final Field SOURCE_MAP_FIELD; + + static { + try { + SOURCE_COLLECTION_FIELD = + Class.forName("java.util.Collections$UnmodifiableCollection").getDeclaredField("c"); + SOURCE_COLLECTION_FIELD.setAccessible(true); + + SOURCE_MAP_FIELD = Class.forName("java.util.Collections$UnmodifiableMap").getDeclaredField("m"); + SOURCE_MAP_FIELD.setAccessible(true); + } catch (final Exception e) { + throw new RuntimeException( + "Could not access source collection" + " field in java.util.Collections$UnmodifiableCollection.", + e); + } + } + + /** + * Creates a new {@link UnmodifiableCollectionsSerializer} and registers its serializer + * for the several unmodifiable Collections that can be created via {@link Collections}, + * including {@link Map}s. + * + * @param kryo the {@link Kryo} instance to set the serializer on. + * @see Collections#unmodifiableCollection(Collection) + * @see Collections#unmodifiableList(List) + * @see Collections#unmodifiableSet(Set) + * @see Collections#unmodifiableSortedSet(SortedSet) + * @see Collections#unmodifiableMap(Map) + * @see Collections#unmodifiableSortedMap(SortedMap) + */ + public static void registerSerializers(final Kryo kryo) { + final UnmodifiableCollectionsSerializer serializer = new UnmodifiableCollectionsSerializer(); + for (final UnmodifiableCollection item : UnmodifiableCollection.values()) { + kryo.register(item.type, serializer); + } + } + + @Override + public Object read(final Kryo kryo, final Input input, final Class clazz) { + final int ordinal = input.readInt(true); + final UnmodifiableCollection unmodifiableCollection = UnmodifiableCollection.values()[ordinal]; + final Object sourceCollection = kryo.readClassAndObject(input); + return unmodifiableCollection.create(sourceCollection); + } + + @Override + public void write(final Kryo kryo, final Output output, final Object object) { + try { + final UnmodifiableCollection unmodifiableCollection = UnmodifiableCollection.valueOfType(object.getClass()); + // the ordinal could be replaced by s.th. else (e.g. a explicitely managed "id") + output.writeInt(unmodifiableCollection.ordinal(), true); + kryo.writeClassAndObject(output, unmodifiableCollection.sourceCollectionField.get(object)); + } catch (final RuntimeException e) { + // Don't eat and wrap RuntimeExceptions because the ObjectBuffer.write... + // handles SerializationException specifically (resizing the buffer)... + throw e; + } catch (final Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public Object copy(Kryo kryo, Object original) { + try { + final UnmodifiableCollection unmodifiableCollection = + UnmodifiableCollection.valueOfType(original.getClass()); + Object sourceCollectionCopy = kryo.copy(unmodifiableCollection.sourceCollectionField.get(original)); + return unmodifiableCollection.create(sourceCollectionCopy); + } catch (final RuntimeException e) { + // Don't eat and wrap RuntimeExceptions + throw e; + } catch (final Exception e) { + throw new RuntimeException(e); + } + } + + private static enum UnmodifiableCollection { + COLLECTION(Collections.unmodifiableCollection(Arrays.asList("")).getClass(), SOURCE_COLLECTION_FIELD) { + @Override + public Object create(final Object sourceCollection) { + return Collections.unmodifiableCollection((Collection) sourceCollection); + } + }, + RANDOM_ACCESS_LIST(Collections.unmodifiableList(new ArrayList()).getClass(), SOURCE_COLLECTION_FIELD) { + @Override + public Object create(final Object sourceCollection) { + return Collections.unmodifiableList((List) sourceCollection); + } + }, + LIST(Collections.unmodifiableList(new LinkedList()).getClass(), SOURCE_COLLECTION_FIELD) { + @Override + public Object create(final Object sourceCollection) { + return Collections.unmodifiableList((List) sourceCollection); + } + }, + SET(Collections.unmodifiableSet(new HashSet()).getClass(), SOURCE_COLLECTION_FIELD) { + @Override + public Object create(final Object sourceCollection) { + return Collections.unmodifiableSet((Set) sourceCollection); + } + }, + SORTED_SET(Collections.unmodifiableSortedSet(new TreeSet()).getClass(), SOURCE_COLLECTION_FIELD) { + @Override + public Object create(final Object sourceCollection) { + return Collections.unmodifiableSortedSet((SortedSet) sourceCollection); + } + }, + MAP(Collections.unmodifiableMap(new HashMap()).getClass(), SOURCE_MAP_FIELD) { + @Override + public Object create(final Object sourceCollection) { + return Collections.unmodifiableMap((Map) sourceCollection); + } + + }, + SORTED_MAP(Collections.unmodifiableSortedMap(new TreeMap()).getClass(), SOURCE_MAP_FIELD) { + @Override + public Object create(final Object sourceCollection) { + return Collections.unmodifiableSortedMap((SortedMap) sourceCollection); + } + }; + + private final Class type; + private final Field sourceCollectionField; + + private UnmodifiableCollection(final Class type, final Field sourceCollectionField) { + this.type = type; + this.sourceCollectionField = sourceCollectionField; + } + + static UnmodifiableCollection valueOfType(final Class type) { + for (final UnmodifiableCollection item : values()) { + if (item.type.equals(type)) { + return item; + } + } + throw new IllegalArgumentException("The type " + type + " is not supported."); + } + + /** + * @param sourceCollection + */ + public abstract Object create(Object sourceCollection); + + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/cglib/CGLibProxySerializer.java b/src/main/java/de/javakaffee/kryoserializers/cglib/CGLibProxySerializer.java index 7f35a376..adc2f0fa 100644 --- a/src/main/java/de/javakaffee/kryoserializers/cglib/CGLibProxySerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/cglib/CGLibProxySerializer.java @@ -16,58 +16,59 @@ */ package de.javakaffee.kryoserializers.cglib; -import net.sf.cglib.proxy.Callback; -import net.sf.cglib.proxy.Enhancer; -import net.sf.cglib.proxy.Factory; - import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; +import net.sf.cglib.proxy.Callback; +import net.sf.cglib.proxy.Enhancer; +import net.sf.cglib.proxy.Factory; + /** * A kryo serializer for cglib proxies. It needs to be registered for {@link CGLibProxyMarker} class. * When the serializer for a certain class is requested (via {@link Kryo#getDefaultSerializer(Class)}) - * {@link #canSerialize(Class)} has to be checked with the provided class to see if + * {@link #canSerialize(Class)} has to be checked with the provided class to see if * a {@link CGLibProxySerializer} should be returned. - * + * * @author Martin Grotzke */ public class CGLibProxySerializer extends Serializer { - /** - * This class is used as a marker class - written to the class attribute - * on serialization and checked on deserialization (via {@link CGLibProxySerializer#canSerialize(Class)}). - */ - public static interface CGLibProxyMarker {} + public static final String DEFAULT_NAMING_MARKER = "$$EnhancerByCGLIB$$"; + + public static boolean canSerialize(final Class cls) { + return Enhancer.isEnhanced(cls) && cls.getName().indexOf(DEFAULT_NAMING_MARKER) > 0; + } - public static final String DEFAULT_NAMING_MARKER = "$$EnhancerByCGLIB$$"; + @Override + public Object read(final Kryo kryo, final Input input, final Class type) { + final Class superclass = kryo.readClass(input).getType(); + final Class[] interfaces = kryo.readObject(input, Class[].class); + final Callback[] callbacks = kryo.readObject(input, Callback[].class); + return createProxy(superclass, interfaces, callbacks); + } - public static boolean canSerialize( final Class cls ) { - return Enhancer.isEnhanced( cls ) && cls.getName().indexOf( DEFAULT_NAMING_MARKER ) > 0; - } - - @Override - public Object read(final Kryo kryo, final Input input, final Class type) { - final Class superclass = kryo.readClass( input ).getType(); - final Class[] interfaces = kryo.readObject(input, Class[].class); - final Callback[] callbacks = kryo.readObject(input, Callback[].class); - return createProxy( superclass, interfaces, callbacks ); - } + @Override + public void write(final Kryo kryo, final Output output, final Object obj) { + kryo.writeClass(output, obj.getClass().getSuperclass()); + kryo.writeObject(output, obj.getClass().getInterfaces()); + kryo.writeObject(output, ((Factory) obj).getCallbacks()); + } - @Override - public void write(final Kryo kryo, final Output output, final Object obj) { - kryo.writeClass( output, obj.getClass().getSuperclass() ); - kryo.writeObject( output, obj.getClass().getInterfaces() ); - kryo.writeObject( output, ((Factory)obj).getCallbacks() ); - } + private Object createProxy(final Class targetClass, final Class[] interfaces, final Callback[] callbacks) { + final Enhancer e = new Enhancer(); + e.setInterfaces(interfaces); + e.setSuperclass(targetClass); + e.setCallbacks(callbacks); + return e.create(); + } - private Object createProxy( final Class targetClass, final Class[] interfaces, final Callback[] callbacks ) { - final Enhancer e = new Enhancer(); - e.setInterfaces( interfaces ); - e.setSuperclass( targetClass ); - e.setCallbacks( callbacks ); - return e.create(); - } + /** + * This class is used as a marker class - written to the class attribute + * on serialization and checked on deserialization (via {@link CGLibProxySerializer#canSerialize(Class)}). + */ + public static interface CGLibProxyMarker { + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/dexx/ListSerializer.java b/src/main/java/de/javakaffee/kryoserializers/dexx/ListSerializer.java index d113b290..aebe40c1 100644 --- a/src/main/java/de/javakaffee/kryoserializers/dexx/ListSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/dexx/ListSerializer.java @@ -1,10 +1,25 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.dexx; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; - import com.github.andrewoma.dexx.collection.IndexedLists; import com.github.andrewoma.dexx.collection.List; @@ -13,58 +28,58 @@ */ public class ListSerializer extends Serializer { - private static final boolean DOES_NOT_ACCEPT_NULL = true; - private static final boolean IMMUTABLE = true; + private static final boolean DOES_NOT_ACCEPT_NULL = true; + private static final boolean IMMUTABLE = true; - public ListSerializer() { - super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); - } + public ListSerializer() { + super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); + } - @Override - public void write(Kryo kryo, Output output, List object) { - output.writeInt(object.size(), true); - for (Object elm : object) { - kryo.writeClassAndObject(output, elm); - } - } + /** + * Creates a new {@link de.javakaffee.kryoserializers.guava.ImmutableListSerializer} and registers its serializer + * + * @param kryo the {@link Kryo} instance to set the serializer on + */ + public static void registerSerializers(final Kryo kryo) { - @Override - public List read(Kryo kryo, Input input, Class aClass) { - final int size = input.readInt(true); - final Object[] list = new Object[size]; - for (int i = 0; i < size; ++i) { - list[i] = kryo.readClassAndObject(input); - } - return IndexedLists.copyOf(list); - } + final ListSerializer serializer = new ListSerializer(); - /** - * Creates a new {@link ImmutableListSerializer} and registers its serializer - * - * @param kryo the {@link Kryo} instance to set the serializer on - */ - public static void registerSerializers(final Kryo kryo) { + kryo.register(List.class, serializer); - final ListSerializer serializer = new ListSerializer(); + // Note: + // Only registering above is good enough for serializing/deserializing. + // but if using Kryo#copy, following is required. - kryo.register(List.class, serializer); + kryo.register(IndexedLists.of().getClass(), serializer); + kryo.register(IndexedLists.of(1).getClass(), serializer); + kryo.register(IndexedLists.of(1, 2).getClass(), serializer); + kryo.register(IndexedLists.of(1, 2, 3).getClass(), serializer); + kryo.register(IndexedLists.of(1, 2, 3, 4).getClass(), serializer); + kryo.register(IndexedLists.of(1, 2, 3, 4, 5).getClass(), serializer); + kryo.register(IndexedLists.of(1, 2, 3, 4, 5, 6).getClass(), serializer); + kryo.register(IndexedLists.of(1, 2, 3, 4, 5, 6, 7).getClass(), serializer); + kryo.register(IndexedLists.of(1, 2, 3, 4, 5, 6, 7, 8).getClass(), serializer); + kryo.register(IndexedLists.of(1, 2, 3, 4, 5, 6, 7, 8, 9).getClass(), serializer); + kryo.register(IndexedLists.of(1, 2, 3, 4, 5, 6, 7, 8, 10).getClass(), serializer); + kryo.register(IndexedLists.of(1, 2, 3, 4, 5, 6, 7, 8, 10, 11).getClass(), serializer); - // Note: - // Only registering above is good enough for serializing/deserializing. - // but if using Kryo#copy, following is required. + } - kryo.register(IndexedLists.of().getClass(), serializer); - kryo.register(IndexedLists.of(1).getClass(), serializer); - kryo.register(IndexedLists.of(1,2).getClass(), serializer); - kryo.register(IndexedLists.of(1,2,3).getClass(), serializer); - kryo.register(IndexedLists.of(1,2,3,4).getClass(), serializer); - kryo.register(IndexedLists.of(1,2,3,4,5).getClass(), serializer); - kryo.register(IndexedLists.of(1,2,3,4,5,6).getClass(), serializer); - kryo.register(IndexedLists.of(1,2,3,4,5,6,7).getClass(), serializer); - kryo.register(IndexedLists.of(1,2,3,4,5,6,7,8).getClass(), serializer); - kryo.register(IndexedLists.of(1,2,3,4,5,6,7,8,9).getClass(), serializer); - kryo.register(IndexedLists.of(1,2,3,4,5,6,7,8,10).getClass(), serializer); - kryo.register(IndexedLists.of(1,2,3,4,5,6,7,8,10,11).getClass(), serializer); + @Override + public void write(Kryo kryo, Output output, List object) { + output.writeInt(object.size(), true); + for (Object elm : object) { + kryo.writeClassAndObject(output, elm); + } + } - } + @Override + public List read(Kryo kryo, Input input, Class aClass) { + final int size = input.readInt(true); + final Object[] list = new Object[size]; + for (int i = 0; i < size; ++i) { + list[i] = kryo.readClassAndObject(input); + } + return IndexedLists.copyOf(list); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/dexx/MapSerializer.java b/src/main/java/de/javakaffee/kryoserializers/dexx/MapSerializer.java index 15568258..7c942ff4 100644 --- a/src/main/java/de/javakaffee/kryoserializers/dexx/MapSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/dexx/MapSerializer.java @@ -1,72 +1,88 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.dexx; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map.Entry; + import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; - import com.github.andrewoma.dexx.collection.Map; import com.github.andrewoma.dexx.collection.Maps; import com.github.andrewoma.dexx.collection.Pair; -import java.util.HashMap; -import java.util.ArrayList; -import java.util.Map.Entry; - /** -* A kryo {@link Serializer} for dexx {@link Map} + * A kryo {@link Serializer} for dexx {@link Map} */ -public class MapSerializer extends Serializer> { - - private static final boolean DOES_NOT_ACCEPT_NULL = true; - private static final boolean IMMUTABLE = true; - - public MapSerializer() { - super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); - } - - @Override - public void write(Kryo kryo, Output output, Map immutableMap) { - kryo.writeObject(output, immutableMap.asMap()); - } - - @Override - public Map read(Kryo kryo, Input input, Class> type) { - HashMap map = kryo.readObject(input, HashMap.class); - ArrayList> listOfPairs = new ArrayList(); - - for (Entry entry : map.entrySet()) { - Pair pair = new Pair(entry.getKey(), entry.getValue()); - listOfPairs.add(pair); - } - - return Maps.copyOf(listOfPairs); - } - - /** - * Creates a new {@link ImmutableMapSerializer} and registers its serializer - * for the several ImmutableMap related classes. - * - * @param kryo the {@link Kryo} instance to set the serializer on - */ - public static void registerSerializers(final Kryo kryo) { - - final MapSerializer serializer = new MapSerializer(); - - kryo.register(Map.class, serializer); - kryo.register(Maps.of().getClass(), serializer); - - Object o1 = new Object(); - Object o2 = new Object(); - Object o3 = new Object(); - Object o4 = new Object(); - Object o5 = new Object(); - - kryo.register(Maps.of(o1, o1).getClass(), serializer); - kryo.register(Maps.of(o1, o1, o2, o2).getClass(), serializer); - kryo.register(Maps.of(o1, o1, o2, o2, o3, o3).getClass(), serializer); - kryo.register(Maps.of(o1, o1, o2, o2, o3, o3, o4, o4).getClass(), serializer); - kryo.register(Maps.of(o1, o1, o2, o2, o3, o3, o4, o4, o5, o5).getClass(), serializer); - - } +public class MapSerializer extends Serializer> { + + private static final boolean DOES_NOT_ACCEPT_NULL = true; + private static final boolean IMMUTABLE = true; + + public MapSerializer() { + super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); + } + + /** + * Creates a new {@link de.javakaffee.kryoserializers.guava.ImmutableMapSerializer} and registers its serializer + * for the several ImmutableMap related classes. + * + * @param kryo the {@link Kryo} instance to set the serializer on + */ + public static void registerSerializers(final Kryo kryo) { + + final MapSerializer serializer = new MapSerializer(); + + kryo.register(Map.class, serializer); + kryo.register(Maps.of().getClass(), serializer); + + Object o1 = new Object(); + Object o2 = new Object(); + Object o3 = new Object(); + Object o4 = new Object(); + Object o5 = new Object(); + + kryo.register(Maps.of(o1, o1).getClass(), serializer); + kryo.register(Maps.of(o1, o1, o2, o2).getClass(), serializer); + kryo.register(Maps.of(o1, o1, o2, o2, o3, o3).getClass(), serializer); + kryo.register(Maps.of(o1, o1, o2, o2, o3, o3, o4, o4).getClass(), serializer); + kryo.register(Maps.of(o1, o1, o2, o2, o3, o3, o4, o4, o5, o5).getClass(), serializer); + + } + + @Override + public void write(Kryo kryo, Output output, Map immutableMap) { + kryo.writeObject(output, immutableMap.asMap()); + } + + @SuppressWarnings("unchecked") + @Override + public Map read(Kryo kryo, Input input, Class> type) { + HashMap map = kryo.readObject(input, HashMap.class); + ArrayList> listOfPairs = new ArrayList(); + + for (Entry entry : map.entrySet()) { + Pair pair = new Pair(entry.getKey(), entry.getValue()); + listOfPairs.add(pair); + } + + return Maps.copyOf(listOfPairs); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/dexx/SetSerializer.java b/src/main/java/de/javakaffee/kryoserializers/dexx/SetSerializer.java index 4a0e7b06..7be61865 100644 --- a/src/main/java/de/javakaffee/kryoserializers/dexx/SetSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/dexx/SetSerializer.java @@ -1,71 +1,86 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.dexx; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; - import com.github.andrewoma.dexx.collection.Builder; import com.github.andrewoma.dexx.collection.Set; import com.github.andrewoma.dexx.collection.Sets; /** -* A kryo {@link Serializer} for dexx {@link Set} + * A kryo {@link Serializer} for dexx {@link Set} */ public class SetSerializer extends Serializer> { - private static final boolean DOES_NOT_ACCEPT_NULL = false; - private static final boolean IMMUTABLE = true; + private static final boolean DOES_NOT_ACCEPT_NULL = false; + private static final boolean IMMUTABLE = true; - public SetSerializer() { - super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); - } + public SetSerializer() { + super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); + } - @Override - public void write(Kryo kryo, Output output, Set object) { - output.writeInt(object.size(), true); - for (Object elm : object) { - kryo.writeClassAndObject(output, elm); - } - } + /** + * Creates a new {@link de.javakaffee.kryoserializers.guava.ImmutableSetSerializer} and registers its serializer + * for the several ImmutableSet related classes. + * + * @param kryo the {@link Kryo} instance to set the serializer on + */ + public static void registerSerializers(final Kryo kryo) { - @Override - public Set read(Kryo kryo, Input input, Class> type) { - final int size = input.readInt(true); - Builder> builder = Sets.builder(); - for (int i = 0; i < size; ++i) { - builder.add(kryo.readClassAndObject(input)); - } - return builder.build(); - } + final SetSerializer serializer = new SetSerializer(); - /** - * Creates a new {@link ImmutableSetSerializer} and registers its serializer - * for the several ImmutableSet related classes. - * - * @param kryo the {@link Kryo} instance to set the serializer on - */ - public static void registerSerializers(final Kryo kryo) { + kryo.register(Set.class, serializer); - final SetSerializer serializer = new SetSerializer(); + // Note: + // Only registering above is good enough for serializing/deserializing. + // but if using Kryo#copy, following is required. - kryo.register(Set.class, serializer); + kryo.register(Sets.of().getClass(), serializer); + kryo.register(Sets.of(1).getClass(), serializer); + kryo.register(Sets.of(1, 2, 3).getClass(), serializer); + kryo.register(Sets.of(1, 2, 3, 4).getClass(), serializer); + kryo.register(Sets.of(1, 2, 3, 4, 5).getClass(), serializer); + kryo.register(Sets.of(1, 2, 3, 4, 5, 6).getClass(), serializer); + kryo.register(Sets.of(1, 2, 3, 4, 5, 6, 7).getClass(), serializer); + kryo.register(Sets.of(1, 2, 3, 4, 5, 6, 7, 8).getClass(), serializer); + kryo.register(Sets.of(1, 2, 3, 4, 5, 6, 7, 8, 9).getClass(), serializer); + kryo.register(Sets.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).getClass(), serializer); + kryo.register(Sets.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11).getClass(), serializer); - // Note: - // Only registering above is good enough for serializing/deserializing. - // but if using Kryo#copy, following is required. + } - kryo.register(Sets.of().getClass(), serializer); - kryo.register(Sets.of(1).getClass(), serializer); - kryo.register(Sets.of(1,2,3).getClass(), serializer); - kryo.register(Sets.of(1,2,3,4).getClass(), serializer); - kryo.register(Sets.of(1,2,3,4,5).getClass(), serializer); - kryo.register(Sets.of(1,2,3,4,5,6).getClass(), serializer); - kryo.register(Sets.of(1,2,3,4,5,6,7).getClass(), serializer); - kryo.register(Sets.of(1,2,3,4,5,6,7,8).getClass(), serializer); - kryo.register(Sets.of(1,2,3,4,5,6,7,8,9).getClass(), serializer); - kryo.register(Sets.of(1,2,3,4,5,6,7,8,9,10).getClass(), serializer); - kryo.register(Sets.of(1,2,3,4,5,6,7,8,9,10,11).getClass(), serializer); + @Override + public void write(Kryo kryo, Output output, Set object) { + output.writeInt(object.size(), true); + for (Object elm : object) { + kryo.writeClassAndObject(output, elm); + } + } - } + @Override + public Set read(Kryo kryo, Input input, Class> type) { + final int size = input.readInt(true); + Builder> builder = Sets.builder(); + for (int i = 0; i < size; ++i) { + builder.add(kryo.readClassAndObject(input)); + } + return builder.build(); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/guava/ArrayListMultimapSerializer.java b/src/main/java/de/javakaffee/kryoserializers/guava/ArrayListMultimapSerializer.java index 90c24e66..89e02413 100644 --- a/src/main/java/de/javakaffee/kryoserializers/guava/ArrayListMultimapSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/guava/ArrayListMultimapSerializer.java @@ -1,45 +1,62 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; - import com.google.common.collect.ArrayListMultimap; /** * A kryo {@link Serializer} for guava-libraries {@link ArrayListMultimap}. * This does not yet support {@link Kryo#copy(java.lang.Object)}. */ -public class ArrayListMultimapSerializer extends MultimapSerializerBase> { - - private static final boolean DOES_NOT_ACCEPT_NULL = false; - - private static final boolean IMMUTABLE = false; - - public ArrayListMultimapSerializer() { - super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); - } - - @Override - public void write(Kryo kryo, Output output, ArrayListMultimap multimap) { - writeMultimap(kryo, output, multimap); - } - - @Override - public ArrayListMultimap read(Kryo kryo, Input input, Class> type) { - final ArrayListMultimap multimap = ArrayListMultimap.create(); - readMultimap(kryo, input, multimap); - return multimap; - } - - /** - * Creates a new {@link ArrayListMultimapSerializer} and registers its serializer. - * - * @param kryo the {@link Kryo} instance to set the serializer on - */ - public static void registerSerializers(final Kryo kryo) { - final ArrayListMultimapSerializer serializer = new ArrayListMultimapSerializer(); - kryo.register(ArrayListMultimap.class, serializer); - } +public class ArrayListMultimapSerializer + extends MultimapSerializerBase> { + + private static final boolean DOES_NOT_ACCEPT_NULL = false; + + private static final boolean IMMUTABLE = false; + + public ArrayListMultimapSerializer() { + super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); + } + + /** + * Creates a new {@link ArrayListMultimapSerializer} and registers its serializer. + * + * @param kryo the {@link Kryo} instance to set the serializer on + */ + public static void registerSerializers(final Kryo kryo) { + final ArrayListMultimapSerializer serializer = new ArrayListMultimapSerializer(); + kryo.register(ArrayListMultimap.class, serializer); + } + + @Override + public void write(Kryo kryo, Output output, ArrayListMultimap multimap) { + writeMultimap(kryo, output, multimap); + } + + @Override + public ArrayListMultimap read(Kryo kryo, Input input, + Class> type) { + final ArrayListMultimap multimap = ArrayListMultimap.create(); + readMultimap(kryo, input, multimap); + return multimap; + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/guava/HashMultimapSerializer.java b/src/main/java/de/javakaffee/kryoserializers/guava/HashMultimapSerializer.java index 23d9af33..95591925 100644 --- a/src/main/java/de/javakaffee/kryoserializers/guava/HashMultimapSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/guava/HashMultimapSerializer.java @@ -1,10 +1,25 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; - import com.google.common.collect.HashMultimap; /** @@ -13,33 +28,33 @@ */ public class HashMultimapSerializer extends MultimapSerializerBase> { - private static final boolean DOES_NOT_ACCEPT_NULL = false; - - private static final boolean IMMUTABLE = false; - - public HashMultimapSerializer() { - super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); - } - - @Override - public void write(Kryo kryo, Output output, HashMultimap multimap) { - writeMultimap(kryo, output, multimap); - } - - @Override - public HashMultimap read(Kryo kryo, Input input, Class> type) { - final HashMultimap multimap = HashMultimap.create(); - readMultimap(kryo, input, multimap); - return multimap; - } - - /** - * Creates a new {@link HashMultimapSerializer} and registers its serializer. - * - * @param kryo the {@link Kryo} instance to set the serializer on - */ - public static void registerSerializers(final Kryo kryo) { - final HashMultimapSerializer serializer = new HashMultimapSerializer(); - kryo.register(HashMultimap.class, serializer); - } + private static final boolean DOES_NOT_ACCEPT_NULL = false; + + private static final boolean IMMUTABLE = false; + + public HashMultimapSerializer() { + super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); + } + + /** + * Creates a new {@link HashMultimapSerializer} and registers its serializer. + * + * @param kryo the {@link Kryo} instance to set the serializer on + */ + public static void registerSerializers(final Kryo kryo) { + final HashMultimapSerializer serializer = new HashMultimapSerializer(); + kryo.register(HashMultimap.class, serializer); + } + + @Override + public void write(Kryo kryo, Output output, HashMultimap multimap) { + writeMultimap(kryo, output, multimap); + } + + @Override + public HashMultimap read(Kryo kryo, Input input, Class> type) { + final HashMultimap multimap = HashMultimap.create(); + readMultimap(kryo, input, multimap); + return multimap; + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableListSerializer.java b/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableListSerializer.java index f12b3e8c..454cf041 100644 --- a/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableListSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableListSerializer.java @@ -1,87 +1,99 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; -import com.google.common.collect.HashBasedTable; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableTable; -import com.google.common.collect.Lists; -import com.google.common.collect.Table; +import com.google.common.collect.*; /** * A kryo {@link Serializer} for guava-libraries {@link ImmutableList}. */ public class ImmutableListSerializer extends Serializer> { - private static final boolean DOES_NOT_ACCEPT_NULL = false; - private static final boolean IMMUTABLE = true; + private static final boolean DOES_NOT_ACCEPT_NULL = false; + private static final boolean IMMUTABLE = true; - public ImmutableListSerializer() { - super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); - } + public ImmutableListSerializer() { + super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); + } - @Override - public void write(Kryo kryo, Output output, ImmutableList object) { - output.writeInt(object.size(), true); - for (Object elm : object) { - kryo.writeClassAndObject(output, elm); - } - } + /** + * Creates a new {@link ImmutableListSerializer} and registers its serializer + * for the several ImmutableList related classes. + * + * @param kryo the {@link Kryo} instance to set the serializer on + */ + public static void registerSerializers(final Kryo kryo) { - @Override - public ImmutableList read(Kryo kryo, Input input, Class> type) { - final int size = input.readInt(true); - final Object[] list = new Object[size]; - for (int i = 0; i < size; ++i) { - list[i] = kryo.readClassAndObject(input); - } - return ImmutableList.copyOf(list); - } + // ImmutableList (abstract class) + // +- RegularImmutableList + // | RegularImmutableList + // +- SingletonImmutableList + // | Optimized for List with only 1 element. + // +- SubList + // | Representation for part of ImmutableList + // +- ReverseImmutableList + // | For iterating in reverse order + // +- StringAsImmutableList + // | Used by Lists#charactersOf + // +- Values (ImmutableTable values) + // Used by return value of #values() when there are multiple cells - /** - * Creates a new {@link ImmutableListSerializer} and registers its serializer - * for the several ImmutableList related classes. - * - * @param kryo the {@link Kryo} instance to set the serializer on - */ - public static void registerSerializers(final Kryo kryo) { + final ImmutableListSerializer serializer = new ImmutableListSerializer(); - // ImmutableList (abstract class) - // +- RegularImmutableList - // | RegularImmutableList - // +- SingletonImmutableList - // | Optimized for List with only 1 element. - // +- SubList - // | Representation for part of ImmutableList - // +- ReverseImmutableList - // | For iterating in reverse order - // +- StringAsImmutableList - // | Used by Lists#charactersOf - // +- Values (ImmutableTable values) - // Used by return value of #values() when there are multiple cells + kryo.register(ImmutableList.class, serializer); - final ImmutableListSerializer serializer = new ImmutableListSerializer(); + // Note: + // Only registering above is good enough for serializing/deserializing. + // but if using Kryo#copy, following is required. - kryo.register(ImmutableList.class, serializer); + kryo.register(ImmutableList.of().getClass(), serializer); + kryo.register(ImmutableList.of(1).getClass(), serializer); + kryo.register(ImmutableList.of(1, 2, 3, 4).subList(1, 3).getClass(), serializer); + kryo.register(ImmutableList.of(1, 2).reverse().getClass(), serializer); - // Note: - // Only registering above is good enough for serializing/deserializing. - // but if using Kryo#copy, following is required. + kryo.register(Lists.charactersOf("KryoRocks").getClass(), serializer); - kryo.register(ImmutableList.of().getClass(), serializer); - kryo.register(ImmutableList.of(1).getClass(), serializer); - kryo.register(ImmutableList.of(1, 2, 3, 4).subList(1, 3).getClass(), serializer); - kryo.register(ImmutableList.of(1, 2).reverse().getClass(), serializer); + Table baseTable = HashBasedTable.create(); + baseTable.put(1, 2, 3); + baseTable.put(4, 5, 6); + Table table = ImmutableTable.copyOf(baseTable); + kryo.register(table.values().getClass(), serializer); - kryo.register(Lists.charactersOf("KryoRocks").getClass(), serializer); + } - Table baseTable = HashBasedTable.create(); - baseTable.put(1, 2, 3); - baseTable.put(4, 5, 6); - Table table = ImmutableTable.copyOf(baseTable); - kryo.register(table.values().getClass(), serializer); + @Override + public void write(Kryo kryo, Output output, ImmutableList object) { + output.writeInt(object.size(), true); + for (Object elm : object) { + kryo.writeClassAndObject(output, elm); + } + } - } + @Override + public ImmutableList read(Kryo kryo, Input input, Class> type) { + final int size = input.readInt(true); + final Object[] list = new Object[size]; + for (int i = 0; i < size; ++i) { + list[i] = kryo.readClassAndObject(input); + } + return ImmutableList.copyOf(list); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableMapSerializer.java b/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableMapSerializer.java index e832c299..fd4a205d 100644 --- a/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableMapSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableMapSerializer.java @@ -1,5 +1,25 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Map; + import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; @@ -7,63 +27,59 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; - - /** * A kryo {@link Serializer} for guava-libraries {@link ImmutableMap}. */ -public class ImmutableMapSerializer extends Serializer> { - - private static final boolean DOES_NOT_ACCEPT_NULL = true; - private static final boolean IMMUTABLE = true; - - public ImmutableMapSerializer() { - super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); - } - - @Override - public void write(Kryo kryo, Output output, ImmutableMap immutableMap) { - kryo.writeObject(output, Maps.newHashMap(immutableMap)); - } - - @Override - public ImmutableMap read(Kryo kryo, Input input, Class> type) { - Map map = kryo.readObject(input, HashMap.class); - return ImmutableMap.copyOf(map); - } - - /** - * Creates a new {@link ImmutableMapSerializer} and registers its serializer - * for the several ImmutableMap related classes. - * - * @param kryo the {@link Kryo} instance to set the serializer on - */ - public static void registerSerializers(final Kryo kryo) { - - final ImmutableMapSerializer serializer = new ImmutableMapSerializer(); - - kryo.register(ImmutableMap.class, serializer); - kryo.register(ImmutableMap.of().getClass(), serializer); - - Object o1 = new Object(); - Object o2 = new Object(); - - kryo.register(ImmutableMap.of(o1, o1).getClass(), serializer); - kryo.register(ImmutableMap.of(o1, o1, o2, o2).getClass(), serializer); - - Map enumMap = new EnumMap(DummyEnum.class); - for (DummyEnum e : DummyEnum.values()) { - enumMap.put(e, o1); - } - - kryo.register(ImmutableMap.copyOf(enumMap).getClass(), serializer); - } - - private enum DummyEnum { - VALUE1, - VALUE2 - } +public class ImmutableMapSerializer extends Serializer> { + + private static final boolean DOES_NOT_ACCEPT_NULL = true; + private static final boolean IMMUTABLE = true; + + public ImmutableMapSerializer() { + super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); + } + + /** + * Creates a new {@link ImmutableMapSerializer} and registers its serializer + * for the several ImmutableMap related classes. + * + * @param kryo the {@link Kryo} instance to set the serializer on + */ + public static void registerSerializers(final Kryo kryo) { + + final ImmutableMapSerializer serializer = new ImmutableMapSerializer(); + + kryo.register(ImmutableMap.class, serializer); + kryo.register(ImmutableMap.of().getClass(), serializer); + + Object o1 = new Object(); + Object o2 = new Object(); + + kryo.register(ImmutableMap.of(o1, o1).getClass(), serializer); + kryo.register(ImmutableMap.of(o1, o1, o2, o2).getClass(), serializer); + + Map enumMap = new EnumMap(DummyEnum.class); + for (DummyEnum e : DummyEnum.values()) { + enumMap.put(e, o1); + } + + kryo.register(ImmutableMap.copyOf(enumMap).getClass(), serializer); + } + + @Override + public void write(Kryo kryo, Output output, ImmutableMap immutableMap) { + kryo.writeObject(output, Maps.newHashMap(immutableMap)); + } + + @SuppressWarnings("unchecked") + @Override + public ImmutableMap read(Kryo kryo, Input input, Class> type) { + Map map = kryo.readObject(input, HashMap.class); + return ImmutableMap.copyOf(map); + } + + private enum DummyEnum { + VALUE1, + VALUE2 + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableMultimapSerializer.java b/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableMultimapSerializer.java index bbf64938..5f4af561 100644 --- a/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableMultimapSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableMultimapSerializer.java @@ -1,104 +1,114 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; +import java.util.List; +import java.util.Map; +import java.util.Set; + import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableListMultimap; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMultimap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.ImmutableSetMultimap; - -import java.util.List; -import java.util.Map; -import java.util.Set; +import com.google.common.collect.*; /** * A kryo {@link Serializer} for guava-libraries {@link ImmutableMultimap}. */ public class ImmutableMultimapSerializer extends Serializer> { - private static final boolean DOES_NOT_ACCEPT_NULL = true; - private static final boolean IMMUTABLE = true; - - public ImmutableMultimapSerializer() { - super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); - } - - @Override - public void write(Kryo kryo, Output output, ImmutableMultimap immutableMultiMap) { - kryo.writeObject(output, ImmutableMap.copyOf(immutableMultiMap.asMap())); - } - - @Override - public ImmutableMultimap read(Kryo kryo, Input input, Class> type) { - final ImmutableMultimap.Builder builder; - if (type.equals (ImmutableListMultimap.class)) { - builder = ImmutableMultimap.builder(); - } - else if (type.equals (ImmutableSetMultimap.class)) { - builder = ImmutableSetMultimap.builder(); - } - else { - builder = ImmutableMultimap.builder(); - } - - final Map map = kryo.readObject(input, ImmutableMap.class); - final Set>> entries = map.entrySet(); - - for (Map.Entry> entry : entries) { - builder.putAll(entry.getKey(), entry.getValue()); - } - - return builder.build(); - } - - /** - * Creates a new {@link ImmutableMultimapSerializer} and registers its serializer - * for the several ImmutableMultimap related classes. - * - * @param kryo the {@link Kryo} instance to set the serializer on - */ - public static void registerSerializers(final Kryo kryo) { - // ImmutableMap is used by ImmutableMultimap. However, - // we already have a separate serializer class for ImmutableMap, - // ImmutableMapSerializer. If it is not already being used, register it. - Serializer immutableMapSerializer = kryo.getSerializer(ImmutableMap.class); - if (!(immutableMapSerializer instanceof ImmutableMapSerializer)) { - ImmutableMapSerializer.registerSerializers(kryo); - } - - // ImmutableList is used by ImmutableListMultimap. However, - // we already have a separate serializer class for ImmutableList, - // ImmutableListSerializer. If it is not already being used, register it. - Serializer immutableListSerializer = kryo.getSerializer(ImmutableList.class); - if (!(immutableListSerializer instanceof ImmutableListSerializer)) { - ImmutableListSerializer.registerSerializers(kryo); - } - - // ImmutableSet is used by ImmutableSetMultimap. However, - // we already have a separate serializer class for ImmutableSet, - // ImmutableSetSerializer. If it is not already being used, register it. - Serializer immutableSetSerializer = kryo.getSerializer(ImmutableSet.class); - if (!(immutableSetSerializer instanceof ImmutableSetSerializer)) { - ImmutableSetSerializer.registerSerializers(kryo); - } - - final ImmutableMultimapSerializer serializer = new ImmutableMultimapSerializer(); - - // ImmutableMultimap (abstract class) - // +- EmptyImmutableListMultimap - // +- ImmutableListMultimap - // +- EmptyImmutableSetMultimap - // +- ImmutableSetMultimap - - kryo.register(ImmutableMultimap.class, serializer); - kryo.register(ImmutableListMultimap.of().getClass(), serializer); - kryo.register(ImmutableListMultimap.of("A", "B").getClass(), serializer); - kryo.register(ImmutableSetMultimap.of().getClass(), serializer); - kryo.register(ImmutableSetMultimap.of("A", "B").getClass(), serializer); - } + private static final boolean DOES_NOT_ACCEPT_NULL = true; + private static final boolean IMMUTABLE = true; + + public ImmutableMultimapSerializer() { + super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); + } + + /** + * Creates a new {@link ImmutableMultimapSerializer} and registers its serializer + * for the several ImmutableMultimap related classes. + * + * @param kryo the {@link Kryo} instance to set the serializer on + */ + public static void registerSerializers(final Kryo kryo) { + // ImmutableMap is used by ImmutableMultimap. However, + // we already have a separate serializer class for ImmutableMap, + // ImmutableMapSerializer. If it is not already being used, register it. + Serializer immutableMapSerializer = kryo.getSerializer(ImmutableMap.class); + if (!(immutableMapSerializer instanceof ImmutableMapSerializer)) { + ImmutableMapSerializer.registerSerializers(kryo); + } + + // ImmutableList is used by ImmutableListMultimap. However, + // we already have a separate serializer class for ImmutableList, + // ImmutableListSerializer. If it is not already being used, register it. + Serializer immutableListSerializer = kryo.getSerializer(ImmutableList.class); + if (!(immutableListSerializer instanceof ImmutableListSerializer)) { + ImmutableListSerializer.registerSerializers(kryo); + } + + // ImmutableSet is used by ImmutableSetMultimap. However, + // we already have a separate serializer class for ImmutableSet, + // ImmutableSetSerializer. If it is not already being used, register it. + Serializer immutableSetSerializer = kryo.getSerializer(ImmutableSet.class); + if (!(immutableSetSerializer instanceof ImmutableSetSerializer)) { + ImmutableSetSerializer.registerSerializers(kryo); + } + + final ImmutableMultimapSerializer serializer = new ImmutableMultimapSerializer(); + + // ImmutableMultimap (abstract class) + // +- EmptyImmutableListMultimap + // +- ImmutableListMultimap + // +- EmptyImmutableSetMultimap + // +- ImmutableSetMultimap + + kryo.register(ImmutableMultimap.class, serializer); + kryo.register(ImmutableListMultimap.of().getClass(), serializer); + kryo.register(ImmutableListMultimap.of("A", "B").getClass(), serializer); + kryo.register(ImmutableSetMultimap.of().getClass(), serializer); + kryo.register(ImmutableSetMultimap.of("A", "B").getClass(), serializer); + } + + @Override + public void write(Kryo kryo, Output output, ImmutableMultimap immutableMultiMap) { + kryo.writeObject(output, ImmutableMap.copyOf(immutableMultiMap.asMap())); + } + + @SuppressWarnings("unchecked") + @Override + public ImmutableMultimap read(Kryo kryo, Input input, + Class> type) { + final ImmutableMultimap.Builder builder; + if (type.equals(ImmutableListMultimap.class)) { + builder = ImmutableMultimap.builder(); + } else if (type.equals(ImmutableSetMultimap.class)) { + builder = ImmutableSetMultimap.builder(); + } else { + builder = ImmutableMultimap.builder(); + } + + final Map map = kryo.readObject(input, ImmutableMap.class); + final Set>> entries = map.entrySet(); + + for (Map.Entry> entry : entries) { + builder.putAll(entry.getKey(), entry.getValue()); + } + + return builder.build(); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableSetSerializer.java b/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableSetSerializer.java index 59bb41bf..18a840f1 100644 --- a/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableSetSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableSetSerializer.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; import com.esotericsoftware.kryo.Kryo; @@ -9,71 +25,74 @@ /** * A kryo {@link Serializer} for guava-libraries {@link ImmutableSet}. + *

+ * (the array.clone as done by copyOf is saved), for more elements copyOf seems to get more efficient. * - *@implNote ImmutableSet builder would be a little bit more efficient for less than five elements - *(the array.clone as done by copyOf is saved), for more elements copyOf seems to get more efficient. + * @implNote ImmutableSet builder would be a little bit more efficient for less than five elements */ public class ImmutableSetSerializer extends Serializer> { - private static final boolean DOES_NOT_ACCEPT_NULL = false; - private static final boolean IMMUTABLE = true; + private static final boolean DOES_NOT_ACCEPT_NULL = false; + private static final boolean IMMUTABLE = true; - public ImmutableSetSerializer() { - super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); - } + public ImmutableSetSerializer() { + super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); + } - @Override - public void write(Kryo kryo, Output output, ImmutableSet object) { - output.writeInt(object.size(), true); - for (Object elm : object) { - kryo.writeClassAndObject(output, elm); - } - } + /** + * Creates a new {@link ImmutableSetSerializer} and registers its serializer + * for the several ImmutableSet related classes. + * + * @param kryo the {@link Kryo} instance to set the serializer on + */ + public static void registerSerializers(final Kryo kryo) { - @Override - public ImmutableSet read(Kryo kryo, Input input, Class> type) { - final int size = input.readInt(true); - ImmutableSet.Builder builder = ImmutableSet.builder(); - for (int i = 0; i < size; ++i) { - builder.add(kryo.readClassAndObject(input)); - } - return builder.build(); - } + // ImmutableList (abstract class) + // +- EmptyImmutableSet + // | EmptyImmutableSet + // +- SingletonImmutableSet + // | Optimized for Set with only 1 element. + // +- RegularImmutableSet + // | RegularImmutableList + // +- EnumImmutableSet + // | EnumImmutableSet - /** - * Creates a new {@link ImmutableSetSerializer} and registers its serializer - * for the several ImmutableSet related classes. - * - * @param kryo the {@link Kryo} instance to set the serializer on - */ - public static void registerSerializers(final Kryo kryo) { + final ImmutableSetSerializer serializer = new ImmutableSetSerializer(); - // ImmutableList (abstract class) - // +- EmptyImmutableSet - // | EmptyImmutableSet - // +- SingletonImmutableSet - // | Optimized for Set with only 1 element. - // +- RegularImmutableSet - // | RegularImmutableList - // +- EnumImmutableSet - // | EnumImmutableSet + kryo.register(ImmutableSet.class, serializer); - final ImmutableSetSerializer serializer = new ImmutableSetSerializer(); + // Note: + // Only registering above is good enough for serializing/deserializing. + // but if using Kryo#copy, following is required. - kryo.register(ImmutableSet.class, serializer); + kryo.register(ImmutableSet.of().getClass(), serializer); + kryo.register(ImmutableSet.of(1).getClass(), serializer); + kryo.register(ImmutableSet.of(1, 2, 3).getClass(), serializer); - // Note: - // Only registering above is good enough for serializing/deserializing. - // but if using Kryo#copy, following is required. + kryo.register(Sets.immutableEnumSet(SomeEnum.A, SomeEnum.B, SomeEnum.C).getClass(), serializer); + } - kryo.register(ImmutableSet.of().getClass(), serializer); - kryo.register(ImmutableSet.of(1).getClass(), serializer); - kryo.register(ImmutableSet.of(1,2,3).getClass(), serializer); + @Override + public void write(Kryo kryo, Output output, ImmutableSet object) { + output.writeInt(object.size(), true); + for (Object elm : object) { + kryo.writeClassAndObject(output, elm); + } + } - kryo.register(Sets.immutableEnumSet(SomeEnum.A, SomeEnum.B, SomeEnum.C).getClass(), serializer); - } + @Override + public ImmutableSet read(Kryo kryo, Input input, Class> type) { + final int size = input.readInt(true); + ImmutableSet.Builder builder = ImmutableSet.builder(); + for (int i = 0; i < size; ++i) { + builder.add(kryo.readClassAndObject(input)); + } + return builder.build(); + } - private enum SomeEnum { - A, B, C - } -} \ No newline at end of file + private enum SomeEnum { + A, + B, + C + } +} diff --git a/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableSortedMapSerializer.java b/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableSortedMapSerializer.java index f2750539..72601666 100644 --- a/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableSortedMapSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableSortedMapSerializer.java @@ -1,5 +1,26 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; +import java.util.EnumMap; +import java.util.Map; +import java.util.Objects; +import java.util.TreeMap; + import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; @@ -7,75 +28,90 @@ import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Maps; -import java.util.EnumMap; -import java.util.Map; -import java.util.TreeMap; - - /** * A kryo {@link Serializer} for guava-libraries {@link ImmutableSortedMap}. */ -public class ImmutableSortedMapSerializer extends Serializer> { - - private static final boolean DOES_NOT_ACCEPT_NULL = true; - private static final boolean IMMUTABLE = true; - - public ImmutableSortedMapSerializer() { - super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); - } - - @Override - public void write(Kryo kryo, Output output, ImmutableSortedMap immutableMap) { - kryo.writeObject(output, Maps.newTreeMap(immutableMap)); - } - - @Override - public ImmutableSortedMap read(Kryo kryo, Input input, Class> type) { - Map map = kryo.readObject(input, TreeMap.class); - return ImmutableSortedMap.copyOf(map); - } - - /** - * Creates a new {@link ImmutableSortedMapSerializer} and registers its serializer - * for the several ImmutableMap related classes. - * - * @param kryo the {@link Kryo} instance to set the serializer on - */ - public static void registerSerializers(final Kryo kryo) { - - final ImmutableSortedMapSerializer serializer = new ImmutableSortedMapSerializer(); - - kryo.register(ImmutableSortedMap.class, serializer); - kryo.register(ImmutableSortedMap.of().getClass(), serializer); - - final Comparable k1 = new Comparable() { - @Override - public int compareTo(Object o) { - return o == this ? 0 : -1; - } - }; - final Comparable k2 = new Comparable() { - @Override - public int compareTo(Object o) { - return o == this ? 0 : 1; - } - }; - final Object v1 = new Object(); - final Object v2 = new Object(); - - kryo.register(ImmutableSortedMap.of(k1, v1).getClass(), serializer); - kryo.register(ImmutableSortedMap.of(k1, v1, k2, v2).getClass(), serializer); - - Map enumMap = new EnumMap(DummyEnum.class); - for (DummyEnum e : DummyEnum.values()) { - enumMap.put(e, v1); - } - - kryo.register(ImmutableSortedMap.copyOf(enumMap).getClass(), serializer); - } - - private enum DummyEnum { - VALUE1, - VALUE2 - } +public class ImmutableSortedMapSerializer extends Serializer> { + + private static final boolean DOES_NOT_ACCEPT_NULL = true; + private static final boolean IMMUTABLE = true; + + public ImmutableSortedMapSerializer() { + super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); + } + + /** + * Creates a new {@link ImmutableSortedMapSerializer} and registers its serializer + * for the several ImmutableMap related classes. + * + * @param kryo the {@link Kryo} instance to set the serializer on + */ + public static void registerSerializers(final Kryo kryo) { + + final ImmutableSortedMapSerializer serializer = new ImmutableSortedMapSerializer(); + + kryo.register(ImmutableSortedMap.class, serializer); + kryo.register(ImmutableSortedMap.of().getClass(), serializer); + + final DummyComparable k1 = new DummyComparable(1); + final DummyComparable k2 = new DummyComparable(0); + + final Object v1 = new Object(); + final Object v2 = new Object(); + + kryo.register(ImmutableSortedMap.of(k1, v1).getClass(), serializer); + kryo.register(ImmutableSortedMap.of(k1, v1, k2, v2).getClass(), serializer); + + Map enumMap = new EnumMap<>(DummyEnum.class); + for (DummyEnum e : DummyEnum.values()) { + enumMap.put(e, v1); + } + + kryo.register(ImmutableSortedMap.copyOf(enumMap).getClass(), serializer); + } + + @Override + public void write(Kryo kryo, Output output, ImmutableSortedMap immutableMap) { + kryo.writeObject(output, Maps.newTreeMap(immutableMap)); + } + + @SuppressWarnings("unchecked") + @Override + public ImmutableSortedMap read(Kryo kryo, Input input, Class> type) { + Map map = kryo.readObject(input, TreeMap.class); + return ImmutableSortedMap.copyOf(map); + } + + private enum DummyEnum { + VALUE_1, + VALUE_2 + } + + private static class DummyComparable implements Comparable { + private final int ordering; + + private DummyComparable(int ordering) { + this.ordering = ordering; + } + + @Override + public int compareTo(DummyComparable o) { + return Integer.compare(ordering, o.ordering); + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + DummyComparable that = (DummyComparable) o; + return ordering == that.ordering; + } + + @Override + public int hashCode() { + return Objects.hash(ordering); + } + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableSortedSetSerializer.java b/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableSortedSetSerializer.java index 3cebb7a5..7269c453 100644 --- a/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableSortedSetSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/guava/ImmutableSortedSetSerializer.java @@ -1,62 +1,80 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; +import java.util.Comparator; + import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.google.common.collect.ImmutableSortedSet; -import java.util.Comparator; /** * A kryo {@link Serializer} for guava-libraries {@link ImmutableSortedSet}. */ public class ImmutableSortedSetSerializer extends Serializer> { - private static final boolean DOES_NOT_ACCEPT_NULL = false; - private static final boolean IMMUTABLE = true; - - public ImmutableSortedSetSerializer() { - super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); - } - - @Override - public void write(Kryo kryo, Output output, ImmutableSortedSet object) { - kryo.writeClassAndObject(output, object.comparator()); - output.writeInt(object.size(), true); - for (Object elm : object) { - kryo.writeClassAndObject(output, elm); - } - } - - @Override - public ImmutableSortedSet read(Kryo kryo, Input input, Class> type) { - @SuppressWarnings ("unchecked") - ImmutableSortedSet.Builder builder = ImmutableSortedSet.orderedBy((Comparator)kryo.readClassAndObject (input)); - final int size = input.readInt(true); - for (int i = 0; i < size; ++i) { - builder.add(kryo.readClassAndObject(input)); - } - return builder.build(); - } - - /** - * Creates a new {@link ImmutableSortedSetSerializer} and registers its serializer - * for the several ImmutableSortedSet related classes. - * - * @param kryo the {@link Kryo} instance to set the serializer on - */ - public static void registerSerializers(final Kryo kryo) { - - // ImmutableSortedSet (abstract class) - // +- EmptyImmutableSortedSet - // +- RegularImmutableSortedSet - // +- DescendingImmutableSortedSet - - final ImmutableSortedSetSerializer serializer = new ImmutableSortedSetSerializer(); - - kryo.register(ImmutableSortedSet.class, serializer); - kryo.register(ImmutableSortedSet.of().getClass(), serializer); - kryo.register(ImmutableSortedSet.of("").getClass(), serializer); - kryo.register(ImmutableSortedSet.of().descendingSet ().getClass(), serializer); - } + private static final boolean DOES_NOT_ACCEPT_NULL = false; + private static final boolean IMMUTABLE = true; + + public ImmutableSortedSetSerializer() { + super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); + } + + /** + * Creates a new {@link ImmutableSortedSetSerializer} and registers its serializer + * for the several ImmutableSortedSet related classes. + * + * @param kryo the {@link Kryo} instance to set the serializer on + */ + public static void registerSerializers(final Kryo kryo) { + + // ImmutableSortedSet (abstract class) + // +- EmptyImmutableSortedSet + // +- RegularImmutableSortedSet + // +- DescendingImmutableSortedSet + + final ImmutableSortedSetSerializer serializer = new ImmutableSortedSetSerializer(); + + kryo.register(ImmutableSortedSet.class, serializer); + kryo.register(ImmutableSortedSet.of().getClass(), serializer); + kryo.register(ImmutableSortedSet.of("").getClass(), serializer); + kryo.register(ImmutableSortedSet.of().descendingSet().getClass(), serializer); + } + + @Override + public void write(Kryo kryo, Output output, ImmutableSortedSet object) { + kryo.writeClassAndObject(output, object.comparator()); + output.writeInt(object.size(), true); + for (Object elm : object) { + kryo.writeClassAndObject(output, elm); + } + } + + @Override + public ImmutableSortedSet read(Kryo kryo, Input input, Class> type) { + @SuppressWarnings("unchecked") + ImmutableSortedSet.Builder builder = + ImmutableSortedSet.orderedBy((Comparator) kryo.readClassAndObject(input)); + final int size = input.readInt(true); + for (int i = 0; i < size; ++i) { + builder.add(kryo.readClassAndObject(input)); + } + return builder.build(); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/guava/LinkedHashMultimapSerializer.java b/src/main/java/de/javakaffee/kryoserializers/guava/LinkedHashMultimapSerializer.java index 7099e8b7..9bcca48b 100644 --- a/src/main/java/de/javakaffee/kryoserializers/guava/LinkedHashMultimapSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/guava/LinkedHashMultimapSerializer.java @@ -1,45 +1,62 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; - import com.google.common.collect.LinkedHashMultimap; /** * A kryo {@link Serializer} for guava-libraries {@link LinkedHashMultimap}. * This does not yet support {@link Kryo#copy(java.lang.Object)}. */ -public class LinkedHashMultimapSerializer extends MultimapSerializerBase> { - - private static final boolean DOES_NOT_ACCEPT_NULL = false; - - private static final boolean IMMUTABLE = false; - - public LinkedHashMultimapSerializer() { - super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); - } - - @Override - public void write(Kryo kryo, Output output, LinkedHashMultimap multimap) { - writeMultimap(kryo, output, multimap); - } - - @Override - public LinkedHashMultimap read(Kryo kryo, Input input, Class> type) { - final LinkedHashMultimap multimap = LinkedHashMultimap.create(); - readMultimap(kryo, input, multimap); - return multimap; - } - - /** - * Creates a new {@link LinkedHashMultimapSerializer} and registers its serializer. - * - * @param kryo the {@link Kryo} instance to set the serializer on - */ - public static void registerSerializers(final Kryo kryo) { - final LinkedHashMultimapSerializer serializer = new LinkedHashMultimapSerializer(); - kryo.register(LinkedHashMultimap.class, serializer); - } +public class LinkedHashMultimapSerializer + extends MultimapSerializerBase> { + + private static final boolean DOES_NOT_ACCEPT_NULL = false; + + private static final boolean IMMUTABLE = false; + + public LinkedHashMultimapSerializer() { + super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); + } + + /** + * Creates a new {@link LinkedHashMultimapSerializer} and registers its serializer. + * + * @param kryo the {@link Kryo} instance to set the serializer on + */ + public static void registerSerializers(final Kryo kryo) { + final LinkedHashMultimapSerializer serializer = new LinkedHashMultimapSerializer(); + kryo.register(LinkedHashMultimap.class, serializer); + } + + @Override + public void write(Kryo kryo, Output output, LinkedHashMultimap multimap) { + writeMultimap(kryo, output, multimap); + } + + @Override + public LinkedHashMultimap read(Kryo kryo, Input input, + Class> type) { + final LinkedHashMultimap multimap = LinkedHashMultimap.create(); + readMultimap(kryo, input, multimap); + return multimap; + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/guava/LinkedListMultimapSerializer.java b/src/main/java/de/javakaffee/kryoserializers/guava/LinkedListMultimapSerializer.java index 5599b023..a375b68d 100644 --- a/src/main/java/de/javakaffee/kryoserializers/guava/LinkedListMultimapSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/guava/LinkedListMultimapSerializer.java @@ -1,45 +1,62 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; - import com.google.common.collect.LinkedListMultimap; /** * A kryo {@link Serializer} for guava-libraries {@link LinkedListMultimap}. * This does not yet support {@link Kryo#copy(java.lang.Object)}. */ -public class LinkedListMultimapSerializer extends MultimapSerializerBase> { - - private static final boolean DOES_NOT_ACCEPT_NULL = false; - - private static final boolean IMMUTABLE = false; - - public LinkedListMultimapSerializer() { - super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); - } - - @Override - public void write(Kryo kryo, Output output, LinkedListMultimap multimap) { - writeMultimap(kryo, output, multimap); - } - - @Override - public LinkedListMultimap read(Kryo kryo, Input input, Class> type) { - final LinkedListMultimap multimap = LinkedListMultimap.create(); - readMultimap(kryo, input, multimap); - return multimap; - } - - /** - * Creates a new {@link LinkedListMultimapSerializer} and registers its serializer. - * - * @param kryo the {@link Kryo} instance to set the serializer on - */ - public static void registerSerializers(final Kryo kryo) { - final LinkedListMultimapSerializer serializer = new LinkedListMultimapSerializer(); - kryo.register(LinkedListMultimap.class, serializer); - } +public class LinkedListMultimapSerializer + extends MultimapSerializerBase> { + + private static final boolean DOES_NOT_ACCEPT_NULL = false; + + private static final boolean IMMUTABLE = false; + + public LinkedListMultimapSerializer() { + super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); + } + + /** + * Creates a new {@link LinkedListMultimapSerializer} and registers its serializer. + * + * @param kryo the {@link Kryo} instance to set the serializer on + */ + public static void registerSerializers(final Kryo kryo) { + final LinkedListMultimapSerializer serializer = new LinkedListMultimapSerializer(); + kryo.register(LinkedListMultimap.class, serializer); + } + + @Override + public void write(Kryo kryo, Output output, LinkedListMultimap multimap) { + writeMultimap(kryo, output, multimap); + } + + @Override + public LinkedListMultimap read(Kryo kryo, Input input, + Class> type) { + final LinkedListMultimap multimap = LinkedListMultimap.create(); + readMultimap(kryo, input, multimap); + return multimap; + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/guava/MultimapSerializerBase.java b/src/main/java/de/javakaffee/kryoserializers/guava/MultimapSerializerBase.java index 67bfe88c..4d6738e9 100644 --- a/src/main/java/de/javakaffee/kryoserializers/guava/MultimapSerializerBase.java +++ b/src/main/java/de/javakaffee/kryoserializers/guava/MultimapSerializerBase.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; import java.util.Map; @@ -6,29 +22,29 @@ import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; - import com.google.common.collect.Multimap; public abstract class MultimapSerializerBase> extends Serializer { - public MultimapSerializerBase(boolean acceptsNull, boolean immutable) { - super(acceptsNull, immutable); - } + public MultimapSerializerBase(boolean acceptsNull, boolean immutable) { + super(acceptsNull, immutable); + } - protected void writeMultimap(Kryo kryo, Output output, Multimap multimap) { - output.writeInt(multimap.size(), true); - for (final Map.Entry entry : multimap.entries()) { - kryo.writeClassAndObject(output, entry.getKey()); - kryo.writeClassAndObject(output, entry.getValue()); - } - } + protected void writeMultimap(Kryo kryo, Output output, Multimap multimap) { + output.writeInt(multimap.size(), true); + for (final Map.Entry entry : multimap.entries()) { + kryo.writeClassAndObject(output, entry.getKey()); + kryo.writeClassAndObject(output, entry.getValue()); + } + } - protected void readMultimap(Kryo kryo, Input input, Multimap multimap) { - final int size = input.readInt(true); - for (int i = 0; i < size; ++i) { - final K key = (K) kryo.readClassAndObject(input); - final V value = (V) kryo.readClassAndObject(input); - multimap.put(key, value); - } - } + @SuppressWarnings("unchecked") + protected void readMultimap(Kryo kryo, Input input, Multimap multimap) { + final int size = input.readInt(true); + for (int i = 0; i < size; ++i) { + final K key = (K) kryo.readClassAndObject(input); + final V value = (V) kryo.readClassAndObject(input); + multimap.put(key, value); + } + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/guava/ReverseListSerializer.java b/src/main/java/de/javakaffee/kryoserializers/guava/ReverseListSerializer.java index 65a9b6ba..fa454c87 100644 --- a/src/main/java/de/javakaffee/kryoserializers/guava/ReverseListSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/guava/ReverseListSerializer.java @@ -1,78 +1,94 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; -import com.google.common.collect.Lists; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.serializers.CollectionSerializer; - -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; /** - * A {@link Lists.ReverseList} Serializer. + * A {@link ImmutableList#reverse()} Serializer. * Treat as a {@link List} by reversing before write and after read. */ public abstract class ReverseListSerializer extends Serializer> { - private static final CollectionSerializer serializer = new CollectionSerializer(); + private static final CollectionSerializer serializer = new CollectionSerializer(); - @SuppressWarnings("unchecked") - @Override - public void write(Kryo kryo, Output output, List object) { - // reverse the ReverseList to get the "forward" list, and treat as regular List. - List forwardList = Lists.reverse(object); - serializer.write(kryo, output, forwardList); - } + public static void registerSerializers(final Kryo kryo) { + kryo.register(Lists.reverse(Lists.newLinkedList()).getClass(), forReverseList()); + kryo.register(Lists.reverse(Lists.newArrayList()).getClass(), forRandomAccessReverseList()); + } - @SuppressWarnings("unchecked") - @Override - public List copy(Kryo kryo, List original) { - List forwardList = Lists.reverse(original); - return Lists.reverse((List) serializer.copy(kryo, forwardList)); - } + public static ReverseListSerializer forReverseList() { + return new ReverseListSerializer.ReverseList(); + } - public static void registerSerializers(final Kryo kryo) { - kryo.register(Lists.reverse(Lists.newLinkedList()).getClass(), forReverseList()); - kryo.register(Lists.reverse(Lists.newArrayList()).getClass(), forRandomAccessReverseList()); - } + public static ReverseListSerializer forRandomAccessReverseList() { + return new ReverseListSerializer.RandomAccessReverseList(); + } - public static ReverseListSerializer forReverseList() { - return new ReverseListSerializer.ReverseList(); - } + @SuppressWarnings("unchecked") + @Override + public void write(Kryo kryo, Output output, List object) { + // reverse the ReverseList to get the "forward" list, and treat as regular List. + List forwardList = Lists.reverse(object); + serializer.write(kryo, output, forwardList); + } - public static ReverseListSerializer forRandomAccessReverseList() { - return new ReverseListSerializer.RandomAccessReverseList(); - } + @SuppressWarnings("unchecked") + @Override + public List copy(Kryo kryo, List original) { + List forwardList = Lists.reverse(original); + return Lists.reverse((List) serializer.copy(kryo, forwardList)); + } - /** - * A {@link Lists.ReverseList} implementation based on a {@link LinkedList}. - */ - private static class ReverseList extends ReverseListSerializer { + /** + * A {@link Lists.ReverseList} implementation based on a {@link LinkedList}. + */ + private static class ReverseList extends ReverseListSerializer { - @SuppressWarnings("unchecked") - @Override - public List read(Kryo kryo, Input input, Class> type) { - // reading a "forward" list as a LinkedList and returning the reversed list. - List forwardList = (List) serializer.read(kryo, input, (Class) LinkedList.class); - return Lists.reverse(forwardList); - } - } + @SuppressWarnings("unchecked") + @Override + public List read(Kryo kryo, Input input, Class> type) { + // reading a "forward" list as a LinkedList and returning the reversed list. + List forwardList = (List) serializer.read(kryo, input, (Class) LinkedList.class); + return Lists.reverse(forwardList); + } + } - /** - * A {@link Lists.ReverseList} implementation based on an {@link ArrayList}. - */ - private static class RandomAccessReverseList extends ReverseListSerializer { + /** + * A {@link Lists.ReverseList} implementation based on an {@link ArrayList}. + */ + private static class RandomAccessReverseList extends ReverseListSerializer { - @SuppressWarnings("unchecked") - @Override - public List read(Kryo kryo, Input input, Class> type) { - // reading a "forward" list as a ArrayList and returning the reversed list. - List forwardList = (List) serializer.read(kryo, input, (Class) ArrayList.class); - return Lists.reverse(forwardList); - } - } + @SuppressWarnings("unchecked") + @Override + public List read(Kryo kryo, Input input, Class> type) { + // reading a "forward" list as a ArrayList and returning the reversed list. + List forwardList = (List) serializer.read(kryo, input, (Class) ArrayList.class); + return Lists.reverse(forwardList); + } + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/guava/TreeMultimapSerializer.java b/src/main/java/de/javakaffee/kryoserializers/guava/TreeMultimapSerializer.java index 7bae7d12..68e3b2e4 100644 --- a/src/main/java/de/javakaffee/kryoserializers/guava/TreeMultimapSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/guava/TreeMultimapSerializer.java @@ -1,10 +1,25 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; - import com.google.common.collect.TreeMultimap; /** @@ -12,36 +27,38 @@ * The default comparator is assumed so the multimaps are not null-safe. * This does not yet support {@link Kryo#copy(java.lang.Object)}. */ -public class TreeMultimapSerializer extends MultimapSerializerBase> { - - /* assumes default comparator */ - private static final boolean DOES_NOT_ACCEPT_NULL = true; - - private static final boolean IMMUTABLE = false; - - public TreeMultimapSerializer() { - super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); - } - - @Override - public void write(Kryo kryo, Output output, TreeMultimap multimap) { - writeMultimap(kryo, output, multimap); - } - - @Override - public TreeMultimap read(Kryo kryo, Input input, Class> type) { - final TreeMultimap multimap = TreeMultimap.create(); - readMultimap(kryo, input, multimap); - return multimap; - } - - /** - * Creates a new {@link TreeMultimapSerializer} and registers its serializer. - * - * @param kryo the {@link Kryo} instance to set the serializer on - */ - public static void registerSerializers(final Kryo kryo) { - final TreeMultimapSerializer serializer = new TreeMultimapSerializer(); - kryo.register(TreeMultimap.class, serializer); - } +public class TreeMultimapSerializer + extends MultimapSerializerBase> { + + /* assumes default comparator */ + private static final boolean DOES_NOT_ACCEPT_NULL = true; + + private static final boolean IMMUTABLE = false; + + public TreeMultimapSerializer() { + super(DOES_NOT_ACCEPT_NULL, IMMUTABLE); + } + + /** + * Creates a new {@link TreeMultimapSerializer} and registers its serializer. + * + * @param kryo the {@link Kryo} instance to set the serializer on + */ + public static void registerSerializers(final Kryo kryo) { + final TreeMultimapSerializer serializer = new TreeMultimapSerializer(); + kryo.register(TreeMultimap.class, serializer); + } + + @Override + public void write(Kryo kryo, Output output, TreeMultimap multimap) { + writeMultimap(kryo, output, multimap); + } + + @Override + public TreeMultimap read(Kryo kryo, Input input, + Class> type) { + final TreeMultimap multimap = TreeMultimap.create(); + readMultimap(kryo, input, multimap); + return multimap; + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/guava/UnmodifiableNavigableSetSerializer.java b/src/main/java/de/javakaffee/kryoserializers/guava/UnmodifiableNavigableSetSerializer.java index d94df4fd..036b96c8 100644 --- a/src/main/java/de/javakaffee/kryoserializers/guava/UnmodifiableNavigableSetSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/guava/UnmodifiableNavigableSetSerializer.java @@ -1,5 +1,25 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; +import java.lang.reflect.Field; +import java.util.NavigableSet; +import java.util.TreeSet; + import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; @@ -8,74 +28,71 @@ import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Sets; -import java.lang.reflect.Field; -import java.util.NavigableSet; -import java.util.TreeSet; - /** * A kryo {@link Serializer} for guava-libraries {@link ImmutableSortedSet}. */ public class UnmodifiableNavigableSetSerializer extends Serializer> { - Field delegate; + Field delegate; - public UnmodifiableNavigableSetSerializer() { - // Do not allow nulls - super(false); - try { - Class clazz = Class.forName(Sets.class.getCanonicalName() + "$UnmodifiableNavigableSet"); - delegate = clazz.getDeclaredField("delegate"); - delegate.setAccessible(true); - } catch (IllegalArgumentException e) { - throw new RuntimeException("Issues reflectively writing UnmodifiableNavigableSet", e); - } catch (ClassNotFoundException e) { - throw new RuntimeException("Issues reflectively writing UnmodifiableNavigableSet", e); - } catch (SecurityException e) { - throw new RuntimeException("Issues reflectively writing UnmodifiableNavigableSet", e); - } catch (NoSuchFieldException e) { - throw new RuntimeException("Issues reflectively writing UnmodifiableNavigableSet", e); - } - } + public UnmodifiableNavigableSetSerializer() { + // Do not allow nulls + super(false); + try { + Class clazz = Class.forName(Sets.class.getCanonicalName() + "$UnmodifiableNavigableSet"); + delegate = clazz.getDeclaredField("delegate"); + delegate.setAccessible(true); + } catch (IllegalArgumentException e) { + throw new RuntimeException("Issues reflectively writing UnmodifiableNavigableSet", e); + } catch (ClassNotFoundException e) { + throw new RuntimeException("Issues reflectively writing UnmodifiableNavigableSet", e); + } catch (SecurityException e) { + throw new RuntimeException("Issues reflectively writing UnmodifiableNavigableSet", e); + } catch (NoSuchFieldException e) { + throw new RuntimeException("Issues reflectively writing UnmodifiableNavigableSet", e); + } + } - @VisibleForTesting - protected Object getDelegateFromUnmodifiableNavigableSet(NavigableSet object) { - try { - return delegate.get(object); - } catch (IllegalArgumentException e) { - throw new RuntimeException("Issues reflectively writing UnmodifiableNavigableSet", e); - } catch (IllegalAccessException e) { - throw new RuntimeException("Issues reflectively writing UnmodifiableNavigableSet", e); - } - } + /** + * Creates a new {@link UnmodifiableNavigableSetSerializer} and registers its serializer + * for the UnmodifiableNavigableSetSerializer related class. + * + * @param kryo the {@link Kryo} instance to set the serializer on + */ + public static void registerSerializers(final Kryo kryo) { - @Override - public void write(Kryo kryo, Output output, NavigableSet object) { - // We want to preserve the underlying delegate class, so we need to reflectively get it and write it directly via kryo - kryo.writeClassAndObject(output, getDelegateFromUnmodifiableNavigableSet(object)); - } + // UnmodifiableNavigableSetSerializer (private class) - @Override - public NavigableSet read(Kryo kryo, Input input, Class> type) { - return Sets.unmodifiableNavigableSet((NavigableSet) kryo.readClassAndObject(input)); - } + final UnmodifiableNavigableSetSerializer serializer = new UnmodifiableNavigableSetSerializer(); - @Override - public NavigableSet copy(Kryo kryo, NavigableSet original) { - return Sets.unmodifiableNavigableSet((NavigableSet) kryo.copy(getDelegateFromUnmodifiableNavigableSet(original))); - } + kryo.register(Sets.unmodifiableNavigableSet(new TreeSet()).getClass(), serializer); + } - /** - * Creates a new {@link UnmodifiableNavigableSetSerializer} and registers its serializer - * for the UnmodifiableNavigableSetSerializer related class. - * - * @param kryo the {@link Kryo} instance to set the serializer on - */ - public static void registerSerializers(final Kryo kryo) { + @VisibleForTesting + protected Object getDelegateFromUnmodifiableNavigableSet(NavigableSet object) { + try { + return delegate.get(object); + } catch (IllegalArgumentException e) { + throw new RuntimeException("Issues reflectively writing UnmodifiableNavigableSet", e); + } catch (IllegalAccessException e) { + throw new RuntimeException("Issues reflectively writing UnmodifiableNavigableSet", e); + } + } - // UnmodifiableNavigableSetSerializer (private class) + @Override + public void write(Kryo kryo, Output output, NavigableSet object) { + // We want to preserve the underlying delegate class, so we need to reflectively get it and write it directly via kryo + kryo.writeClassAndObject(output, getDelegateFromUnmodifiableNavigableSet(object)); + } - final UnmodifiableNavigableSetSerializer serializer = new UnmodifiableNavigableSetSerializer(); + @Override + public NavigableSet read(Kryo kryo, Input input, Class> type) { + return Sets.unmodifiableNavigableSet((NavigableSet) kryo.readClassAndObject(input)); + } - kryo.register(Sets.unmodifiableNavigableSet(new TreeSet()).getClass(), serializer); - } + @Override + public NavigableSet copy(Kryo kryo, NavigableSet original) { + return Sets.unmodifiableNavigableSet( + (NavigableSet) kryo.copy(getDelegateFromUnmodifiableNavigableSet(original))); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/jodatime/IdentifiableChronology.java b/src/main/java/de/javakaffee/kryoserializers/jodatime/IdentifiableChronology.java index 4f91d45e..0394a7e1 100644 --- a/src/main/java/de/javakaffee/kryoserializers/jodatime/IdentifiableChronology.java +++ b/src/main/java/de/javakaffee/kryoserializers/jodatime/IdentifiableChronology.java @@ -1,14 +1,23 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.jodatime; import org.joda.time.Chronology; -import org.joda.time.chrono.BuddhistChronology; -import org.joda.time.chrono.CopticChronology; -import org.joda.time.chrono.EthiopicChronology; -import org.joda.time.chrono.GJChronology; -import org.joda.time.chrono.GregorianChronology; -import org.joda.time.chrono.ISOChronology; -import org.joda.time.chrono.IslamicChronology; -import org.joda.time.chrono.JulianChronology; +import org.joda.time.chrono.*; import com.esotericsoftware.kryo.io.Input; @@ -16,77 +25,78 @@ * An enumeration that provides a String id for subclasses of {@link Chronology}. * For {@link ISOChronology}, null is used as id, as {@link ISOChronology} * is used as default and the id does not have to be serialized. - * + * * @author Martin Grotzke (martin.grotzke@freiheit.com) (initial creation) */ enum IdentifiableChronology { - - ISO( null, ISOChronology.getInstance() ), - COPTIC( "COPTIC", CopticChronology.getInstance() ), - ETHIOPIC( "ETHIOPIC", EthiopicChronology.getInstance()), - GREGORIAN("GREGORIAN", GregorianChronology.getInstance()), - JULIAN("JULIAN", JulianChronology.getInstance()), - ISLAMIC("ISLAMIC",IslamicChronology.getInstance()), - BUDDHIST( "BUDDHIST", BuddhistChronology.getInstance()), - GJ( "GJ", GJChronology.getInstance()); - - private final String _id; - private final Chronology _chronology; - - private IdentifiableChronology( final String id, final Chronology chronology ) { - _id = id; - _chronology = chronology; - } - - public String getId() { - return _id; - } - - /** - * Determines the id for the given {@link Chronology} subclass that later - * can be used to resolve the {@link Chronology} with {@link #valueOfId(String)}. - * For {@link ISOChronology} class null is returned. - * - * @param clazz a subclass of {@link Chronology}. - * @return an id, or null for {@link ISOChronology}. - * @throws IllegalArgumentException if the {@link Chronology} is not supported. - */ - public static String getIdByChronology( final Class clazz ) throws IllegalArgumentException { - for( final IdentifiableChronology item : values() ) { - if ( clazz.equals( item._chronology.getClass() ) ) { - return item._id; - } - } - throw new IllegalArgumentException( "Chronology not supported: " + clazz.getSimpleName() ); - } - - /** - * Returns the chronology of the {@link IdentifiableChronology} matching the - * provided id. If the provided id is null, - * {@link ISOChronology} is returned. - * @param id the id from {@link #getIdByChronology(Class)}. - * @return a matching {@link Chronology} if any was found. - * @throws IllegalArgumentException if no match was found. - */ - public static Chronology valueOfId(final String id) throws IllegalArgumentException { - if ( id == null ) { - return ISO._chronology; - } - for( final IdentifiableChronology item : values() ) { - if ( id.equals( item._id ) ) { - return item._chronology; - } - } - throw new IllegalArgumentException( "No chronology found for id " + id ); - } - - static Chronology readChronology( final Input input ) { - final String chronologyId = input.readString(); - return IdentifiableChronology.valueOfId( "".equals( chronologyId ) ? null : chronologyId ); - } - - static String getChronologyId( final Chronology chronology ) { - return IdentifiableChronology.getIdByChronology( chronology.getClass() ); - } - -} \ No newline at end of file + + ISO(null, ISOChronology.getInstance()), + COPTIC("COPTIC", CopticChronology.getInstance()), + ETHIOPIC("ETHIOPIC", EthiopicChronology.getInstance()), + GREGORIAN("GREGORIAN", GregorianChronology.getInstance()), + JULIAN("JULIAN", JulianChronology.getInstance()), + ISLAMIC("ISLAMIC", IslamicChronology.getInstance()), + BUDDHIST("BUDDHIST", BuddhistChronology.getInstance()), + GJ("GJ", GJChronology.getInstance()); + + private final String _id; + private final Chronology _chronology; + + private IdentifiableChronology(final String id, final Chronology chronology) { + _id = id; + _chronology = chronology; + } + + /** + * Determines the id for the given {@link Chronology} subclass that later + * can be used to resolve the {@link Chronology} with {@link #valueOfId(String)}. + * For {@link ISOChronology} class null is returned. + * + * @param clazz a subclass of {@link Chronology}. + * @return an id, or null for {@link ISOChronology}. + * @throws IllegalArgumentException if the {@link Chronology} is not supported. + */ + public static String getIdByChronology(final Class clazz) throws IllegalArgumentException { + for (final IdentifiableChronology item : values()) { + if (clazz.equals(item._chronology.getClass())) { + return item._id; + } + } + throw new IllegalArgumentException("Chronology not supported: " + clazz.getSimpleName()); + } + + /** + * Returns the chronology of the {@link IdentifiableChronology} matching the + * provided id. If the provided id is null, + * {@link ISOChronology} is returned. + * + * @param id the id from {@link #getIdByChronology(Class)}. + * @return a matching {@link Chronology} if any was found. + * @throws IllegalArgumentException if no match was found. + */ + public static Chronology valueOfId(final String id) throws IllegalArgumentException { + if (id == null) { + return ISO._chronology; + } + for (final IdentifiableChronology item : values()) { + if (id.equals(item._id)) { + return item._chronology; + } + } + throw new IllegalArgumentException("No chronology found for id " + id); + } + + static Chronology readChronology(final Input input) { + final String chronologyId = input.readString(); + return IdentifiableChronology.valueOfId("".equals(chronologyId) ? null : chronologyId); + } + + static String getChronologyId(final Chronology chronology) { + return IdentifiableChronology.getIdByChronology(chronology.getClass()); + } + + public String getId() { + return _id; + } + +} diff --git a/src/main/java/de/javakaffee/kryoserializers/jodatime/JodaDateTimeSerializer.java b/src/main/java/de/javakaffee/kryoserializers/jodatime/JodaDateTimeSerializer.java index 3648a655..fa58dc69 100644 --- a/src/main/java/de/javakaffee/kryoserializers/jodatime/JodaDateTimeSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/jodatime/JodaDateTimeSerializer.java @@ -19,14 +19,7 @@ import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; -import org.joda.time.chrono.BuddhistChronology; -import org.joda.time.chrono.CopticChronology; -import org.joda.time.chrono.EthiopicChronology; -import org.joda.time.chrono.GJChronology; -import org.joda.time.chrono.GregorianChronology; -import org.joda.time.chrono.ISOChronology; -import org.joda.time.chrono.IslamicChronology; -import org.joda.time.chrono.JulianChronology; +import org.joda.time.chrono.*; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; @@ -52,49 +45,48 @@ *
  • {@link BuddhistChronology}
  • *
  • {@link GJChronology}
  • * - *

    * * @author Martin Grotzke */ public class JodaDateTimeSerializer extends Serializer { - static final String MILLIS = "millis"; - static final String DATE_TIME = "dt"; - static final String CHRONOLOGY = "ch"; - static final String TIME_ZONE = "tz"; + static final String MILLIS = "millis"; + static final String DATE_TIME = "dt"; + static final String CHRONOLOGY = "ch"; + static final String TIME_ZONE = "tz"; - public JodaDateTimeSerializer() { - setImmutable(true); - } + public JodaDateTimeSerializer() { + setImmutable(true); + } - @Override - public DateTime read(final Kryo kryo, final Input input, final Class type) { - final long millis = input.readLong(true); - final Chronology chronology = IdentifiableChronology.readChronology( input ); - final DateTimeZone tz = readTimeZone( input ); - return new DateTime( millis, chronology.withZone( tz ) ); - } + @Override + public DateTime read(final Kryo kryo, final Input input, final Class type) { + final long millis = input.readLong(true); + final Chronology chronology = IdentifiableChronology.readChronology(input); + final DateTimeZone tz = readTimeZone(input); + return new DateTime(millis, chronology.withZone(tz)); + } - @Override - public void write(final Kryo kryo, final Output output, final DateTime obj) { - output.writeLong(obj.getMillis(), true); + @Override + public void write(final Kryo kryo, final Output output, final DateTime obj) { + output.writeLong(obj.getMillis(), true); - final String chronologyId = IdentifiableChronology.getChronologyId( obj.getChronology() ); - output.writeString(chronologyId == null ? "" : chronologyId); + final String chronologyId = IdentifiableChronology.getChronologyId(obj.getChronology()); + output.writeString(chronologyId == null ? "" : chronologyId); - output.writeString(obj.getZone().getID()); - } + output.writeString(obj.getZone().getID()); + } - private DateTimeZone readTimeZone( final Input input ) { - final String tz = input.readString(); + private DateTimeZone readTimeZone(final Input input) { + final String tz = input.readString(); - // special case for "" to maintain backwards compatibility, but generally this is considered harmful, - // potentially remove this with the next major release that involves breaking changes - // https://github.com/magro/kryo-serializers/issues/30 - if ("".equals(tz)) { - return DateTimeZone.getDefault(); - } + // special case for "" to maintain backwards compatibility, but generally this is considered harmful, + // potentially remove this with the next major release that involves breaking changes + // https://github.com/magro/kryo-serializers/issues/30 + if ("".equals(tz)) { + return DateTimeZone.getDefault(); + } - return DateTimeZone.forID(tz); - } + return DateTimeZone.forID(tz); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/jodatime/JodaIntervalSerializer.java b/src/main/java/de/javakaffee/kryoserializers/jodatime/JodaIntervalSerializer.java index 115011ae..40f5b5a3 100644 --- a/src/main/java/de/javakaffee/kryoserializers/jodatime/JodaIntervalSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/jodatime/JodaIntervalSerializer.java @@ -1,4 +1,6 @@ /* + * Copyright 2018 Martin Grotzke + * * 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 @@ -16,14 +18,7 @@ import org.joda.time.Chronology; import org.joda.time.Interval; -import org.joda.time.chrono.BuddhistChronology; -import org.joda.time.chrono.CopticChronology; -import org.joda.time.chrono.EthiopicChronology; -import org.joda.time.chrono.GJChronology; -import org.joda.time.chrono.GregorianChronology; -import org.joda.time.chrono.ISOChronology; -import org.joda.time.chrono.IslamicChronology; -import org.joda.time.chrono.JulianChronology; +import org.joda.time.chrono.*; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; @@ -31,7 +26,7 @@ import com.esotericsoftware.kryo.io.Output; /** - * A format for Joda {@link Interval}, that stores the start and end millis, and chronology + * A format for Joda {@link Interval}, that stores the start and end millis, and chronology * as separate attributes. If the chronology is {@link ISOChronology}, * the attribute is omitted, thus {@link ISOChronology} is seen as default. *

    @@ -46,36 +41,33 @@ *

  • {@link BuddhistChronology}
  • *
  • {@link GJChronology}
  • * - *

    - * */ public class JodaIntervalSerializer extends Serializer { - public JodaIntervalSerializer() { - setImmutable(true); - } + public JodaIntervalSerializer() { + setImmutable(true); + } + + @Override + public Interval read(final Kryo kryo, final Input input, final Class type) { + + long startMillis = input.readLong(true); + long endMillis = input.readLong(true); + + final Chronology chronology = IdentifiableChronology.readChronology(input); + + return new Interval(startMillis, endMillis, chronology); + } - @Override - public Interval read(final Kryo kryo, final Input input, final Class type) { - - long startMillis = input.readLong(true); - long endMillis = input.readLong(true); - - final Chronology chronology = IdentifiableChronology.readChronology( input ); - - return new Interval(startMillis, endMillis, chronology); - } + @Override + public void write(final Kryo kryo, final Output output, final Interval obj) { + final long startMillis = obj.getStartMillis(); + final long endMillis = obj.getEndMillis(); + final String chronologyId = IdentifiableChronology.getChronologyId(obj.getChronology()); - @Override - public void write(final Kryo kryo, final Output output, final Interval obj) { - final long startMillis = obj.getStartMillis(); - final long endMillis = obj.getEndMillis(); - final String chronologyId = IdentifiableChronology.getChronologyId( obj.getChronology() ); - - output.writeLong(startMillis, true); - output.writeLong(endMillis, true); - output.writeString(chronologyId == null ? "" : chronologyId); - } - + output.writeLong(startMillis, true); + output.writeLong(endMillis, true); + output.writeString(chronologyId == null ? "" : chronologyId); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/jodatime/JodaLocalDateSerializer.java b/src/main/java/de/javakaffee/kryoserializers/jodatime/JodaLocalDateSerializer.java index 35ac8dbe..91c12876 100644 --- a/src/main/java/de/javakaffee/kryoserializers/jodatime/JodaLocalDateSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/jodatime/JodaLocalDateSerializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 Rennie Petersen + * Copyright 2018 Martin Grotzke * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,14 +18,7 @@ import org.joda.time.Chronology; import org.joda.time.LocalDate; -import org.joda.time.chrono.BuddhistChronology; -import org.joda.time.chrono.CopticChronology; -import org.joda.time.chrono.EthiopicChronology; -import org.joda.time.chrono.GJChronology; -import org.joda.time.chrono.GregorianChronology; -import org.joda.time.chrono.ISOChronology; -import org.joda.time.chrono.IslamicChronology; -import org.joda.time.chrono.JulianChronology; +import org.joda.time.chrono.*; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; @@ -38,7 +31,7 @@ * No time zone is involved. If the chronology is {@link org.joda.time.chrono.ISOChronology} the * attribute is serialized as an empty string, thus {@link org.joda.time.chrono.ISOChronology} is * considered to be default. - * + *

    * Note that internally the LocalDate object makes use of an iLocalMillis value, but that field is * not accessible for reading here because the getLocalMillis() method is protected. There could * conceivably be cases where a user has created a derived version of LocalDate, and is using the @@ -56,33 +49,29 @@ *

  • {@link BuddhistChronology}
  • *
  • {@link GJChronology}
  • * - *

    * * @author Rennie Petersen */ public class JodaLocalDateSerializer extends Serializer { - public JodaLocalDateSerializer() { - setImmutable(true); - } + public JodaLocalDateSerializer() { + setImmutable(true); + } - @Override - public LocalDate read(final Kryo kryo, final Input input, final Class type) { - final int packedYearMonthDay = input.readInt(true); - final Chronology chronology = IdentifiableChronology.readChronology(input); - return new LocalDate(packedYearMonthDay / (13 * 32), - (packedYearMonthDay % (13 * 32)) / 32, - packedYearMonthDay % 32, - chronology); - } + @Override + public LocalDate read(final Kryo kryo, final Input input, final Class type) { + final int packedYearMonthDay = input.readInt(true); + final Chronology chronology = IdentifiableChronology.readChronology(input); + return new LocalDate(packedYearMonthDay / (13 * 32), (packedYearMonthDay % (13 * 32)) / 32, + packedYearMonthDay % 32, chronology); + } - @Override - public void write(final Kryo kryo, final Output output, final LocalDate localDate) { - final int packedYearMonthDay = localDate.getYear() * 13 * 32 + - localDate.getMonthOfYear() * 32 + - localDate.getDayOfMonth(); - output.writeInt(packedYearMonthDay, true); - final String chronologyId = IdentifiableChronology.getChronologyId(localDate.getChronology()); - output.writeString(chronologyId == null ? "" : chronologyId); - } + @Override + public void write(final Kryo kryo, final Output output, final LocalDate localDate) { + final int packedYearMonthDay = + localDate.getYear() * 13 * 32 + localDate.getMonthOfYear() * 32 + localDate.getDayOfMonth(); + output.writeInt(packedYearMonthDay, true); + final String chronologyId = IdentifiableChronology.getChronologyId(localDate.getChronology()); + output.writeString(chronologyId == null ? "" : chronologyId); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/jodatime/JodaLocalDateTimeSerializer.java b/src/main/java/de/javakaffee/kryoserializers/jodatime/JodaLocalDateTimeSerializer.java index c3e94d36..84069c14 100644 --- a/src/main/java/de/javakaffee/kryoserializers/jodatime/JodaLocalDateTimeSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/jodatime/JodaLocalDateTimeSerializer.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 Rennie Petersen + * Copyright 2018 Martin Grotzke * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,19 +18,12 @@ import org.joda.time.Chronology; import org.joda.time.LocalDateTime; -import org.joda.time.chrono.BuddhistChronology; -import org.joda.time.chrono.CopticChronology; -import org.joda.time.chrono.EthiopicChronology; -import org.joda.time.chrono.GJChronology; -import org.joda.time.chrono.GregorianChronology; -import org.joda.time.chrono.ISOChronology; -import org.joda.time.chrono.IslamicChronology; -import org.joda.time.chrono.JulianChronology; +import org.joda.time.chrono.*; import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; -import com.esotericsoftware.kryo.Serializer; /** * A Kryo serializer for joda {@link LocalDateTime}. The LocalDateTime object is read or written as @@ -50,38 +43,32 @@ *
  • {@link BuddhistChronology}
  • *
  • {@link GJChronology}
  • * - *

    * * @author Rennie Petersen */ public class JodaLocalDateTimeSerializer extends Serializer { - public JodaLocalDateTimeSerializer() { setImmutable(true); } + public JodaLocalDateTimeSerializer() { + setImmutable(true); + } - @Override - public LocalDateTime read(Kryo kryo, Input input, Class type) { - final long packedLocalDateTime = input.readLong(true); - final int packedYearMonthDay = (int)(packedLocalDateTime / 86400000); - final int millisOfDay = (int)(packedLocalDateTime % 86400000); - final Chronology chronology = IdentifiableChronology.readChronology(input); - return new LocalDateTime(packedYearMonthDay / (13 * 32), - (packedYearMonthDay % (13 * 32)) / 32, - packedYearMonthDay % 32, - millisOfDay / 3600000, - (millisOfDay % 3600000) / 60000, - (millisOfDay % 60000) / 1000, - millisOfDay % 1000, - chronology ); - } + @Override + public LocalDateTime read(Kryo kryo, Input input, Class type) { + final long packedLocalDateTime = input.readLong(true); + final int packedYearMonthDay = (int) (packedLocalDateTime / 86400000); + final int millisOfDay = (int) (packedLocalDateTime % 86400000); + final Chronology chronology = IdentifiableChronology.readChronology(input); + return new LocalDateTime(packedYearMonthDay / (13 * 32), (packedYearMonthDay % (13 * 32)) / 32, + packedYearMonthDay % 32, millisOfDay / 3600000, (millisOfDay % 3600000) / 60000, + (millisOfDay % 60000) / 1000, millisOfDay % 1000, chronology); + } - @Override - public void write(Kryo kryo, Output output, LocalDateTime localDateTime) { - final int packedYearMonthDay = localDateTime.getYear() * 13 * 32 + - localDateTime.getMonthOfYear() * 32 + - localDateTime.getDayOfMonth(); - output.writeLong((long)packedYearMonthDay * 86400000 + localDateTime.getMillisOfDay(), true); - final String chronologyId = - IdentifiableChronology.getChronologyId(localDateTime.getChronology()); - output.writeString(chronologyId == null ? "" : chronologyId); - } + @Override + public void write(Kryo kryo, Output output, LocalDateTime localDateTime) { + final int packedYearMonthDay = + localDateTime.getYear() * 13 * 32 + localDateTime.getMonthOfYear() * 32 + localDateTime.getDayOfMonth(); + output.writeLong((long) packedYearMonthDay * 86400000 + localDateTime.getMillisOfDay(), true); + final String chronologyId = IdentifiableChronology.getChronologyId(localDateTime.getChronology()); + output.writeString(chronologyId == null ? "" : chronologyId); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/jodatime/JodaLocalTimeSerializer.java b/src/main/java/de/javakaffee/kryoserializers/jodatime/JodaLocalTimeSerializer.java index 841606e9..2160c314 100644 --- a/src/main/java/de/javakaffee/kryoserializers/jodatime/JodaLocalTimeSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/jodatime/JodaLocalTimeSerializer.java @@ -1,14 +1,31 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.jodatime; -import com.esotericsoftware.kryo.Kryo; -import com.esotericsoftware.kryo.Serializer; -import com.esotericsoftware.kryo.io.Input; -import com.esotericsoftware.kryo.io.Output; import org.joda.time.Chronology; import org.joda.time.DateTimeZone; import org.joda.time.LocalTime; import org.joda.time.chrono.*; +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.Serializer; +import com.esotericsoftware.kryo.io.Input; +import com.esotericsoftware.kryo.io.Output; + /** * A format for Joda {@link LocalTime}, that stores the milliseconds of the day and chronology * as separate attributes. @@ -24,32 +41,31 @@ *
  • {@link BuddhistChronology}
  • *
  • {@link GJChronology}
  • * - *

    * * @author Rob Reeves */ public class JodaLocalTimeSerializer extends Serializer { - @Override - public void write(Kryo kryo, Output output, LocalTime object) { - final int time = object.getMillisOfDay(); - output.writeInt(time, true); + @Override + public void write(Kryo kryo, Output output, LocalTime object) { + final int time = object.getMillisOfDay(); + output.writeLong(time, true); - //LocalTime always converts the internal DateTimeZone to UTC so there is no need to serialize it. - final String chronologyId = IdentifiableChronology.getChronologyId(object.getChronology()); - output.writeString(chronologyId); - } + //LocalTime always converts the internal DateTimeZone to UTC so there is no need to serialize it. + final String chronologyId = IdentifiableChronology.getChronologyId(object.getChronology()); + output.writeString(chronologyId); + } - @Override - public LocalTime read(Kryo kryo, Input input, Class type) { - final int time = input.readInt(true); - final Chronology chronology = IdentifiableChronology.readChronology(input); + @Override + public LocalTime read(Kryo kryo, Input input, Class type) { + final long time = input.readLong(true); + final Chronology chronology = IdentifiableChronology.readChronology(input); - //LocalTime always converts the internal DateTimeZone to UTC. - return new LocalTime(time, chronology.withZone(DateTimeZone.UTC)); - } + //LocalTime always converts the internal DateTimeZone to UTC. + return new LocalTime(time, chronology.withZone(DateTimeZone.UTC)); + } - @Override - public LocalTime copy(Kryo kryo, LocalTime original) { - return new LocalTime(original); - } + @Override + public LocalTime copy(Kryo kryo, LocalTime original) { + return new LocalTime(original); + } } diff --git a/src/main/java/de/javakaffee/kryoserializers/protobuf/ProtobufSerializer.java b/src/main/java/de/javakaffee/kryoserializers/protobuf/ProtobufSerializer.java index c28fd860..48b9fbeb 100644 --- a/src/main/java/de/javakaffee/kryoserializers/protobuf/ProtobufSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/protobuf/ProtobufSerializer.java @@ -1,79 +1,94 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.protobuf; +import static com.esotericsoftware.kryo.Kryo.NULL; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; -import com.google.protobuf.GeneratedMessage; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import static com.esotericsoftware.kryo.Kryo.NULL; +import com.google.protobuf.GeneratedMessageV3; -public class ProtobufSerializer extends Serializer { +public class ProtobufSerializer extends Serializer { - private Method parseFromMethod = null; + private Method parseFromMethod = null; - @Override - public void write(Kryo kryo, Output output, T protobufMessage) { - // If our protobuf is null - if (protobufMessage == null) { - // Write our special null value - output.writeByte(NULL); - output.flush(); + @Override + public void write(Kryo kryo, Output output, T protobufMessage) { + // If our protobuf is null + if (protobufMessage == null) { + // Write our special null value + output.writeByte(NULL); + output.flush(); - // and we're done - return; - } + // and we're done + return; + } - // Otherwise serialize protobuf to a byteArray - byte[] bytes = protobufMessage.toByteArray(); + // Otherwise serialize protobuf to a byteArray + byte[] bytes = protobufMessage.toByteArray(); - // Write the length of our byte array - output.writeInt(bytes.length + 1, true); + // Write the length of our byte array + output.writeInt(bytes.length + 1, true); - // Write the byte array out - output.writeBytes(bytes); - output.flush(); - } + // Write the byte array out + output.writeBytes(bytes); + output.flush(); + } - @Override - public T read(Kryo kryo, Input input, Class type) { - // Read the length of our byte array - int length = input.readInt(true); + @SuppressWarnings("unchecked") + @Override + public T read(Kryo kryo, Input input, Class type) { + // Read the length of our byte array + int length = input.readInt(true); - // If the length is equal to our special null value - if (length == NULL) { - // Just return null - return null; - } - // Otherwise read the byte array length - byte[] bytes = input.readBytes(length - 1); - try { - // Deserialize protobuf - return (T) (getParseFromMethod(type).invoke(type, bytes)); - } catch (NoSuchMethodException e) { - throw new RuntimeException("Unable to deserialize protobuf "+e.getMessage(), e); - } catch (InvocationTargetException e) { - throw new RuntimeException("Unable to deserialize protobuf "+e.getMessage(), e); - } catch (IllegalAccessException e) { - throw new RuntimeException("Unable to deserialize protobuf "+e.getMessage(), e); - } - } + // If the length is equal to our special null value + if (length == NULL) { + // Just return null + return null; + } + // Otherwise read the byte array length + byte[] bytes = input.readBytes(length - 1); + try { + // Deserialize protobuf + return (T) (getParseFromMethod(type).invoke(type, (Object) bytes)); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException("Unable to deserialize protobuf " + e.getMessage(), e); + } + } - /** - * Caches method reflection lookup - * @throws NoSuchMethodException - */ - private Method getParseFromMethod(Class type) throws NoSuchMethodException { - if (parseFromMethod == null) { - parseFromMethod = type.getMethod("parseFrom", byte[].class); - } - return parseFromMethod; - } + /** + * Caches method reflection lookup + * + * @throws NoSuchMethodException should never be thrown + */ + private Method getParseFromMethod(Class type) throws NoSuchMethodException { + if (parseFromMethod == null) { + parseFromMethod = type.getMethod("parseFrom", byte[].class); + } + return parseFromMethod; + } - @Override - public boolean getAcceptsNull () { - return true; - } -} \ No newline at end of file + @Override + public boolean getAcceptsNull() { + return true; + } +} diff --git a/src/main/java/de/javakaffee/kryoserializers/wicket/MiniMapSerializer.java b/src/main/java/de/javakaffee/kryoserializers/wicket/MiniMapSerializer.java index 855d9ba5..e3f58c28 100644 --- a/src/main/java/de/javakaffee/kryoserializers/wicket/MiniMapSerializer.java +++ b/src/main/java/de/javakaffee/kryoserializers/wicket/MiniMapSerializer.java @@ -31,57 +31,58 @@ /** * A format for wicket's {@link MiniMap}. - * + * * @author Martin Grotzke */ public class MiniMapSerializer extends Serializer> { - - /* To be correct we need to know the size of the internal array, otherwise - * we might create a too small MiniMap on deserilization - */ - private static final Field KEYS_FIELD; - - static { - try { - KEYS_FIELD = MiniMap.class.getDeclaredField( "keys" ); - KEYS_FIELD.setAccessible( true ); - } catch ( final Exception e ) { - throw new RuntimeException( "The MiniMap seems to have changed, could not access expected field.", e ); - } - } - private int getMaxEntries( final MiniMap map ) { - try { - return ( (Object[])KEYS_FIELD.get( map ) ).length; - } catch ( final Exception e ) { - throw new RuntimeException( "Could not access keys field.", e ); - } - } + /* To be correct we need to know the size of the internal array, otherwise + * we might create a too small MiniMap on deserilization + */ + private static final Field KEYS_FIELD; + + static { + try { + KEYS_FIELD = MiniMap.class.getDeclaredField("keys"); + KEYS_FIELD.setAccessible(true); + } catch (final Exception e) { + throw new RuntimeException("The MiniMap seems to have changed, could not access expected field.", e); + } + } + + private int getMaxEntries(final MiniMap map) { + try { + return ((Object[]) KEYS_FIELD.get(map)).length; + } catch (final Exception e) { + throw new RuntimeException("Could not access keys field.", e); + } + } - @Override - public void write(final Kryo kryo, final Output output, final MiniMap map) { - output.writeInt(getMaxEntries( map ), true); - output.writeInt( map.size(), true); + @Override + public void write(final Kryo kryo, final Output output, final MiniMap map) { + output.writeInt(getMaxEntries(map), true); + output.writeInt(map.size(), true); - for (final Entry entry : map.entrySet()) { - kryo.writeClassAndObject(output, entry.getKey()); - kryo.writeClassAndObject(output, entry.getValue()); - } + for (final Entry entry : map.entrySet()) { + kryo.writeClassAndObject(output, entry.getKey()); + kryo.writeClassAndObject(output, entry.getValue()); + } - if ( TRACE ) trace( "kryo", "Wrote map: " + map ); - } + if (TRACE) + trace("kryo", "Wrote map: " + map); + } - @Override - public MiniMap read(final Kryo kryo, final Input input, final Class> type) { - final int maxEntries = input.readInt( true ); - final MiniMap result = new MiniMap( maxEntries ); - final int size = input.readInt( true ); - for ( int i = 0; i < size; i++ ) { - final Object key = kryo.readClassAndObject( input ); - final Object value = kryo.readClassAndObject( input ); - result.put( key, value ); - } - return result; - } + @Override + public MiniMap read(final Kryo kryo, final Input input, final Class> type) { + final int maxEntries = input.readInt(true); + final MiniMap result = new MiniMap(maxEntries); + final int size = input.readInt(true); + for (int i = 0; i < size; i++) { + final Object key = kryo.readClassAndObject(input); + final Object value = kryo.readClassAndObject(input); + result.put(key, value); + } + return result; + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/EnumMapSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/EnumMapSerializerTest.java index 41a52598..da62063f 100755 --- a/src/test/java/de/javakaffee/kryoserializers/EnumMapSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/EnumMapSerializerTest.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers; import static org.testng.Assert.*; @@ -15,44 +31,54 @@ * A test case for the {@link EnumMapSerializer}. */ public class EnumMapSerializerTest { - private static enum Vipers { - SNAKE_CHARMER, BLACK_MAMBA, COTTONMOUTH, COPPERHEAD, CALIFORNIA_MOUNTAIN_SNAKE, SIDEWINDER; - } + private Kryo _kryo; + private EnumMap> _original; - private static enum Colors { - BLUE, ORANGE, PINK, WHITE, BROWN, BLONDE; - } - - private Kryo _kryo; - private EnumMap> _original; - - @BeforeTest - protected void beforeTest() { - _kryo = new Kryo(); + @BeforeTest + protected void beforeTest() { + _kryo = new Kryo(); _kryo.register(EnumMap.class, new EnumMapSerializer()); _original = new EnumMap>(Vipers.class); - } - + } + @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test(expectedExceptions={ClassCastException.class}) - public void testCopyEmpty() throws Exception { - EnumMap copy = _kryo.copy(_original); - // The next statement asserts that the key type of the copy is initialized correctly - - // it should throw the expected ClassCastException. - copy.put(Colors.BROWN, new HashSet()); - } + @Test(expectedExceptions = { ClassCastException.class }) + public void testCopyEmpty() throws Exception { + EnumMap copy = _kryo.copy(_original); + // The next statement asserts that the key type of the copy is initialized correctly - + // it should throw the expected ClassCastException. + copy.put(Colors.BROWN, new HashSet()); + } @Test - public void testDeepCopy() throws Exception { + public void testDeepCopy() throws Exception { final Set mambaAka = new HashSet(); mambaAka.add("Beatrix Kiddo"); mambaAka.add("The Bride"); - _original.put(Vipers.BLACK_MAMBA, mambaAka); - - EnumMap> copy = _kryo.copy(_original); - assertNotSame(_original, copy); - assertTrue(copy.containsKey(Vipers.BLACK_MAMBA)); - assertNotSame(_original.get(Vipers.BLACK_MAMBA), copy.get(Vipers.BLACK_MAMBA)); - assertEquals(_original, copy); - } + _original.put(Vipers.BLACK_MAMBA, mambaAka); + + EnumMap> copy = _kryo.copy(_original); + assertNotSame(_original, copy); + assertTrue(copy.containsKey(Vipers.BLACK_MAMBA)); + assertNotSame(_original.get(Vipers.BLACK_MAMBA), copy.get(Vipers.BLACK_MAMBA)); + assertEquals(_original, copy); + } + + private static enum Vipers { + SNAKE_CHARMER, + BLACK_MAMBA, + COTTONMOUTH, + COPPERHEAD, + CALIFORNIA_MOUNTAIN_SNAKE, + SIDEWINDER; + } + + private static enum Colors { + BLUE, + ORANGE, + PINK, + WHITE, + BROWN, + BLONDE; + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/FieldAnnotationAwareSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/FieldAnnotationAwareSerializerTest.java index f6b889ff..c121307d 100644 --- a/src/test/java/de/javakaffee/kryoserializers/FieldAnnotationAwareSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/FieldAnnotationAwareSerializerTest.java @@ -1,15 +1,26 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.testng.Assert.*; -import java.lang.annotation.Annotation; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; +import java.lang.annotation.*; +import java.nio.ByteBuffer; import java.util.Arrays; import org.testng.annotations.Test; @@ -27,98 +38,104 @@ */ public class FieldAnnotationAwareSerializerTest { - // Use Non-ASCII characters in order to be able to check the byte buffer for - // the existence of the string values. - protected static final String FIRST_VALUE = "åæø first value"; - protected static final String SECOND_VALUE = "äöü second value"; + // Use Non-ASCII characters in order to be able to check the byte buffer for + // the existence of the string values. + protected static final String FIRST_VALUE = "\u00e5\u00e6\u00f8 first value"; + protected static final String SECOND_VALUE = "\u00e4\u00f6\u00fc second value"; + + private static final int BUFFER_SIZE = 1024; + + private CustomBean makeBean() { + final CustomBean customBean = new CustomBean(); + customBean.setFirstValue(FIRST_VALUE); + customBean.setSecondValue(SECOND_VALUE); + return customBean; + } - private static final int BUFFER_SIZE = 1024; + private byte[] makeBuffer() { + return new byte[BUFFER_SIZE]; + } - private CustomBean makeBean() { - final CustomBean customBean = new CustomBean(); - customBean.setFirstValue(FIRST_VALUE); - customBean.setSecondValue(SECOND_VALUE); - return customBean; - } + @Test + public void testExcludeFields() throws Exception { - private byte[] makeBuffer() { - return new byte[BUFFER_SIZE]; - } + final Kryo kryo = new Kryo(); + @SuppressWarnings("unchecked") + final SerializerFactory disregardingSerializerFactory = + new FieldAnnotationAwareSerializer.Factory(Arrays.>asList(CustomMark.class), + true); + kryo.addDefaultSerializer(CustomBean.class, disregardingSerializerFactory); - @Test - public void testExcludeFields() throws Exception { + final byte[] buffer = makeBuffer(); - final Kryo kryo = new Kryo(); - @SuppressWarnings("unchecked") - final SerializerFactory disregardingSerializerFactory = new FieldAnnotationAwareSerializer.Factory( - Arrays.>asList(CustomMark.class), true); - kryo.addDefaultSerializer(CustomBean.class, disregardingSerializerFactory); + final CustomBean outputBean = makeBean(); + final Output output = new Output(buffer); + kryo.writeObject(output, outputBean); - final byte[] buffer = makeBuffer(); + final Input input = new Input(buffer); + final CustomBean inputBean = kryo.readObject(input, CustomBean.class); - final CustomBean outputBean = makeBean(); - final Output output = new Output(buffer); - kryo.writeObject(output, outputBean); + String decodedBuffer = UTF_8.decode(ByteBuffer.wrap(buffer)).toString(); - final Input input = new Input(buffer); - final CustomBean inputBean = kryo.readObject(input, CustomBean.class); + assertEquals(inputBean.getSecondValue(), outputBean.getSecondValue()); + assertFalse(decodedBuffer.contains(outputBean.getFirstValue())); + assertTrue(decodedBuffer.contains(outputBean.getSecondValue())); + assertNull(inputBean.getFirstValue()); + } - assertEquals(inputBean.getSecondValue(), outputBean.getSecondValue()); - assertFalse(new String(buffer).contains(outputBean.getFirstValue())); - assertTrue(new String(buffer).contains(outputBean.getSecondValue())); - assertNull(inputBean.getFirstValue()); - } + @Test + public void testIncludeFields() throws Exception { - @Test - public void testIncludeFields() throws Exception { + final Kryo kryo = new Kryo(); + @SuppressWarnings("unchecked") + final SerializerFactory regardingSerializerFactory = + new FieldAnnotationAwareSerializer.Factory(Arrays.>asList(CustomMark.class), + false); + kryo.addDefaultSerializer(CustomBean.class, regardingSerializerFactory); - final Kryo kryo = new Kryo(); - @SuppressWarnings("unchecked") - final SerializerFactory regardingSerializerFactory = new FieldAnnotationAwareSerializer.Factory( - Arrays.>asList(CustomMark.class), false); - kryo.addDefaultSerializer(CustomBean.class, regardingSerializerFactory); + final byte[] buffer = makeBuffer(); - final byte[] buffer = makeBuffer(); + final CustomBean outputBean = makeBean(); + final Output output = new Output(buffer); + kryo.writeObject(output, outputBean); - final CustomBean outputBean = makeBean(); - final Output output = new Output(buffer); - kryo.writeObject(output, outputBean); + final Input input = new Input(buffer); + final CustomBean inputBean = kryo.readObject(input, CustomBean.class); - final Input input = new Input(buffer); - final CustomBean inputBean = kryo.readObject(input, CustomBean.class); + String decodedBuffer = UTF_8.decode(ByteBuffer.wrap(buffer)).toString(); - assertEquals(inputBean.getFirstValue(), outputBean.getFirstValue()); - assertTrue(new String(buffer).contains(outputBean.getFirstValue())); - assertFalse(new String(buffer).contains(outputBean.getSecondValue())); - assertNull(inputBean.getSecondValue()); - } + assertEquals(inputBean.getFirstValue(), outputBean.getFirstValue()); + assertTrue(decodedBuffer.contains(outputBean.getFirstValue())); + assertFalse(decodedBuffer.contains(outputBean.getSecondValue())); + assertNull(inputBean.getSecondValue()); + } - private static class CustomBean { + @Target(ElementType.FIELD) + @Retention(RetentionPolicy.RUNTIME) + private static @interface CustomMark { + } - @CustomMark - private String firstValue; + private static class CustomBean { - private String secondValue; + @CustomMark + private String firstValue; - public String getSecondValue() { - return secondValue; - } + private String secondValue; - public void setSecondValue(final String secondValue) { - this.secondValue = secondValue; - } + public String getSecondValue() { + return secondValue; + } - public String getFirstValue() { - return firstValue; - } + public void setSecondValue(final String secondValue) { + this.secondValue = secondValue; + } - public void setFirstValue(final String firstValue) { - this.firstValue = firstValue; - } - } + public String getFirstValue() { + return firstValue; + } - @Target(ElementType.FIELD) - @Retention(RetentionPolicy.RUNTIME) - private static @interface CustomMark { - } + public void setFirstValue(final String firstValue) { + this.firstValue = firstValue; + } + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/KryoTest.java b/src/test/java/de/javakaffee/kryoserializers/KryoTest.java index d6bff54d..855e4d67 100644 --- a/src/test/java/de/javakaffee/kryoserializers/KryoTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/KryoTest.java @@ -16,7 +16,7 @@ */ package de.javakaffee.kryoserializers; -import static de.javakaffee.kryoserializers.TestClasses.createPerson; +import static de.javakaffee.kryoserializers.TestClasses.*; import static org.testng.Assert.assertEquals; import java.lang.reflect.Field; @@ -26,32 +26,12 @@ import java.math.BigInteger; import java.net.URI; import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.BitSet; -import java.util.Calendar; -import java.util.Collection; -import java.util.Collections; -import java.util.Currency; -import java.util.Date; -import java.util.EnumMap; -import java.util.EnumSet; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.HashSet; -import java.util.IdentityHashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.UUID; +import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Pattern; -import org.apache.commons.lang.mutable.MutableInt; +import org.apache.commons.lang3.mutable.MutableInt; import org.testng.Assert; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; @@ -63,20 +43,10 @@ import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.serializers.DefaultSerializers.BigDecimalSerializer; import com.esotericsoftware.kryo.serializers.DefaultSerializers.BigIntegerSerializer; +import com.google.common.base.Charsets; -import de.javakaffee.kryoserializers.TestClasses.ClassWithoutDefaultConstructor; -import de.javakaffee.kryoserializers.TestClasses.Container; -import de.javakaffee.kryoserializers.TestClasses.CounterHolder; -import de.javakaffee.kryoserializers.TestClasses.CounterHolderArray; -import de.javakaffee.kryoserializers.TestClasses.Email; -import de.javakaffee.kryoserializers.TestClasses.HashMapWithIntConstructorOnly; -import de.javakaffee.kryoserializers.TestClasses.Holder; -import de.javakaffee.kryoserializers.TestClasses.HolderArray; -import de.javakaffee.kryoserializers.TestClasses.HolderList; -import de.javakaffee.kryoserializers.TestClasses.MyContainer; -import de.javakaffee.kryoserializers.TestClasses.Person; +import de.javakaffee.kryoserializers.TestClasses.*; import de.javakaffee.kryoserializers.TestClasses.Person.Gender; -import de.javakaffee.kryoserializers.TestClasses.SomeInterface; /** * Test for {@link Kryo} serialization. @@ -84,809 +54,780 @@ * @author Martin Grotzke */ public class KryoTest { - - private Kryo _kryo; - - @BeforeTest - protected void beforeTest() { - _kryo = new KryoReflectionFactorySupport() { - - @Override - @SuppressWarnings( { "rawtypes", "unchecked" } ) - public Serializer getDefaultSerializer( final Class type ) { - if ( EnumSet.class.isAssignableFrom( type ) ) { - return new EnumSetSerializer(); - } - if ( EnumMap.class.isAssignableFrom( type ) ) { - return new EnumMapSerializer(); - } - if ( Collection.class.isAssignableFrom( type ) ) { - return new CopyForIterateCollectionSerializer(); - } - if ( Map.class.isAssignableFrom( type ) ) { - return new CopyForIterateMapSerializer(); - } - if ( Date.class.isAssignableFrom( type ) ) { - return new DateSerializer( type ); - } - return super.getDefaultSerializer( type ); - } - }; - _kryo.setRegistrationRequired(false); - _kryo.register( Arrays.asList( "" ).getClass(), new ArraysAsListSerializer() ); - _kryo.register( Collections.EMPTY_LIST.getClass(), new CollectionsEmptyListSerializer() ); - _kryo.register( Collections.EMPTY_MAP.getClass(), new CollectionsEmptyMapSerializer() ); - _kryo.register( Collections.EMPTY_SET.getClass(), new CollectionsEmptySetSerializer() ); - _kryo.register( Collections.singletonList( "" ).getClass(), new CollectionsSingletonListSerializer() ); - _kryo.register( Collections.singleton( "" ).getClass(), new CollectionsSingletonSetSerializer() ); - _kryo.register( Collections.singletonMap( "", "" ).getClass(), new CollectionsSingletonMapSerializer() ); - _kryo.register( BigDecimal.class, new BigDecimalSerializer() ); - _kryo.register( BigInteger.class, new BigIntegerSerializer() ); - _kryo.register( Pattern.class, new RegexSerializer() ); - _kryo.register( BitSet.class, new BitSetSerializer() ); - _kryo.register( URI.class, new URISerializer() ); - _kryo.register( UUID.class, new UUIDSerializer() ); - _kryo.register( GregorianCalendar.class, new GregorianCalendarSerializer() ); - _kryo.register( InvocationHandler.class, new JdkProxySerializer() ); - UnmodifiableCollectionsSerializer.registerSerializers( _kryo ); - SynchronizedCollectionsSerializer.registerSerializers( _kryo ); - } - - @Test( enabled = true ) - public void testSingletonList() throws Exception { - final List obj = Collections.singletonList( "foo" ); - final List deserialized = deserialize( serialize( obj ), obj.getClass() ); - assertDeepEquals( deserialized, obj ); - } - - @Test( enabled = true ) - public void testCopySingletonList() throws Exception { - final List obj = Collections.singletonList( "foo" ); - final List copy = _kryo.copy( obj ); - assertDeepEquals( copy, obj ); - } - - @Test( enabled = true ) - public void testSingletonSet() throws Exception { - final Set obj = Collections.singleton( "foo" ); - final Set deserialized = deserialize( serialize( obj ), obj.getClass() ); - assertDeepEquals( deserialized, obj ); - } - - @Test( enabled = true ) - public void testCopySingletonSet() throws Exception { - final Set obj = Collections.singleton( "foo" ); - final Set copy = _kryo.copy( obj ); - assertDeepEquals( copy, obj ); - } - - @Test( enabled = true ) - public void testSingletonMap() throws Exception { - final Map obj = Collections.singletonMap( "foo", "bar" ); - final Map deserialized = deserialize( serialize( obj ), obj.getClass() ); - assertDeepEquals( deserialized, obj ); - } - - @Test( enabled = true ) - public void testCopySingletonMap() throws Exception { - final Map obj = Collections.singletonMap( "foo", "bar" ); - final Map copy = _kryo.copy( obj ); - assertDeepEquals( copy, obj ); - } - - @Test( enabled = true ) - public void testEnumSet() throws Exception { - final EnumSet set = EnumSet.allOf( Gender.class ); - final EnumSet deserialized = deserialize( serialize( set ), set.getClass() ); - assertDeepEquals( deserialized, set ); - } - - @Test - public void testCopyEnumSet() throws Exception { - final EnumSet set = EnumSet.allOf( Gender.class ); - final EnumSet copy = _kryo.copy(set); - assertDeepEquals( copy, set ); - } - - @Test( enabled = true ) - public void testEnumMap() throws Exception { - final EnumMap map = new EnumMap( Gender.class ); - final String value = "foo"; - map.put( Gender.FEMALE, value ); - // Another entry with the same value - to check reference handling - map.put( Gender.MALE, value ); - @SuppressWarnings( "unchecked" ) - final EnumMap deserialized = deserialize( serialize( map ), map.getClass() ); - assertDeepEquals( deserialized, map ); - } - - @Test - public void testCopyEnumMap() throws Exception { - final EnumMap map = new EnumMap( Gender.class ); - final String value = "foo"; - map.put( Gender.FEMALE, value ); - final EnumMap copy = _kryo.copy(map); - assertDeepEquals( copy, map ); - } - - /** - * Test that linked hash map is serialized correctly with the {@link CopyForIterateMapSerializer}: - * test that insertion order is retained. - * @throws Exception - */ - @Test( enabled = true ) - public void testCopyForIterateMapSerializer() throws Exception { - final Map map = new LinkedHashMap(); - // use doubles as e.g. integers hash to the value... - for( int i = 0; i < 10; i++ ) { - map.put( Double.valueOf( String.valueOf( i ) + "." + Math.abs( i ) ), "value: " + i ); - } - @SuppressWarnings( "unchecked" ) - final Map deserialized = deserialize( serialize( map ), map.getClass() ); - assertDeepEquals( deserialized, map ); - } - - @Test( enabled = true ) - public void testGregorianCalendar() throws Exception { - final Holder cal = new Holder( Calendar.getInstance( Locale.ENGLISH ) ); - @SuppressWarnings( "unchecked" ) - final Holder deserialized = deserialize( serialize( cal ), Holder.class ); - assertDeepEquals( deserialized, cal ); - - assertEquals( deserialized.item.getTimeInMillis(), cal.item.getTimeInMillis() ); - assertEquals( deserialized.item.getTimeZone(), cal.item.getTimeZone() ); - assertEquals( deserialized.item.getMinimalDaysInFirstWeek(), cal.item.getMinimalDaysInFirstWeek() ); - assertEquals( deserialized.item.getFirstDayOfWeek(), cal.item.getFirstDayOfWeek() ); - assertEquals( deserialized.item.isLenient(), cal.item.isLenient() ); - } - - @Test( enabled = true ) - public void testCopyGregorianCalendar() throws Exception { - final Holder cal = new Holder( Calendar.getInstance( Locale.ENGLISH ) ); - final Holder copy = _kryo.copy( cal ); - assertDeepEquals( copy, cal ); - - assertEquals( copy.item.getTimeInMillis(), cal.item.getTimeInMillis() ); - assertEquals( copy.item.getTimeZone(), cal.item.getTimeZone() ); - assertEquals( copy.item.getMinimalDaysInFirstWeek(), cal.item.getMinimalDaysInFirstWeek() ); - assertEquals( copy.item.getFirstDayOfWeek(), cal.item.getFirstDayOfWeek() ); - assertEquals( copy.item.isLenient(), cal.item.isLenient() ); - } - - @Test( enabled = true ) - public void testJavaUtilDate() throws Exception { - final Holder cal = new Holder( new Date(System.currentTimeMillis()) ); - @SuppressWarnings( "unchecked" ) - final Holder deserialized = deserialize( serialize( cal ), Holder.class ); - assertDeepEquals( deserialized, cal ); - assertEquals(deserialized.item.getTime(), cal.item.getTime()); - } - - @Test( enabled = true ) - public void testCopyJavaUtilDate() throws Exception { - final Holder cal = new Holder( new Date(System.currentTimeMillis()) ); - final Holder copy = _kryo.copy( cal ); - assertDeepEquals( copy, cal ); - assertEquals(copy.item.getTime(), cal.item.getTime()); - } - - @Test( enabled = true ) - public void testJavaSqlTimestamp() throws Exception { - final Holder cal = new Holder( new Timestamp(System.currentTimeMillis()) ); - @SuppressWarnings( "unchecked" ) - final Holder deserialized = deserialize( serialize( cal ), Holder.class ); - assertDeepEquals( deserialized, cal ); - assertEquals( deserialized.item.getTime(), cal.item.getTime() ); - } - - @Test( enabled = true ) - public void testCopyJavaSqlTimestamp() throws Exception { - final Holder cal = new Holder( new Timestamp(System.currentTimeMillis()) ); - final Holder copy = _kryo.copy( cal ); - assertDeepEquals( copy, cal ); - assertEquals( copy.item.getTime(), cal.item.getTime() ); - } - - @Test(enabled = true) - public void testJavaSqlDate() throws Exception { - final Holder date = new Holder(new java.sql.Date(System.currentTimeMillis())); - @SuppressWarnings("unchecked") - final Holder deserialized = deserialize(serialize(date), Holder.class); - assertDeepEquals(deserialized, date); - assertEquals(deserialized.item.getTime(), date.item.getTime()); - } - - @Test(enabled = true) - public void testCopyJavaSqlDate() throws Exception { - final Holder date = new Holder(new java.sql.Date(System.currentTimeMillis())); - final Holder copy = _kryo.copy(date); - assertDeepEquals(copy, date); - assertEquals(copy.item.getTime(), date.item.getTime()); - } - - @Test(enabled = true) - public void testJavaSqlTime() throws Exception { - final Holder time = new Holder(new java.sql.Time(System.currentTimeMillis())); - @SuppressWarnings("unchecked") - final Holder deserialized = deserialize(serialize(time), Holder.class); - assertDeepEquals(deserialized, time); - assertEquals(deserialized.item.getTime(), time.item.getTime()); - } - - @Test(enabled = true) - public void testCopyJavaSqlTime() throws Exception { - final Holder time = new Holder(new java.sql.Time(System.currentTimeMillis())); - final Holder copy = _kryo.copy(time); - assertDeepEquals(copy, time); - assertEquals(copy.item.getTime(), time.item.getTime()); - } - - @Test(enabled = true) - public void testBitSet() throws Exception { - final BitSet bitSet = new BitSet(10); - bitSet.flip(2); - bitSet.flip(4); - final Holder holder = new Holder(bitSet); - @SuppressWarnings("unchecked") - final Holder deserialized = deserialize(serialize(holder), Holder.class); - assertDeepEquals(deserialized, holder); - } - - @Test(enabled = true) - public void testCopyBitSet() throws Exception { - final BitSet bitSet = new BitSet(10); - bitSet.flip(2); - bitSet.flip(4); - final BitSet copy = _kryo.copy(bitSet); - assertDeepEquals(copy, bitSet); - } - - @Test( enabled = true ) - public void testURI() throws Exception { - final Holder uri = new Holder( new URI("http://www.google.com") ); - @SuppressWarnings( "unchecked" ) - final Holder deserialized = deserialize( serialize( uri ), Holder.class ); - assertDeepEquals(deserialized, uri); - } - - @Test( enabled = true ) - public void testCopyURI() throws Exception { - final Holder uri = new Holder( new URI("http://www.google.com") ); - final Holder copy = _kryo.copy( uri ); - assertDeepEquals(copy, uri); - } - - @Test( enabled = true ) - public void testUUID() throws Exception { - final Holder uuid = new Holder( UUID.randomUUID() ); - @SuppressWarnings( "unchecked" ) - final Holder deserialized = deserialize( serialize( uuid ), Holder.class ); - assertDeepEquals( deserialized, uuid ); - } - - @Test( enabled = true ) - public void testCopyUUID() throws Exception { - final Holder uuid = new Holder( UUID.randomUUID() ); - final Holder copy = _kryo.copy( uuid ); - assertDeepEquals( copy, uuid ); - } - - @Test( enabled = true ) - public void testRegex() throws Exception { - final Holder pattern = new Holder( Pattern.compile("regex") ); - @SuppressWarnings( "unchecked" ) - final Holder deserialized = deserialize( serialize( pattern ), Holder.class ); - assertDeepEquals( deserialized, pattern ); - - final Holder patternWithFlags = new Holder( Pattern.compile("\n", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE) ); - @SuppressWarnings( "unchecked" ) - final Holder deserializedWithFlags = deserialize( serialize( patternWithFlags ), Holder.class ); - assertDeepEquals( deserializedWithFlags, patternWithFlags ); - } - - @Test( enabled = true ) - public void testCopyRegex() throws Exception { - final Holder pattern = new Holder( Pattern.compile("regex") ); - final Holder copy = _kryo.copy( pattern ); - assertDeepEquals( copy, pattern ); - - final Holder patternWithFlags = new Holder( Pattern.compile("\n", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE) ); - final Holder copyWithFlags = _kryo.copy( patternWithFlags ); - assertDeepEquals( copyWithFlags, patternWithFlags ); - } - - @Test( enabled = true ) - public void testStringBuffer() throws Exception { - final StringBuffer stringBuffer = new StringBuffer( "with some content \n& some lines..." ); - final StringBuffer deserialized = deserialize( serialize( stringBuffer ), StringBuffer.class ); - assertDeepEquals( deserialized, stringBuffer ); - } - - @Test( enabled = true ) - public void testStringBuilder() throws Exception { - final StringBuilder stringBuilder = new StringBuilder( "with some content \n& some lines..." ); - final StringBuilder deserialized = deserialize( serialize( stringBuilder ), StringBuilder.class ); - assertDeepEquals( deserialized, stringBuilder ); - } - - @Test( enabled = true ) - public void testMapWithIntConstructorOnly() throws Exception { - final HashMapWithIntConstructorOnly map = new HashMapWithIntConstructorOnly( 5 ); - final HashMapWithIntConstructorOnly deserialized = - deserialize( serialize( map ), HashMapWithIntConstructorOnly.class ); - assertDeepEquals( deserialized, map ); - - } - - @Test( enabled = true ) - public void testCurrency() throws Exception { - final Currency currency = Currency.getInstance( "EUR" ); - final Currency deserialized = - deserialize( serialize( currency ), Currency.class ); - assertDeepEquals( deserialized, currency ); - - // Check that the transient field defaultFractionDigits is initialized correctly - Assert.assertEquals( deserialized.getCurrencyCode(), currency.getCurrencyCode() ); - Assert.assertEquals( deserialized.getDefaultFractionDigits(), currency.getDefaultFractionDigits() ); - } - - @DataProvider - public Object[][] unmodifiableCollections() { - final HashMap m = new HashMap(); - m.put( "foo", "bar" ); - return new Object[][] { - { Collections.unmodifiableList( new ArrayList( Arrays.asList( "foo", "bar" ) ) ) }, - { Collections.unmodifiableSet( new HashSet( Arrays.asList( "foo", "bar" ) ) ) }, - { Collections.unmodifiableMap( m ) }, - }; - } - - @SuppressWarnings( "unchecked" ) - @Test( enabled = true, dataProvider = "unmodifiableCollections" ) - public void testUnmodifiableCollections( final Object collection ) throws Exception { - final Holder holder = new Holder( collection ); - final Holder deserialized = deserialize( serialize( holder ), Holder.class ); - assertDeepEquals( deserialized, holder ); - } - - @Test( enabled = true, dataProvider = "unmodifiableCollections" ) - public void testCopyUnmodifiableCollections( final Object collection ) throws Exception { - final Holder unmodifiableCollection = new Holder( collection ); - final Holder copy = _kryo.copy( unmodifiableCollection ); - assertDeepEquals( copy, unmodifiableCollection ); - } - - @DataProvider - public Object[][] synchronizedCollections() { - final HashMap m = new HashMap(); - m.put( "foo", "bar" ); - return new Object[][] { - { Collections.synchronizedList( new ArrayList( Arrays.asList( "foo", "bar" ) ) ) }, - { Collections.synchronizedSet( new HashSet( Arrays.asList( "foo", "bar" ) ) ) }, - { Collections.synchronizedMap( m ) }, - }; - } - - @SuppressWarnings( "unchecked" ) - @Test( enabled = true, dataProvider = "synchronizedCollections" ) - public void testSynchronizedCollections( final Object collection ) throws Exception { - final Holder holder = new Holder( collection ); - final Holder deserialized = deserialize( serialize( holder ), Holder.class ); - assertDeepEquals( deserialized, holder ); - } - - @Test( enabled = true, dataProvider = "synchronizedCollections" ) - public void testCopySynchronizedCollections( final Object collection ) throws Exception { - final Holder synchronizedCollection = new Holder( collection ); - final Holder copy = _kryo.copy( synchronizedCollection ); - assertDeepEquals( copy, synchronizedCollection ); - } - - @SuppressWarnings( "unchecked" ) - @Test( enabled = true ) - public void testJavaUtilCollectionsEmptyList() throws Exception { - final Holder> emptyList = new Holder>( Collections.emptyList() ); - final Holder> deserialized = deserialize( serialize( emptyList ), Holder.class ); - assertDeepEquals( deserialized, emptyList ); - } - - @Test( enabled = true ) - public void testCopyJavaUtilCollectionsEmptyList() throws Exception { - final Holder> emptyList = new Holder>( Collections.emptyList() ); - final Holder> copy = _kryo.copy( emptyList ); - assertDeepEquals( copy, emptyList ); - } - - @SuppressWarnings( "unchecked" ) - @Test( enabled = true ) - public void testJavaUtilCollectionsEmptySet() throws Exception { - final Holder> emptyList = new Holder>( Collections.emptySet() ); - final Holder> deserialized = deserialize( serialize( emptyList ), Holder.class ); - assertDeepEquals( deserialized, emptyList ); - } - - @Test( enabled = true ) - public void testCopyJavaUtilCollectionsEmptySet() throws Exception { - final Holder> emptyList = new Holder>( Collections.emptySet() ); - final Holder> copy = _kryo.copy( emptyList ); - assertDeepEquals( copy, emptyList ); - } - - @SuppressWarnings( "unchecked" ) - @Test( enabled = true ) - public void testJavaUtilCollectionsEmptyMap() throws Exception { - final Holder> emptyMap = new Holder>( Collections.emptyMap() ); - final Holder> deserialized = deserialize( serialize( emptyMap ), Holder.class ); - assertDeepEquals( deserialized, emptyMap ); - } - - @Test( enabled = true ) - public void testCopyJavaUtilCollectionsEmptyMap() throws Exception { - final Holder> emptyMap = new Holder>( Collections.emptyMap() ); - final Holder> copy = _kryo.copy( emptyMap ); - assertDeepEquals( copy, emptyMap ); - } - - @SuppressWarnings( "unchecked" ) - @Test( enabled = true ) - public void testJavaUtilArraysAsListEmpty() throws Exception { - final Holder> asListHolder = new Holder>( Arrays. asList() ); - final Holder> deserialized = deserialize( serialize( asListHolder ), Holder.class ); - assertDeepEquals( deserialized, asListHolder ); - } - - @SuppressWarnings( "unchecked" ) - @Test( enabled = true ) - public void testJavaUtilArraysAsListPrimitiveArrayElement() throws Exception { - final int[] values = { 1, 2 }; - @SuppressWarnings("rawtypes") - final Holder> asListHolder = new Holder( Arrays.asList( values ) ); - final Holder> deserialized = deserialize( serialize( asListHolder ), Holder.class ); - assertDeepEquals( deserialized, asListHolder ); - } - - @SuppressWarnings( "unchecked" ) - @Test( enabled = true ) - public void testJavaUtilArraysAsListBoxedPrimitives() throws Exception { - final Integer[] values = { 1, 2 }; - final List list = Arrays.asList(values); - @SuppressWarnings("rawtypes") - final Holder> asListHolder = new Holder(list); - final Holder> deserialized = deserialize( serialize( asListHolder ), Holder.class ); - assertDeepEquals( deserialized, asListHolder ); - } - - @SuppressWarnings( "unchecked" ) - @Test( enabled = true ) - public void testJavaUtilArraysAsListString() throws Exception { - final Holder> asListHolder = new Holder>( Arrays. asList( "foo", "bar" ) ); - final Holder> deserialized = deserialize( serialize( asListHolder ), Holder.class ); - assertDeepEquals( deserialized, asListHolder ); - } - - @SuppressWarnings( "unchecked" ) - @Test( enabled = true ) - public void testJavaUtilArraysAsListEmail() throws Exception { - final Holder> asListHolder = new Holder>( Arrays.asList( new Email( "foo", "foo@example.org" ) ) ); - final Holder> deserialized = deserialize( serialize( asListHolder ), Holder.class ); - assertDeepEquals( deserialized, asListHolder ); - } - - @Test( enabled = true ) - public void testCopyJavaUtilArraysAsList() throws Exception { - final List list = Arrays. asList("foo", "bar"); - final List copy = _kryo.copy(list); - assertDeepEquals( copy, list ); - } - - @Test( enabled = true ) - public void testJdkProxy() throws Exception { - final Holder bean = new Holder( TestClasses.createProxy() ); - @SuppressWarnings( "unchecked" ) - final Holder deserialized = deserialize( serialize( bean ), Holder.class ); - assertDeepEquals( deserialized, bean ); - } - - @Test( enabled = true ) - public void testCopyJdkProxy() throws Exception { - final Holder bean = new Holder( TestClasses.createProxy() ); - final Holder copy = _kryo.copy( bean ); - assertDeepEquals( copy, bean ); - } - - @Test( enabled = true ) - public void testClassSerializer() throws Exception { - final Holder> clazz = new Holder>( String.class ); - @SuppressWarnings( "unchecked" ) - final Holder> deserialized = deserialize( serialize( clazz ), Holder.class ); - assertDeepEquals( deserialized, clazz ); - } - - @Test( enabled = true ) - public void testInnerClass() throws Exception { - // seems to be related to #15 - final Container container = TestClasses.createContainer(); - final Container deserialized = deserialize( serialize( container ), Container.class ); - assertDeepEquals( deserialized, container ); - } - - @Test( enabled = true ) - public void testSharedObjectIdentity_CounterHolder() throws Exception { - - final AtomicInteger sharedObject = new AtomicInteger( 42 ); - final CounterHolder holder1 = new CounterHolder( sharedObject ); - final CounterHolder holder2 = new CounterHolder( sharedObject ); - final CounterHolderArray holderHolder = new CounterHolderArray( holder1, holder2 ); - - final CounterHolderArray deserialized = deserialize( serialize( holderHolder ), CounterHolderArray.class ); - assertDeepEquals( deserialized, holderHolder ); - Assert.assertTrue( deserialized.holders[0].item == deserialized.holders[1].item ); - - } - - @DataProvider( name = "sharedObjectIdentityProvider" ) - protected Object[][] createSharedObjectIdentityProviderData() { - return new Object[][] { - { AtomicInteger.class.getSimpleName(), new AtomicInteger( 42 ) }, - { Email.class.getSimpleName(), new Email( "foo bar", "foo.bar@example.com" ) } }; - } - - @SuppressWarnings( "unchecked" ) - @Test( enabled = true, dataProvider = "sharedObjectIdentityProvider" ) - public void testSharedObjectIdentityWithArray( final String name, final T sharedObject ) throws Exception { - final Holder holder1 = new Holder( sharedObject ); - final Holder holder2 = new Holder( sharedObject ); - final HolderArray holderHolder = new HolderArray( holder1, holder2 ); - - final HolderArray deserialized = deserialize( serialize( holderHolder ), HolderArray.class ); - assertDeepEquals( deserialized, holderHolder ); - Assert.assertTrue( deserialized.holders[0].item == deserialized.holders[1].item ); - } - - @SuppressWarnings( "unchecked" ) - @Test( enabled = true, dataProvider = "sharedObjectIdentityProvider" ) - public void testSharedObjectIdentity( final String name, final T sharedObject ) throws Exception { - final Holder holder1 = new Holder( sharedObject ); - final Holder holder2 = new Holder( sharedObject ); - final HolderList holderHolder = new HolderList( new ArrayList>( Arrays.asList( holder1, holder2 ) ) ); - - final HolderList deserialized = deserialize( serialize( holderHolder ), HolderList.class ); - assertDeepEquals( deserialized, holderHolder ); - Assert.assertTrue( deserialized.holders.get( 0 ).item == deserialized.holders.get( 1 ).item ); - } - - @DataProvider( name = "typesAsSessionAttributesProvider" ) - protected Object[][] createTypesAsSessionAttributesData() { - return new Object[][] { - { Boolean.class, Boolean.TRUE }, - { String.class, "42" }, - { StringBuilder.class, new StringBuilder( "42" ) }, - { StringBuffer.class, new StringBuffer( "42" ) }, - { Class.class, String.class }, - { Long.class, new Long( 42 ) }, - { Integer.class, new Integer( 42 ) }, - { Character.class, new Character( 'c' ) }, - { Byte.class, new Byte( "b".getBytes()[0] ) }, - { Double.class, new Double( 42d ) }, - { Float.class, new Float( 42f ) }, - { Short.class, new Short( (short) 42 ) }, - { BigDecimal.class, new BigDecimal( 42 ) }, - { AtomicInteger.class, new AtomicInteger( 42 ) }, - { AtomicLong.class, new AtomicLong( 42 ) }, - { MutableInt.class, new MutableInt( 42 ) }, - { Integer[].class, new Integer[] { 42 } }, - { Date.class, new Date( System.currentTimeMillis() - 10000 ) }, - { Calendar.class, Calendar.getInstance() }, - { Currency.class, Currency.getInstance( "EUR" ) }, - { ArrayList.class, new ArrayList( Arrays.asList( "foo" ) ) }, - { int[].class, new int[] { 1, 2 } }, - { long[].class, new long[] { 1, 2 } }, - { short[].class, new short[] { 1, 2 } }, - { float[].class, new float[] { 1, 2 } }, - { double[].class, new double[] { 1, 2 } }, - { int[].class, new int[] { 1, 2 } }, - { byte[].class, "42".getBytes() }, - { char[].class, "42".toCharArray() }, - { String[].class, new String[] { "23", "42" } }, - { Person[].class, new Person[] { createPerson( "foo bar", Gender.MALE, 42 ) } } }; - } - - @Test( enabled = true, dataProvider = "typesAsSessionAttributesProvider" ) - public void testTypesAsSessionAttributes( final Class type, final T instance ) throws Exception { - @SuppressWarnings( "unchecked" ) - final T deserialized = (T) deserialize( serialize( instance ), instance.getClass() ); - assertDeepEquals( deserialized, instance ); - } - - @Test( enabled = true ) - public void testTypesInContainerClass() throws Exception { - final MyContainer myContainer = new MyContainer(); - final MyContainer deserialized = deserialize( serialize( myContainer ), MyContainer.class ); - assertDeepEquals( deserialized, myContainer ); - } - - @Test( enabled = true ) - public void testClassWithoutDefaultConstructor() throws Exception { - final ClassWithoutDefaultConstructor obj = TestClasses.createClassWithoutDefaultConstructor( "foo" ); - final ClassWithoutDefaultConstructor deserialized = deserialize( serialize( obj ), ClassWithoutDefaultConstructor.class ); - assertDeepEquals( deserialized, obj ); - } - - @Test( enabled = true ) - public void testPrivateClass() throws Exception { - final Holder holder = new Holder( TestClasses.createPrivateClass( "foo" ) ); - final Holder deserialized = deserialize( serialize( holder ), Holder.class ); - assertDeepEquals( deserialized, holder ); - } - - @Test( enabled = true ) - public void testCollections() throws Exception { - final EntityWithCollections obj = new EntityWithCollections(); - final EntityWithCollections deserialized = deserialize( serialize( obj ), EntityWithCollections.class ); - assertDeepEquals( deserialized, obj ); - } - - @Test( enabled = true ) - public void testCyclicDependencies() throws Exception { - final Person p1 = createPerson( "foo bar", Gender.MALE, 42, "foo.bar@example.org", "foo.bar@example.com" ); - final Person p2 = createPerson( "bar baz", Gender.FEMALE, 42, "bar.baz@example.org", "bar.baz@example.com" ); - p1.addFriend( p2 ); - p2.addFriend( p1 ); - - final Person deserialized = deserialize( serialize( p1 ), Person.class ); - assertDeepEquals( deserialized, p1 ); - } - - public static class EntityWithCollections { - private final String[] _bars; - private final List _foos; - private final Map _bazens; - - public EntityWithCollections() { - _bars = new String[] { "foo", "bar" }; - _foos = new ArrayList( Arrays.asList( "foo", "bar" ) ); - _bazens = new HashMap(); - _bazens.put( "foo", 1 ); - _bazens.put( "bar", 2 ); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + Arrays.hashCode( _bars ); - result = prime * result + ( ( _bazens == null ) - ? 0 - : _bazens.hashCode() ); - result = prime * result + ( ( _foos == null ) - ? 0 - : _foos.hashCode() ); - return result; - } - - @Override - public boolean equals( final Object obj ) { - if ( this == obj ) { - return true; - } - if ( obj == null ) { - return false; - } - if ( getClass() != obj.getClass() ) { - return false; - } - final EntityWithCollections other = (EntityWithCollections) obj; - if ( !Arrays.equals( _bars, other._bars ) ) { - return false; - } - if ( _bazens == null ) { - if ( other._bazens != null ) { - return false; - } - } else if ( !_bazens.equals( other._bazens ) ) { - return false; - } - if ( _foos == null ) { - if ( other._foos != null ) { - return false; - } - } else if ( !_foos.equals( other._foos ) ) { - return false; - } - return true; - } - } - - public static void assertDeepEquals( final Object one, final Object another ) throws Exception { - assertDeepEquals( one, another, new IdentityHashMap() ); - } - - private static void assertDeepEquals( final Object one, final Object another, final Map alreadyChecked ) - throws Exception { - if ( one == another ) { - return; - } - if ( one == null && another != null || one != null && another == null ) { - Assert.fail( "One of both is null: " + one + ", " + another ); - } - if ( alreadyChecked.containsKey( one ) ) { - return; - } - alreadyChecked.put( one, another ); - - Assert.assertEquals( one.getClass(), another.getClass() ); - if ( one.getClass().isPrimitive() || one instanceof String || one instanceof Character || one instanceof Boolean - || one instanceof Class ) { - Assert.assertEquals( one, another ); - return; - } - - if ( Map.class.isAssignableFrom( one.getClass() ) ) { - final Map m1 = (Map) one; - final Map m2 = (Map) another; - Assert.assertEquals( m1.size(), m2.size() ); - final Iterator> iter1 = m1.entrySet().iterator(); - final Iterator> iter2 = m2.entrySet().iterator(); - while( iter1.hasNext() ) { - Assert.assertTrue( iter2.hasNext() ); - assertDeepEquals( iter1.next(), iter2.next(), alreadyChecked ); - } - return; - } - - if ( Number.class.isAssignableFrom( one.getClass() ) ) { - Assert.assertEquals( ( (Number) one ).longValue(), ( (Number) another ).longValue() ); - return; - } - - if ( one instanceof Currency ) { - // Check that the transient field defaultFractionDigits is initialized correctly (that was issue #34) - final Currency currency1 = ( Currency) one; - final Currency currency2 = ( Currency) another; - Assert.assertEquals( currency1.getCurrencyCode(), currency2.getCurrencyCode() ); - Assert.assertEquals( currency1.getDefaultFractionDigits(), currency2.getDefaultFractionDigits() ); - } - - Class clazz = one.getClass(); - while ( clazz != null ) { - assertEqualDeclaredFields( clazz, one, another, alreadyChecked ); - clazz = clazz.getSuperclass(); - } - - } - - private static void assertEqualDeclaredFields( final Class clazz, final Object one, final Object another, - final Map alreadyChecked ) throws Exception, IllegalAccessException { - for ( final Field field : clazz.getDeclaredFields() ) { - field.setAccessible( true ); - if ( !Modifier.isTransient( field.getModifiers() ) ) { - assertDeepEquals( field.get( one ), field.get( another ), alreadyChecked ); - } - } - } - - protected byte[] serialize( final Object o ) { - return serialize(_kryo, o); - } - - public static byte[] serialize(final Kryo kryo, final Object o) { - if ( o == null ) { - throw new NullPointerException( "Can't serialize null" ); - } - - final Output output = new Output(4096); - kryo.writeObject(output, o); - output.flush(); - return output.getBuffer(); - } - - protected T deserialize( final byte[] in, final Class clazz ) { - return deserialize(_kryo, in, clazz); - } - - public static T deserialize(final Kryo kryo, final byte[] in, final Class clazz) { - final Input input = new Input(in); - return kryo.readObject(input, clazz); - } + + private Kryo _kryo; + + public static void assertDeepEquals(final Object one, final Object another) throws Exception { + assertDeepEquals(one, another, new IdentityHashMap<>()); + } + + private static void assertDeepEquals(final Object one, final Object another, + final Map alreadyChecked) throws Exception { + if (one == another) { + return; + } + if (one == null && another != null || one != null && another == null) { + Assert.fail("One of both is null: " + one + ", " + another); + } + if (alreadyChecked.containsKey(one)) { + return; + } + alreadyChecked.put(one, another); + + Assert.assertEquals(one.getClass(), another.getClass()); + if (one.getClass().isPrimitive() || one instanceof String || one instanceof Character || one instanceof Boolean + || one instanceof Class) { + Assert.assertEquals(one, another); + return; + } + + if (Map.class.isAssignableFrom(one.getClass())) { + final Map m1 = (Map) one; + final Map m2 = (Map) another; + Assert.assertEquals(m1.size(), m2.size()); + final Iterator> iter1 = m1.entrySet().iterator(); + final Iterator> iter2 = m2.entrySet().iterator(); + while (iter1.hasNext()) { + Assert.assertTrue(iter2.hasNext()); + assertDeepEquals(iter1.next(), iter2.next(), alreadyChecked); + } + return; + } + + if (Number.class.isAssignableFrom(one.getClass())) { + Assert.assertEquals(((Number) one).longValue(), ((Number) another).longValue()); + return; + } + + if (one instanceof Currency) { + // Check that the transient field defaultFractionDigits is initialized correctly (that was issue #34) + final Currency currency1 = (Currency) one; + final Currency currency2 = (Currency) another; + Assert.assertEquals(currency1.getCurrencyCode(), currency2.getCurrencyCode()); + Assert.assertEquals(currency1.getDefaultFractionDigits(), currency2.getDefaultFractionDigits()); + } + + Class clazz = one.getClass(); + while (clazz != null) { + assertEqualDeclaredFields(clazz, one, another, alreadyChecked); + clazz = clazz.getSuperclass(); + } + + } + + private static void assertEqualDeclaredFields(final Class clazz, final Object one, final Object another, + final Map alreadyChecked) throws Exception { + for (final Field field : clazz.getDeclaredFields()) { + field.setAccessible(true); + if (!Modifier.isTransient(field.getModifiers())) { + assertDeepEquals(field.get(one), field.get(another), alreadyChecked); + } + } + } + + public static byte[] serialize(final Kryo kryo, final Object o) { + if (o == null) { + throw new NullPointerException("Can't serialize null"); + } + + final Output output = new Output(4096); + kryo.writeObject(output, o); + output.flush(); + return output.getBuffer(); + } + + public static T deserialize(final Kryo kryo, final byte[] in, final Class clazz) { + final Input input = new Input(in); + return kryo.readObject(input, clazz); + } + + @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") + @BeforeTest + protected void beforeTest() { + _kryo = new KryoReflectionFactorySupport() { + + @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) + public Serializer getDefaultSerializer(final Class type) { + if (EnumSet.class.isAssignableFrom(type)) { + return new EnumSetSerializer(); + } + if (EnumMap.class.isAssignableFrom(type)) { + return new EnumMapSerializer(); + } + if (Collection.class.isAssignableFrom(type)) { + return new CopyForIterateCollectionSerializer(); + } + if (Map.class.isAssignableFrom(type)) { + return new CopyForIterateMapSerializer(); + } + if (Date.class.isAssignableFrom(type)) { + return new DateSerializer(type); + } + return super.getDefaultSerializer(type); + } + }; + _kryo.setRegistrationRequired(false); + _kryo.register(Arrays.asList("").getClass(), new ArraysAsListSerializer()); + _kryo.register(Collections.EMPTY_LIST.getClass(), new CollectionsEmptyListSerializer()); + _kryo.register(Collections.EMPTY_MAP.getClass(), new CollectionsEmptyMapSerializer()); + _kryo.register(Collections.EMPTY_SET.getClass(), new CollectionsEmptySetSerializer()); + _kryo.register(Collections.singletonList("").getClass(), new CollectionsSingletonListSerializer()); + _kryo.register(Collections.singleton("").getClass(), new CollectionsSingletonSetSerializer()); + _kryo.register(Collections.singletonMap("", "").getClass(), new CollectionsSingletonMapSerializer()); + _kryo.register(BigDecimal.class, new BigDecimalSerializer()); + _kryo.register(BigInteger.class, new BigIntegerSerializer()); + _kryo.register(Pattern.class, new RegexSerializer()); + _kryo.register(BitSet.class, new BitSetSerializer()); + _kryo.register(URI.class, new URISerializer()); + _kryo.register(UUID.class, new UUIDSerializer()); + _kryo.register(GregorianCalendar.class, new GregorianCalendarSerializer()); + _kryo.register(InvocationHandler.class, new JdkProxySerializer()); + UnmodifiableCollectionsSerializer.registerSerializers(_kryo); + SynchronizedCollectionsSerializer.registerSerializers(_kryo); + } + + @Test() + public void testSingletonList() throws Exception { + final List obj = Collections.singletonList("foo"); + final List deserialized = deserialize(serialize(obj), obj.getClass()); + assertDeepEquals(deserialized, obj); + } + + @Test() + public void testCopySingletonList() throws Exception { + final List obj = Collections.singletonList("foo"); + final List copy = _kryo.copy(obj); + assertDeepEquals(copy, obj); + } + + @Test() + public void testSingletonSet() throws Exception { + final Set obj = Collections.singleton("foo"); + final Set deserialized = deserialize(serialize(obj), obj.getClass()); + assertDeepEquals(deserialized, obj); + } + + @Test() + public void testCopySingletonSet() throws Exception { + final Set obj = Collections.singleton("foo"); + final Set copy = _kryo.copy(obj); + assertDeepEquals(copy, obj); + } + + @Test() + public void testSingletonMap() throws Exception { + final Map obj = Collections.singletonMap("foo", "bar"); + final Map deserialized = deserialize(serialize(obj), obj.getClass()); + assertDeepEquals(deserialized, obj); + } + + @Test() + public void testCopySingletonMap() throws Exception { + final Map obj = Collections.singletonMap("foo", "bar"); + final Map copy = _kryo.copy(obj); + assertDeepEquals(copy, obj); + } + + @Test() + public void testEnumSet() throws Exception { + final EnumSet set = EnumSet.allOf(Gender.class); + final EnumSet deserialized = deserialize(serialize(set), set.getClass()); + assertDeepEquals(deserialized, set); + } + + @Test + public void testCopyEnumSet() throws Exception { + final EnumSet set = EnumSet.allOf(Gender.class); + final EnumSet copy = _kryo.copy(set); + assertDeepEquals(copy, set); + } + + @Test() + public void testEnumMap() throws Exception { + final EnumMap map = new EnumMap<>(Gender.class); + final String value = "foo"; + map.put(Gender.FEMALE, value); + // Another entry with the same value - to check reference handling + map.put(Gender.MALE, value); + @SuppressWarnings("unchecked") + final EnumMap deserialized = deserialize(serialize(map), map.getClass()); + assertDeepEquals(deserialized, map); + } + + @Test + public void testCopyEnumMap() throws Exception { + final EnumMap map = new EnumMap<>(Gender.class); + final String value = "foo"; + map.put(Gender.FEMALE, value); + final EnumMap copy = _kryo.copy(map); + assertDeepEquals(copy, map); + } + + /** + * Test that linked hash map is serialized correctly with the {@link CopyForIterateMapSerializer}: + * test that insertion order is retained. + */ + @Test() + public void testCopyForIterateMapSerializer() throws Exception { + final Map map = new LinkedHashMap<>(); + // use doubles as e.g. integers hash to the value... + for (int i = 0; i < 10; i++) { + map.put(Double.valueOf(String.valueOf(i) + "." + Math.abs(i)), "value: " + i); + } + @SuppressWarnings("unchecked") + final Map deserialized = deserialize(serialize(map), map.getClass()); + assertDeepEquals(deserialized, map); + } + + @Test() + public void testGregorianCalendar() throws Exception { + final Holder cal = new Holder<>(Calendar.getInstance(Locale.ENGLISH)); + @SuppressWarnings("unchecked") + final Holder deserialized = deserialize(serialize(cal), Holder.class); + assertDeepEquals(deserialized, cal); + + assertEquals(deserialized.item.getTimeInMillis(), cal.item.getTimeInMillis()); + assertEquals(deserialized.item.getTimeZone(), cal.item.getTimeZone()); + assertEquals(deserialized.item.getMinimalDaysInFirstWeek(), cal.item.getMinimalDaysInFirstWeek()); + assertEquals(deserialized.item.getFirstDayOfWeek(), cal.item.getFirstDayOfWeek()); + assertEquals(deserialized.item.isLenient(), cal.item.isLenient()); + } + + @Test() + public void testCopyGregorianCalendar() throws Exception { + final Holder cal = new Holder<>(Calendar.getInstance(Locale.ENGLISH)); + final Holder copy = _kryo.copy(cal); + assertDeepEquals(copy, cal); + + assertEquals(copy.item.getTimeInMillis(), cal.item.getTimeInMillis()); + assertEquals(copy.item.getTimeZone(), cal.item.getTimeZone()); + assertEquals(copy.item.getMinimalDaysInFirstWeek(), cal.item.getMinimalDaysInFirstWeek()); + assertEquals(copy.item.getFirstDayOfWeek(), cal.item.getFirstDayOfWeek()); + assertEquals(copy.item.isLenient(), cal.item.isLenient()); + } + + @Test() + public void testJavaUtilDate() throws Exception { + final Holder cal = new Holder<>(new Date(System.currentTimeMillis())); + @SuppressWarnings("unchecked") + final Holder deserialized = deserialize(serialize(cal), Holder.class); + assertDeepEquals(deserialized, cal); + assertEquals(deserialized.item.getTime(), cal.item.getTime()); + } + + @Test() + public void testCopyJavaUtilDate() throws Exception { + final Holder cal = new Holder<>(new Date(System.currentTimeMillis())); + final Holder copy = _kryo.copy(cal); + assertDeepEquals(copy, cal); + assertEquals(copy.item.getTime(), cal.item.getTime()); + } + + @Test() + public void testJavaSqlTimestamp() throws Exception { + final Holder cal = new Holder<>(new Timestamp(System.currentTimeMillis())); + @SuppressWarnings("unchecked") + final Holder deserialized = deserialize(serialize(cal), Holder.class); + assertDeepEquals(deserialized, cal); + assertEquals(deserialized.item.getTime(), cal.item.getTime()); + } + + @Test() + public void testCopyJavaSqlTimestamp() throws Exception { + final Holder cal = new Holder<>(new Timestamp(System.currentTimeMillis())); + final Holder copy = _kryo.copy(cal); + assertDeepEquals(copy, cal); + assertEquals(copy.item.getTime(), cal.item.getTime()); + } + + @Test() + public void testJavaSqlDate() throws Exception { + final Holder date = new Holder<>(new java.sql.Date(System.currentTimeMillis())); + @SuppressWarnings("unchecked") + final Holder deserialized = deserialize(serialize(date), Holder.class); + assertDeepEquals(deserialized, date); + assertEquals(deserialized.item.getTime(), date.item.getTime()); + } + + @Test() + public void testCopyJavaSqlDate() throws Exception { + final Holder date = new Holder<>(new java.sql.Date(System.currentTimeMillis())); + final Holder copy = _kryo.copy(date); + assertDeepEquals(copy, date); + assertEquals(copy.item.getTime(), date.item.getTime()); + } + + @Test() + public void testJavaSqlTime() throws Exception { + final Holder time = new Holder<>(new java.sql.Time(System.currentTimeMillis())); + @SuppressWarnings("unchecked") + final Holder deserialized = deserialize(serialize(time), Holder.class); + assertDeepEquals(deserialized, time); + assertEquals(deserialized.item.getTime(), time.item.getTime()); + } + + @Test() + public void testCopyJavaSqlTime() throws Exception { + final Holder time = new Holder<>(new java.sql.Time(System.currentTimeMillis())); + final Holder copy = _kryo.copy(time); + assertDeepEquals(copy, time); + assertEquals(copy.item.getTime(), time.item.getTime()); + } + + @Test() + public void testBitSet() throws Exception { + final BitSet bitSet = new BitSet(10); + bitSet.flip(2); + bitSet.flip(4); + final Holder holder = new Holder<>(bitSet); + @SuppressWarnings("unchecked") + final Holder deserialized = deserialize(serialize(holder), Holder.class); + assertDeepEquals(deserialized, holder); + } + + @Test() + public void testCopyBitSet() throws Exception { + final BitSet bitSet = new BitSet(10); + bitSet.flip(2); + bitSet.flip(4); + final BitSet copy = _kryo.copy(bitSet); + assertDeepEquals(copy, bitSet); + } + + @Test() + public void testURI() throws Exception { + final Holder uri = new Holder<>(new URI("http://www.google.com")); + @SuppressWarnings("unchecked") + final Holder deserialized = deserialize(serialize(uri), Holder.class); + assertDeepEquals(deserialized, uri); + } + + @Test() + public void testCopyURI() throws Exception { + final Holder uri = new Holder<>(new URI("http://www.google.com")); + final Holder copy = _kryo.copy(uri); + assertDeepEquals(copy, uri); + } + + @Test() + public void testUUID() throws Exception { + final Holder uuid = new Holder<>(UUID.randomUUID()); + @SuppressWarnings("unchecked") + final Holder deserialized = deserialize(serialize(uuid), Holder.class); + assertDeepEquals(deserialized, uuid); + } + + @Test() + public void testCopyUUID() throws Exception { + final Holder uuid = new Holder<>(UUID.randomUUID()); + final Holder copy = _kryo.copy(uuid); + assertDeepEquals(copy, uuid); + } + + @Test() + public void testRegex() throws Exception { + final Holder pattern = new Holder<>(Pattern.compile("regex")); + @SuppressWarnings("unchecked") + final Holder deserialized = deserialize(serialize(pattern), Holder.class); + assertDeepEquals(deserialized, pattern); + + final Holder patternWithFlags = + new Holder<>(Pattern.compile("\n", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE)); + @SuppressWarnings("unchecked") + final Holder deserializedWithFlags = deserialize(serialize(patternWithFlags), Holder.class); + assertDeepEquals(deserializedWithFlags, patternWithFlags); + } + + @Test() + public void testCopyRegex() throws Exception { + final Holder pattern = new Holder<>(Pattern.compile("regex")); + final Holder copy = _kryo.copy(pattern); + assertDeepEquals(copy, pattern); + + final Holder patternWithFlags = + new Holder<>(Pattern.compile("\n", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE)); + final Holder copyWithFlags = _kryo.copy(patternWithFlags); + assertDeepEquals(copyWithFlags, patternWithFlags); + } + + @Test() + public void testStringBuffer() throws Exception { + final StringBuffer stringBuffer = + new StringBuffer("with some content \n& some lines..."); + final StringBuffer deserialized = deserialize(serialize(stringBuffer), StringBuffer.class); + assertDeepEquals(deserialized, stringBuffer); + } + + @Test() + public void testStringBuilder() throws Exception { + final StringBuilder stringBuilder = + new StringBuilder("with some content \n& some lines..."); + final StringBuilder deserialized = deserialize(serialize(stringBuilder), StringBuilder.class); + assertDeepEquals(deserialized, stringBuilder); + } + + @Test() + public void testMapWithIntConstructorOnly() throws Exception { + final HashMapWithIntConstructorOnly map = new HashMapWithIntConstructorOnly(5); + final HashMapWithIntConstructorOnly deserialized = + deserialize(serialize(map), HashMapWithIntConstructorOnly.class); + assertDeepEquals(deserialized, map); + + } + + @Test() + public void testCurrency() throws Exception { + final Currency currency = Currency.getInstance("EUR"); + final Currency deserialized = deserialize(serialize(currency), Currency.class); + assertDeepEquals(deserialized, currency); + + // Check that the transient field defaultFractionDigits is initialized correctly + Assert.assertEquals(deserialized.getCurrencyCode(), currency.getCurrencyCode()); + Assert.assertEquals(deserialized.getDefaultFractionDigits(), currency.getDefaultFractionDigits()); + } + + @DataProvider + public Object[][] unmodifiableCollections() { + final HashMap m = new HashMap<>(); + m.put("foo", "bar"); + return new Object[][] { { Collections.unmodifiableList(new ArrayList<>(Arrays.asList("foo", "bar"))) }, + { Collections.unmodifiableSet(new HashSet<>(Arrays.asList("foo", "bar"))) }, + { Collections.unmodifiableMap(m) }, }; + } + + @SuppressWarnings("unchecked") + @Test(dataProvider = "unmodifiableCollections") + public void testUnmodifiableCollections(final Object collection) throws Exception { + final Holder holder = new Holder<>(collection); + final Holder deserialized = deserialize(serialize(holder), Holder.class); + assertDeepEquals(deserialized, holder); + } + + @Test(dataProvider = "unmodifiableCollections") + public void testCopyUnmodifiableCollections(final Object collection) throws Exception { + final Holder unmodifiableCollection = new Holder<>(collection); + final Holder copy = _kryo.copy(unmodifiableCollection); + assertDeepEquals(copy, unmodifiableCollection); + } + + @DataProvider + public Object[][] synchronizedCollections() { + final HashMap m = new HashMap<>(); + m.put("foo", "bar"); + return new Object[][] { { Collections.synchronizedList(new ArrayList<>(Arrays.asList("foo", "bar"))) }, + { Collections.synchronizedSet(new HashSet<>(Arrays.asList("foo", "bar"))) }, + { Collections.synchronizedMap(m) }, }; + } + + @SuppressWarnings("unchecked") + @Test(dataProvider = "synchronizedCollections") + public void testSynchronizedCollections(final Object collection) throws Exception { + final Holder holder = new Holder<>(collection); + final Holder deserialized = deserialize(serialize(holder), Holder.class); + assertDeepEquals(deserialized, holder); + } + + @Test(dataProvider = "synchronizedCollections") + public void testCopySynchronizedCollections(final Object collection) throws Exception { + final Holder synchronizedCollection = new Holder<>(collection); + final Holder copy = _kryo.copy(synchronizedCollection); + assertDeepEquals(copy, synchronizedCollection); + } + + @SuppressWarnings("unchecked") + @Test() + public void testJavaUtilCollectionsEmptyList() throws Exception { + final Holder> emptyList = new Holder<>(Collections.emptyList()); + final Holder> deserialized = deserialize(serialize(emptyList), Holder.class); + assertDeepEquals(deserialized, emptyList); + } + + @Test() + public void testCopyJavaUtilCollectionsEmptyList() throws Exception { + final Holder> emptyList = new Holder<>(Collections.emptyList()); + final Holder> copy = _kryo.copy(emptyList); + assertDeepEquals(copy, emptyList); + } + + @SuppressWarnings("unchecked") + @Test() + public void testJavaUtilCollectionsEmptySet() throws Exception { + final Holder> emptyList = new Holder<>(Collections.emptySet()); + final Holder> deserialized = deserialize(serialize(emptyList), Holder.class); + assertDeepEquals(deserialized, emptyList); + } + + @Test() + public void testCopyJavaUtilCollectionsEmptySet() throws Exception { + final Holder> emptyList = new Holder<>(Collections.emptySet()); + final Holder> copy = _kryo.copy(emptyList); + assertDeepEquals(copy, emptyList); + } + + @SuppressWarnings("unchecked") + @Test() + public void testJavaUtilCollectionsEmptyMap() throws Exception { + final Holder> emptyMap = new Holder<>(Collections.emptyMap()); + final Holder> deserialized = deserialize(serialize(emptyMap), Holder.class); + assertDeepEquals(deserialized, emptyMap); + } + + @Test() + public void testCopyJavaUtilCollectionsEmptyMap() throws Exception { + final Holder> emptyMap = new Holder<>(Collections.emptyMap()); + final Holder> copy = _kryo.copy(emptyMap); + assertDeepEquals(copy, emptyMap); + } + + @SuppressWarnings({ "unchecked", "ArraysAsListWithZeroOrOneArgument" }) + @Test() + public void testJavaUtilArraysAsListEmpty() throws Exception { + final Holder> asListHolder = new Holder<>(Arrays.asList()); + final Holder> deserialized = deserialize(serialize(asListHolder), Holder.class); + assertDeepEquals(deserialized, asListHolder); + } + + @SuppressWarnings("unchecked") + @Test() + public void testJavaUtilArraysAsListPrimitiveArrayElement() throws Exception { + final int[] values = { 1, 2 }; + final Holder> asListHolder = new Holder(Arrays.asList(new Object[] { values })); + final Holder> deserialized = deserialize(serialize(asListHolder), Holder.class); + assertDeepEquals(deserialized, asListHolder); + } + + @SuppressWarnings("unchecked") + @Test() + public void testJavaUtilArraysAsListBoxedPrimitives() throws Exception { + final Integer[] values = { 1, 2 }; + final List list = Arrays.asList(values); + @SuppressWarnings("rawtypes") + final Holder> asListHolder = new Holder(list); + final Holder> deserialized = deserialize(serialize(asListHolder), Holder.class); + assertDeepEquals(deserialized, asListHolder); + } + + @SuppressWarnings("unchecked") + @Test() + public void testJavaUtilArraysAsListString() throws Exception { + final Holder> asListHolder = new Holder<>(Arrays.asList("foo", "bar")); + final Holder> deserialized = deserialize(serialize(asListHolder), Holder.class); + assertDeepEquals(deserialized, asListHolder); + } + + @SuppressWarnings({ "unchecked", "ArraysAsListWithZeroOrOneArgument" }) + @Test() + public void testJavaUtilArraysAsListEmail() throws Exception { + final Holder> asListHolder = new Holder<>(Arrays.asList(new Email("foo", "foo@example.org"))); + final Holder> deserialized = deserialize(serialize(asListHolder), Holder.class); + assertDeepEquals(deserialized, asListHolder); + } + + @Test() + public void testCopyJavaUtilArraysAsList() throws Exception { + final List list = Arrays.asList("foo", "bar"); + final List copy = _kryo.copy(list); + assertDeepEquals(copy, list); + } + + @Test() + public void testJdkProxy() throws Exception { + final Holder bean = new Holder<>(TestClasses.createProxy()); + @SuppressWarnings("unchecked") + final Holder deserialized = deserialize(serialize(bean), Holder.class); + assertDeepEquals(deserialized, bean); + } + + @Test() + public void testCopyJdkProxy() throws Exception { + final Holder bean = new Holder<>(TestClasses.createProxy()); + final Holder copy = _kryo.copy(bean); + assertDeepEquals(copy, bean); + } + + @Test() + public void testClassSerializer() throws Exception { + final Holder> clazz = new Holder>(String.class); + @SuppressWarnings("unchecked") + final Holder> deserialized = deserialize(serialize(clazz), Holder.class); + assertDeepEquals(deserialized, clazz); + } + + @Test() + public void testInnerClass() throws Exception { + // seems to be related to #15 + final Container container = TestClasses.createContainer(); + final Container deserialized = deserialize(serialize(container), Container.class); + assertDeepEquals(deserialized, container); + } + + @Test() + public void testSharedObjectIdentity_CounterHolder() throws Exception { + + final AtomicInteger sharedObject = new AtomicInteger(42); + final CounterHolder holder1 = new CounterHolder(sharedObject); + final CounterHolder holder2 = new CounterHolder(sharedObject); + final CounterHolderArray holderHolder = new CounterHolderArray(holder1, holder2); + + final CounterHolderArray deserialized = deserialize(serialize(holderHolder), CounterHolderArray.class); + assertDeepEquals(deserialized, holderHolder); + Assert.assertTrue(deserialized.holders[0].item.equals(deserialized.holders[1].item)); + + } + + @DataProvider(name = "sharedObjectIdentityProvider") + protected Object[][] createSharedObjectIdentityProviderData() { + return new Object[][] { { AtomicInteger.class.getSimpleName(), new AtomicInteger(42) }, + { Email.class.getSimpleName(), new Email("foo bar", "foo.bar@example.com") } }; + } + + @SuppressWarnings("unchecked") + @Test(dataProvider = "sharedObjectIdentityProvider") + public void testSharedObjectIdentityWithArray(final String name, final T sharedObject) throws Exception { + final Holder holder1 = new Holder<>(sharedObject); + final Holder holder2 = new Holder<>(sharedObject); + final HolderArray holderHolder = new HolderArray<>(holder1, holder2); + + final HolderArray deserialized = deserialize(serialize(holderHolder), HolderArray.class); + assertDeepEquals(deserialized, holderHolder); + Assert.assertTrue(deserialized.holders[0].item == deserialized.holders[1].item); + } + + @SuppressWarnings("unchecked") + @Test(dataProvider = "sharedObjectIdentityProvider") + public void testSharedObjectIdentity(final String name, final T sharedObject) throws Exception { + final Holder holder1 = new Holder<>(sharedObject); + final Holder holder2 = new Holder<>(sharedObject); + final HolderList holderHolder = new HolderList<>(new ArrayList<>(Arrays.asList(holder1, holder2))); + + final HolderList deserialized = deserialize(serialize(holderHolder), HolderList.class); + assertDeepEquals(deserialized, holderHolder); + Assert.assertTrue(deserialized.holders.get(0).item == deserialized.holders.get(1).item); + } + + @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") + @DataProvider(name = "typesAsSessionAttributesProvider") + protected Object[][] createTypesAsSessionAttributesData() { + return new Object[][] { { Boolean.class, Boolean.TRUE }, { String.class, "42" }, { StringBuilder.class, new StringBuilder("42") }, { StringBuffer.class, new StringBuffer("42") }, + { Class.class, String.class }, { Long.class, 42L }, { Integer.class, 42 }, { Character.class, 'c' }, + { Byte.class, "b".getBytes(Charsets.UTF_8)[0] }, { Double.class, 42d }, { Float.class, 42f }, + { Short.class, (short) 42 }, { BigDecimal.class, new BigDecimal(42) }, { AtomicInteger.class, new AtomicInteger(42) }, { AtomicLong.class, new AtomicLong(42) }, + { MutableInt.class, new MutableInt(42) }, { Integer[].class, new Integer[] { 42 } }, + { Date.class, new Date(System.currentTimeMillis() - 10000) }, { Calendar.class, Calendar.getInstance() }, { Currency.class, Currency.getInstance("EUR") }, + { ArrayList.class, new ArrayList<>(Arrays.asList("foo")) }, { int[].class, new int[] { 1, 2 } }, + { long[].class, new long[] { 1, 2 } }, { short[].class, new short[] { 1, 2 } }, + { float[].class, new float[] { 1, 2 } }, { double[].class, new double[] { 1, 2 } }, + { int[].class, new int[] { 1, 2 } }, { byte[].class, "42".getBytes(Charsets.UTF_8) }, + { char[].class, "42".toCharArray() }, { String[].class, new String[] { "23", "42" } }, + { Person[].class, new Person[] { createPerson("foo bar", Gender.MALE, 42) } } }; + } + + @Test(dataProvider = "typesAsSessionAttributesProvider") + public void testTypesAsSessionAttributes(final Class type, final T instance) throws Exception { + @SuppressWarnings("unchecked") + final T deserialized = (T) deserialize(serialize(instance), instance.getClass()); + assertDeepEquals(deserialized, instance); + } + + @Test() + public void testTypesInContainerClass() throws Exception { + final MyContainer myContainer = new MyContainer(); + final MyContainer deserialized = deserialize(serialize(myContainer), MyContainer.class); + assertDeepEquals(deserialized, myContainer); + } + + @Test() + public void testClassWithoutDefaultConstructor() throws Exception { + final ClassWithoutDefaultConstructor obj = TestClasses.createClassWithoutDefaultConstructor("foo"); + final ClassWithoutDefaultConstructor deserialized = + deserialize(serialize(obj), ClassWithoutDefaultConstructor.class); + assertDeepEquals(deserialized, obj); + } + + @Test() + public void testPrivateClass() throws Exception { + final Holder holder = new Holder(TestClasses.createPrivateClass("foo")); + final Holder deserialized = deserialize(serialize(holder), Holder.class); + assertDeepEquals(deserialized, holder); + } + + @Test() + public void testCollections() throws Exception { + final EntityWithCollections obj = new EntityWithCollections(); + final EntityWithCollections deserialized = deserialize(serialize(obj), EntityWithCollections.class); + assertDeepEquals(deserialized, obj); + } + + @Test() + public void testCyclicDependencies() throws Exception { + final Person p1 = createPerson("foo bar", Gender.MALE, 42, "foo.bar@example.org", "foo.bar@example.com"); + final Person p2 = createPerson("bar baz", Gender.FEMALE, 42, "bar.baz@example.org", "bar.baz@example.com"); + p1.addFriend(p2); + p2.addFriend(p1); + + final Person deserialized = deserialize(serialize(p1), Person.class); + assertDeepEquals(deserialized, p1); + } + + protected byte[] serialize(final Object o) { + return serialize(_kryo, o); + } + + protected T deserialize(final byte[] in, final Class clazz) { + return deserialize(_kryo, in, clazz); + } + + public static class EntityWithCollections { + private final String[] _bars; + private final List _foos; + private final Map _bazens; + + public EntityWithCollections() { + _bars = new String[] { "foo", "bar" }; + _foos = new ArrayList<>(Arrays.asList("foo", "bar")); + _bazens = new HashMap<>(); + _bazens.put("foo", 1); + _bazens.put("bar", 2); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + Arrays.hashCode(_bars); + result = prime * result + ((_bazens == null) ? 0 : _bazens.hashCode()); + result = prime * result + ((_foos == null) ? 0 : _foos.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final EntityWithCollections other = (EntityWithCollections) obj; + if (!Arrays.equals(_bars, other._bars)) { + return false; + } + if (_bazens == null) { + if (other._bazens != null) { + return false; + } + } else if (!_bazens.equals(other._bazens)) { + return false; + } + if (_foos == null) { + return other._foos == null; + } else + return _foos.equals(other._foos); + } + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/SubListSerializersTest.java b/src/test/java/de/javakaffee/kryoserializers/SubListSerializersTest.java index 2dd9be07..0489964a 100644 --- a/src/test/java/de/javakaffee/kryoserializers/SubListSerializersTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/SubListSerializersTest.java @@ -37,147 +37,151 @@ * @author Martin Grotzke */ public class SubListSerializersTest { - - private Kryo _kryo; - - @BeforeClass - public void beforeClass() { - _kryo = new KryoReflectionFactorySupport() { - - @Override - @SuppressWarnings("rawtypes") - public Serializer getDefaultSerializer(final Class type) { - final Serializer> subListSerializer = SubListSerializers.createFor(type); - if ( subListSerializer != null ) { - return subListSerializer; - } - return super.getDefaultSerializer(type); - } - - }; - } - - private void doTest(final List subList) { - final byte[] serialized = serialize( _kryo, subList ); - @SuppressWarnings( "unchecked" ) - final List deserialized = deserialize( _kryo, serialized, subList.getClass() ); - - assertEquals( deserialized, subList ); - assertEquals( deserialized.remove( 0 ), subList.remove( 0 ) ); - } - - private void doTestCopy(final List subList) { - final List copy = _kryo.copy( subList ); - - assertEquals( copy, subList ); - assertEquals( copy.remove( 0 ), subList.remove( 0 ) ); - } - - @Test( enabled = true ) - public void testSubList () throws Exception { - final List subList = new LinkedList( Arrays.asList( TestEnum.values() ) ).subList( 1, 2 ); - doTest(subList); - } - - @Test( enabled = true ) - public void testCopySubList () throws Exception { - final List subList = new LinkedList( Arrays.asList( TestEnum.values() ) ).subList( 1, 2 ); - doTestCopy(subList); - } - - @Test( enabled = true ) - public void testSubListSubList () throws Exception { - final List subList = new LinkedList( Arrays.asList( TestEnum.values() ) ).subList( 1, 3 ).subList(1, 2); - doTest(subList); - } - - @Test( enabled = true ) - public void testCopySubListSubList () throws Exception { - final List subList = new LinkedList( Arrays.asList( TestEnum.values() ) ).subList( 1, 3 ).subList(1, 2); - doTestCopy(subList); - } - - @Test( enabled = true ) - public void testArrayListSubList () throws Exception { - final List subList = new ArrayList( Arrays.asList( TestEnum.values() ) ).subList( 1, 2 ); - doTest(subList); - } - - @Test( enabled = true ) - public void testCopyArrayListSubList () throws Exception { - final List subList = new ArrayList( Arrays.asList( TestEnum.values() ) ).subList( 1, 2 ); - doTestCopy(subList); - } - - @Test( enabled = true ) - public void testArrayListSubListSubList () throws Exception { - final List subList = new ArrayList( Arrays.asList( TestEnum.values() ) ).subList( 1, 3 ).subList(1, 2); - doTest(subList); - } - - @Test( enabled = true ) - public void testCopyArrayListSubListSubList () throws Exception { - final List subList = new ArrayList( Arrays.asList( TestEnum.values() ) ).subList( 1, 3 ).subList(1, 2); - doTestCopy(subList); - } - - @Test( enabled = true ) - public void testArrayListSubListWithSharedItems () throws Exception { - final List mylist = arrayList("1", "1", "2", "1", "1"); - final List subList = mylist.subList(0, 5); - - final byte[] serialized = serialize( _kryo, subList ); - @SuppressWarnings( "unchecked" ) - final List deserialized = deserialize( _kryo, serialized, subList.getClass() ); - - assertEquals( deserialized, subList ); - assertEquals( deserialized, mylist ); - } - - @Test( enabled = true ) - @SuppressWarnings( "unchecked" ) - public void testNestedArrayListSubListWithSharedItems_1() throws Exception { - final List l1 = arrayList("1", "1", "2"); - final List l1s1 = l1.subList(0, 3); - - final List l1s2 = l1.subList(1, 3); - - final List l2 = arrayList("1", "2", "3"); - final List l2s1 = l2.subList(0, 3); - - final List> lists = new ArrayList>(Arrays.asList(l1s1, l1s2, l2s1, l1, l2)); - - final byte[] serialized = serialize( _kryo, lists ); - final List> deserialized = deserialize( _kryo, serialized, lists.getClass() ); - - assertEquals( deserialized, lists ); - } - - @Test( enabled = true ) - @SuppressWarnings( "unchecked" ) - public void testNestedArrayListSubListWithSharedItems_2() throws Exception { - final List l1 = arrayList("1", "1", "2"); - final List l1s1 = l1.subList(0, 3); - - final List l1s2 = l1.subList(1, 3); - - final List l2 = arrayList("1", "2", "3"); - final List l2s1 = l2.subList(0, 3); - - final List> lists = new ArrayList>(Arrays.asList(l1, l2, l1s1, l1s2, l2s1)); - - final byte[] serialized = serialize( _kryo, lists ); - final List> deserialized = deserialize( _kryo, serialized, lists.getClass() ); - - assertEquals( deserialized, lists ); - } - - static enum TestEnum { - ITEM1, ITEM2, ITEM3; - } - - private static ArrayList arrayList(final T ... items) { - return new ArrayList(Arrays.asList(items)); - } - -} \ No newline at end of file + + private Kryo _kryo; + + @SafeVarargs + private static ArrayList arrayList(final T... items) { + return new ArrayList<>(Arrays.asList(items)); + } + + @BeforeClass + public void beforeClass() { + _kryo = new KryoReflectionFactorySupport() { + + @Override + @SuppressWarnings("rawtypes") + public Serializer getDefaultSerializer(final Class type) { + final Serializer> subListSerializer = SubListSerializers.createFor(type); + if (subListSerializer != null) { + return subListSerializer; + } + return super.getDefaultSerializer(type); + } + + }; + } + + private void doTest(final List subList) { + final byte[] serialized = serialize(_kryo, subList); + @SuppressWarnings("unchecked") + final List deserialized = deserialize(_kryo, serialized, subList.getClass()); + + assertEquals(deserialized, subList); + assertEquals(deserialized.remove(0), subList.remove(0)); + } + + private void doTestCopy(final List subList) { + final List copy = _kryo.copy(subList); + + assertEquals(copy, subList); + assertEquals(copy.remove(0), subList.remove(0)); + } + + @Test() + public void testSubList() { + final List subList = new LinkedList<>(Arrays.asList(TestEnum.values())).subList(1, 2); + doTest(subList); + } + + @Test() + public void testCopySubList() { + final List subList = new LinkedList<>(Arrays.asList(TestEnum.values())).subList(1, 2); + doTestCopy(subList); + } + + @Test() + public void testSubListSubList() { + final List subList = new LinkedList<>(Arrays.asList(TestEnum.values())).subList(1, 3).subList(1, 2); + doTest(subList); + } + + @Test() + public void testCopySubListSubList() { + final List subList = new LinkedList<>(Arrays.asList(TestEnum.values())).subList(1, 3).subList(1, 2); + doTestCopy(subList); + } + + @Test() + public void testArrayListSubList() { + final List subList = new ArrayList<>(Arrays.asList(TestEnum.values())).subList(1, 2); + doTest(subList); + } + + @Test() + public void testCopyArrayListSubList() { + final List subList = new ArrayList<>(Arrays.asList(TestEnum.values())).subList(1, 2); + doTestCopy(subList); + } + + @Test() + public void testArrayListSubListSubList() { + final List subList = new ArrayList<>(Arrays.asList(TestEnum.values())).subList(1, 3).subList(1, 2); + doTest(subList); + } + + @Test() + public void testCopyArrayListSubListSubList() { + final List subList = new ArrayList<>(Arrays.asList(TestEnum.values())).subList(1, 3).subList(1, 2); + doTestCopy(subList); + } + + @Test() + public void testArrayListSubListWithSharedItems() { + final List mylist = arrayList("1", "1", "2", "1", "1"); + final List subList = mylist.subList(0, 5); + + final byte[] serialized = serialize(_kryo, subList); + @SuppressWarnings("unchecked") + final List deserialized = deserialize(_kryo, serialized, subList.getClass()); + + assertEquals(deserialized, subList); + assertEquals(deserialized, mylist); + } + + @Test() + @SuppressWarnings({ "unchecked", "Duplicates" }) + public void testNestedArrayListSubListWithSharedItems_1() { + final List list1 = arrayList("1", "1", "2"); + final List list1SubList1 = list1.subList(0, 3); + + final List list1SubList2 = list1.subList(1, 3); + + final List list2 = arrayList("1", "2", "3"); + final List list2SubList1 = list2.subList(0, 3); + + final List> lists = + new ArrayList<>(Arrays.asList(list1SubList1, list1SubList2, list2SubList1, list1, list2)); + + final byte[] serialized = serialize(_kryo, lists); + final List> deserialized = deserialize(_kryo, serialized, lists.getClass()); + + assertEquals(deserialized, lists); + } + + @Test() + @SuppressWarnings({ "unchecked", "Duplicates" }) + public void testNestedArrayListSubListWithSharedItems_2() { + final List l1 = arrayList("1", "1", "2"); + final List l1s1 = l1.subList(0, 3); + + final List l1s2 = l1.subList(1, 3); + + final List l2 = arrayList("1", "2", "3"); + final List l2s1 = l2.subList(0, 3); + + final List> lists = new ArrayList<>(Arrays.asList(l1, l2, l1s1, l1s2, l2s1)); + + final byte[] serialized = serialize(_kryo, lists); + final List> deserialized = deserialize(_kryo, serialized, lists.getClass()); + + assertEquals(deserialized, lists); + } + + enum TestEnum { + ITEM1, + ITEM2, + ITEM3 + } + +} diff --git a/src/test/java/de/javakaffee/kryoserializers/TestClasses.java b/src/test/java/de/javakaffee/kryoserializers/TestClasses.java index d2468cc1..96534bcd 100644 --- a/src/test/java/de/javakaffee/kryoserializers/TestClasses.java +++ b/src/test/java/de/javakaffee/kryoserializers/TestClasses.java @@ -21,844 +21,789 @@ import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Collection; -import java.util.Currency; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; -import org.apache.commons.lang.mutable.MutableInt; +import org.apache.commons.lang3.mutable.MutableInt; -import de.javakaffee.kryoserializers.TestClasses.Person.Gender; +import com.google.common.base.Charsets; +import de.javakaffee.kryoserializers.TestClasses.Person.Gender; /** - * Test for {@link JavolutionTranscoder} + * Test utilities * * @author Martin Grotzke */ +@SuppressWarnings({ "SameParameterValue", "WeakerAccess", "unused" }) public class TestClasses { - static Person createPerson( final String name, final Gender gender, final String... emailAddresses ) { - final Person person = new Person(); - person.setName( name ); - person.setGender( gender ); - if ( emailAddresses != null ) { - final HashMap props = new HashMap(); - for ( int i = 0; i < emailAddresses.length; i++ ) { - final String emailAddress = emailAddresses[i]; - props.put( "email" + i, new Email( name, emailAddress ) ); - } - person.setProps( props ); - } - return person; - } - - static Person createPerson( final String name, final Gender gender, final Integer age, final String... emailAddresses ) { - final Person person = new Person(); - person.setName( name ); - person.setGender( gender ); - person.setAge( age ); - final HashMap props = new HashMap(); - for ( int i = 0; i < emailAddresses.length; i++ ) { - final String emailAddress = emailAddresses[i]; - props.put( "email" + i, new Email( name, emailAddress ) ); - } - person.setProps( props ); - return person; - } - - static ClassWithoutDefaultConstructor createClassWithoutDefaultConstructor( final String string ) { - return new ClassWithoutDefaultConstructor( string ); - } - - static PrivateClass createPrivateClass( final String string ) { - final PrivateClass result = new PrivateClass(); - result.foo = string; - return result; - } - - static Container createContainer() { - return new Container(); - } - - static SomeInterface createProxy() { - return (SomeInterface) Proxy.newProxyInstance( Thread.currentThread().getContextClassLoader(), - new Class[] { SomeInterface.class, Serializable.class }, - new MyInvocationHandler( SomeInterfaceImpl.class ) ); - } - - static class MyInvocationHandler implements InvocationHandler { - - private final Class _targetClazz; - private transient Object _target; - - public MyInvocationHandler( final Class targetClazz ) { - _targetClazz = targetClazz; - } - - public Object invoke( final Object proxy, final Method method, final Object[] args ) throws Throwable { - if ( _target == null ) { - _target = _targetClazz.newInstance(); - } - return method.invoke( _target, args ); - } - } - - static interface SomeInterface { - String hello(); - } - - static class SomeInterfaceImpl implements SomeInterface { - - /** - * {@inheritDoc} - */ - public String hello() { - return "hi"; - } - - } - - public static class Container { - - @SuppressWarnings( "unused" ) - private final Body _body; - - public Container() { - _body = new Body(); - } - - class Body { - } - - } - - public static class Person implements Serializable { - - private static final long serialVersionUID = 1L; - - static enum Gender { - MALE, - FEMALE - } - - private String _name; - private Gender _gender; - private Integer _age; - private Map _props; - private final Collection _friends = new ArrayList(); - - public String getName() { - return _name; - } - - public void addFriend( final Person p ) { - _friends.add( p ); - } - - public void setName( final String name ) { - _name = name; - } - - public Map getProps() { - return _props; - } - - public void setProps( final Map props ) { - _props = props; - } - - public Gender getGender() { - return _gender; - } - - public void setGender( final Gender gender ) { - _gender = gender; - } - - public Integer getAge() { - return _age; - } - - public void setAge( final Integer age ) { - _age = age; - } - - public Collection getFriends() { - return _friends; - } - - /** - * @param friends - * @param friends2 - * @return - */ - private boolean flatEquals( final Collection c1, final Collection c2 ) { - return c1 == c2 || c1 != null && c2 != null && c1.size() == c2.size(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ( ( _age == null ) - ? 0 - : _age.hashCode() ); - result = prime * result + ( ( _friends == null ) - ? 0 - : _friends.size() ); - result = prime * result + ( ( _gender == null ) - ? 0 - : _gender.hashCode() ); - result = prime * result + ( ( _name == null ) - ? 0 - : _name.hashCode() ); - result = prime * result + ( ( _props == null ) - ? 0 - : _props.hashCode() ); - return result; - } - - @Override - public boolean equals( final Object obj ) { - if ( this == obj ) { - return true; - } - if ( obj == null ) { - return false; - } - if ( getClass() != obj.getClass() ) { - return false; - } - final Person other = (Person) obj; - if ( _age == null ) { - if ( other._age != null ) { - return false; - } - } else if ( !_age.equals( other._age ) ) { - return false; - } - if ( _friends == null ) { - if ( other._friends != null ) { - return false; - } - } else if ( !flatEquals( _friends, other._friends ) ) { - return false; - } - if ( _gender == null ) { - if ( other._gender != null ) { - return false; - } - } else if ( !_gender.equals( other._gender ) ) { - return false; - } - if ( _name == null ) { - if ( other._name != null ) { - return false; - } - } else if ( !_name.equals( other._name ) ) { - return false; - } - if ( _props == null ) { - if ( other._props != null ) { - return false; - } - } else if ( !_props.equals( other._props ) ) { - return false; - } - return true; - } - - @Override - public String toString() { - return "Person [_age=" + _age + ", _friends.size=" + _friends.size() + ", _gender=" + _gender + ", _name=" + _name - + ", _props=" + _props + "]"; - } - - } - - public static class Email implements Serializable { - - private static final long serialVersionUID = 1L; - - private String _name; - private String _email; - - public Email() { - } - - public Email( final String name, final String email ) { - super(); - _name = name; - _email = email; - } - - public String getName() { - return _name; - } - - public void setName( final String name ) { - _name = name; - } - - public String getEmail() { - return _email; - } - - public void setEmail( final String email ) { - _email = email; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ( ( _email == null ) - ? 0 - : _email.hashCode() ); - result = prime * result + ( ( _name == null ) - ? 0 - : _name.hashCode() ); - return result; - } - - @Override - public boolean equals( final Object obj ) { - if ( this == obj ) { - return true; - } - if ( obj == null ) { - return false; - } - if ( getClass() != obj.getClass() ) { - return false; - } - final Email other = (Email) obj; - if ( _email == null ) { - if ( other._email != null ) { - return false; - } - } else if ( !_email.equals( other._email ) ) { - return false; - } - if ( _name == null ) { - if ( other._name != null ) { - return false; - } - } else if ( !_name.equals( other._name ) ) { - return false; - } - return true; - } - - @Override - public String toString() { - return "Email [_email=" + _email + ", _name=" + _name + "]"; - } - - } - - public static class PublicClass { - PrivateClass privateClass; - - public PublicClass() { - } - - public PublicClass( final PrivateClass protectedClass ) { - this.privateClass = protectedClass; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ( ( privateClass == null ) - ? 0 - : privateClass.hashCode() ); - return result; - } - - @Override - public boolean equals( final Object obj ) { - if ( this == obj ) { - return true; - } - if ( obj == null ) { - return false; - } - if ( getClass() != obj.getClass() ) { - return false; - } - final PublicClass other = (PublicClass) obj; - if ( privateClass == null ) { - if ( other.privateClass != null ) { - return false; - } - } else if ( !privateClass.equals( other.privateClass ) ) { - return false; - } - return true; - } - } - - private static class PrivateClass { - String foo; - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ( ( foo == null ) - ? 0 - : foo.hashCode() ); - return result; - } - - @Override - public boolean equals( final Object obj ) { - if ( this == obj ) { - return true; - } - if ( obj == null ) { - return false; - } - if ( getClass() != obj.getClass() ) { - return false; - } - final PrivateClass other = (PrivateClass) obj; - if ( foo == null ) { - if ( other.foo != null ) { - return false; - } - } else if ( !foo.equals( other.foo ) ) { - return false; - } - return true; - } - } - - public static class ClassWithoutDefaultConstructor { - final String value; - - public ClassWithoutDefaultConstructor( final String value ) { - this.value = value; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ( ( value == null ) - ? 0 - : value.hashCode() ); - return result; - } - - @Override - public boolean equals( final Object obj ) { - if ( this == obj ) { - return true; - } - if ( obj == null ) { - return false; - } - if ( getClass() != obj.getClass() ) { - return false; - } - final ClassWithoutDefaultConstructor other = (ClassWithoutDefaultConstructor) obj; - if ( value == null ) { - if ( other.value != null ) { - return false; - } - } else if ( !value.equals( other.value ) ) { - return false; - } - return true; - } - - @Override - public String toString() { - return "ClassWithoutDefaultConstructor [value=" + value + "]"; - } - } - - @SuppressWarnings( "unused" ) - public static class MyContainer { - - private int _int; - private long _long; - private final boolean _boolean; - private final Boolean _Boolean; - private final Class _Class; - private String _String; - private final StringBuilder _StringBuilder; - private final StringBuffer _StringBuffer; - private Long _Long; - private Integer _Integer; - private Character _Character; - private Byte _Byte; - private Double _Double; - private Float _Float; - private Short _Short; - private BigDecimal _BigDecimal; - private AtomicInteger _AtomicInteger; - private AtomicLong _AtomicLong; - private MutableInt _MutableInt; - private Integer[] _IntegerArray; - private Date _Date; - private Calendar _Calendar; - private final Currency _Currency; - private List _ArrayList; - private final Set _HashSet; - private final Map _HashMap; - private int[] _intArray; - private long[] _longArray; - private short[] _shortArray; - private float[] _floatArray; - private double[] _doubleArray; - private byte[] _byteArray; - private char[] _charArray; - private String[] _StringArray; - private Person[] _PersonArray; - - public MyContainer() { - - _int = 1; - _long = 2; - _boolean = true; - _Boolean = Boolean.TRUE; - _Class = String.class; - _String = "3"; - _StringBuffer = new StringBuffer( "foo" ); - _StringBuilder = new StringBuilder( "foo" ); - _Long = new Long( 4 ); - _Integer = new Integer( 5 ); - _Character = new Character( 'c' ); - _Byte = new Byte( "b".getBytes()[0] ); - _Double = new Double( 6d ); - _Float = new Float( 7f ); - _Short = new Short( (short) 8 ); - _BigDecimal = new BigDecimal( 9 ); - _AtomicInteger = new AtomicInteger( 10 ); - _AtomicLong = new AtomicLong( 11 ); - _MutableInt = new MutableInt( 12 ); - _IntegerArray = new Integer[] { 13 }; - _Date = new Date( System.currentTimeMillis() - 10000 ); - _Calendar = Calendar.getInstance(); - _Currency = Currency.getInstance( "EUR" ); - _ArrayList = new ArrayList( Arrays.asList( "foo" ) ); - _HashSet = new HashSet(); - _HashSet.add( "14" ); - - _HashMap = new HashMap(); - _HashMap.put( "foo", 23 ); - _HashMap.put( "bar", 42 ); - - _intArray = new int[] { 1, 2 }; - _longArray = new long[] { 1, 2 }; - _shortArray = new short[] { 1, 2 }; - _floatArray = new float[] { 1, 2 }; - _doubleArray = new double[] { 1, 2 }; - _byteArray = "42".getBytes(); - _charArray = "42".toCharArray(); - _StringArray = new String[] { "23", "42" }; - _PersonArray = new Person[] { createPerson( "foo bar", Gender.MALE, 42 ) }; - - } - - public int getInt() { - return _int; - } - - public void setInt( final int i ) { - _int = i; - } - - public long getLong() { - return _long; - } - - public void setLong( final long l ) { - _long = l; - } - - public String getString() { - return _String; - } - - public void setString( final String string ) { - _String = string; - } - - public Long getLongWrapper() { - return _Long; - } - - public void setLongWrapper( final Long l ) { - _Long = l; - } - - public Integer getInteger() { - return _Integer; - } - - public void setInteger( final Integer integer ) { - _Integer = integer; - } - - public Character getCharacter() { - return _Character; - } - - public void setCharacter( final Character character ) { - _Character = character; - } - - public Byte getByte() { - return _Byte; - } - - public void setByte( final Byte b ) { - _Byte = b; - } - - public Double getDouble() { - return _Double; - } - - public void setDouble( final Double d ) { - _Double = d; - } - - public Float getFloat() { - return _Float; - } - - public void setFloat( final Float f ) { - _Float = f; - } - - public Short getShort() { - return _Short; - } - - public void setShort( final Short s ) { - _Short = s; - } - - public BigDecimal getBigDecimal() { - return _BigDecimal; - } + static Person createPerson(final String name, final Gender gender, final String... emailAddresses) { + final Person person = new Person(); + person.setName(name); + person.setGender(gender); + if (emailAddresses != null) { + final HashMap props = new HashMap<>(); + for (int i = 0; i < emailAddresses.length; i++) { + final String emailAddress = emailAddresses[i]; + props.put("email" + i, new Email(name, emailAddress)); + } + person.setProps(props); + } + return person; + } + + static Person createPerson(final String name, final Gender gender, final Integer age, + final String... emailAddresses) { + final Person person = new Person(); + person.setName(name); + person.setGender(gender); + person.setAge(age); + final HashMap props = new HashMap<>(); + for (int i = 0; i < emailAddresses.length; i++) { + final String emailAddress = emailAddresses[i]; + props.put("email" + i, new Email(name, emailAddress)); + } + person.setProps(props); + return person; + } + + static ClassWithoutDefaultConstructor createClassWithoutDefaultConstructor(final String string) { + return new ClassWithoutDefaultConstructor(string); + } + + static PrivateClass createPrivateClass(final String string) { + final PrivateClass result = new PrivateClass(); + result.foo = string; + return result; + } + + static Container createContainer() { + return new Container(); + } + + static SomeInterface createProxy() { + return (SomeInterface) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), + new Class[] { SomeInterface.class, Serializable.class }, + new MyInvocationHandler(SomeInterfaceImpl.class)); + } + + interface SomeInterface { + String hello(); + } + + static class MyInvocationHandler implements InvocationHandler { + + private final Class _targetClazz; + private transient Object _target; + + public MyInvocationHandler(final Class targetClazz) { + _targetClazz = targetClazz; + } + + public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { + if (_target == null) { + _target = _targetClazz.newInstance(); + } + return method.invoke(_target, args); + } + } + + static class SomeInterfaceImpl implements SomeInterface { + + /** + * {@inheritDoc} + */ + public String hello() { + return "hi"; + } + + } + + public static class Container { + + @SuppressWarnings("unused") + private final Body _body; + + public Container() { + _body = new Body(); + } + + class Body { + } + + } + + public static class Person implements Serializable { + + private static final long serialVersionUID = 1L; + private final Collection _friends = new ArrayList<>(); + private String _name; + private Gender _gender; + private Integer _age; + private Map _props; + + public String getName() { + return _name; + } + + public void setName(final String name) { + _name = name; + } + + public void addFriend(final Person p) { + _friends.add(p); + } + + public Map getProps() { + return _props; + } + + public void setProps(final Map props) { + _props = props; + } + + public Gender getGender() { + return _gender; + } + + public void setGender(final Gender gender) { + _gender = gender; + } + + public Integer getAge() { + return _age; + } + + public void setAge(final Integer age) { + _age = age; + } + + public Collection getFriends() { + return _friends; + } + + private boolean flatEquals(final Collection c1, final Collection c2) { + return c1 == c2 || c1 != null && c2 != null && c1.size() == c2.size(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((_age == null) ? 0 : _age.hashCode()); + result = prime * result + _friends.size(); + result = prime * result + ((_gender == null) ? 0 : _gender.hashCode()); + result = prime * result + ((_name == null) ? 0 : _name.hashCode()); + result = prime * result + ((_props == null) ? 0 : _props.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Person other = (Person) obj; + if (_age == null) { + if (other._age != null) { + return false; + } + } else if (!_age.equals(other._age)) { + return false; + } + if (!flatEquals(_friends, other._friends)) { + return false; + } + if (_gender == null) { + if (other._gender != null) { + return false; + } + } else if (!_gender.equals(other._gender)) { + return false; + } + if (_name == null) { + if (other._name != null) { + return false; + } + } else if (!_name.equals(other._name)) { + return false; + } + if (_props == null) { + return other._props == null; + } else + return _props.equals(other._props); + } + + @Override + public String toString() { + return "Person [_age=" + _age + ", _friends.size=" + _friends.size() + ", _gender=" + _gender + ", _name=" + + _name + ", _props=" + _props + "]"; + } + + enum Gender { + MALE, + FEMALE + } + + } + + public static class Email implements Serializable { + + private static final long serialVersionUID = 1L; + + private String _name; + private String _email; + + public Email() { + } + + public Email(final String name, final String email) { + super(); + _name = name; + _email = email; + } + + public String getName() { + return _name; + } + + public void setName(final String name) { + _name = name; + } + + public String getEmail() { + return _email; + } + + public void setEmail(final String email) { + _email = email; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((_email == null) ? 0 : _email.hashCode()); + result = prime * result + ((_name == null) ? 0 : _name.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Email other = (Email) obj; + if (_email == null) { + if (other._email != null) { + return false; + } + } else if (!_email.equals(other._email)) { + return false; + } + if (_name == null) { + return other._name == null; + } else + return _name.equals(other._name); + } + + @Override + public String toString() { + return "Email [_email=" + _email + ", _name=" + _name + "]"; + } + + } + + public static class PublicClass { + PrivateClass privateClass; + + public PublicClass() { + } + + public PublicClass(final PrivateClass protectedClass) { + this.privateClass = protectedClass; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((privateClass == null) ? 0 : privateClass.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final PublicClass other = (PublicClass) obj; + if (privateClass == null) { + return other.privateClass == null; + } else + return privateClass.equals(other.privateClass); + } + } + + private static class PrivateClass { + String foo; + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((foo == null) ? 0 : foo.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final PrivateClass other = (PrivateClass) obj; + if (foo == null) { + return other.foo == null; + } else + return foo.equals(other.foo); + } + } + + public static class ClassWithoutDefaultConstructor { + final String value; + + public ClassWithoutDefaultConstructor(final String value) { + this.value = value; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((value == null) ? 0 : value.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final ClassWithoutDefaultConstructor other = (ClassWithoutDefaultConstructor) obj; + if (value == null) { + return other.value == null; + } else + return value.equals(other.value); + } + + @Override + public String toString() { + return "ClassWithoutDefaultConstructor [value=" + value + "]"; + } + } + + @SuppressWarnings("unused") + public static class MyContainer { + + private final boolean _boolean; + private final Boolean _Boolean; + private final Class _Class; + private final StringBuilder _StringBuilder; + private final StringBuffer _StringBuffer; + private final Currency _Currency; + private final Set _HashSet; + private final Map _HashMap; + private int _int; + private long _long; + private String _String; + private Long _Long; + private Integer _Integer; + private Character _Character; + private Byte _Byte; + private Double _Double; + private Float _Float; + private Short _Short; + private BigDecimal _BigDecimal; + private AtomicInteger _AtomicInteger; + private AtomicLong _AtomicLong; + private MutableInt _MutableInt; + private Integer[] _IntegerArray; + private Date _Date; + private Calendar _Calendar; + private List _ArrayList; + private int[] _intArray; + private long[] _longArray; + private short[] _shortArray; + private float[] _floatArray; + private double[] _doubleArray; + private byte[] _byteArray; + private char[] _charArray; + private String[] _StringArray; + private Person[] _PersonArray; + + @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") + public MyContainer() { + + _int = 1; + _long = 2; + _boolean = true; + _Boolean = Boolean.TRUE; + _Class = String.class; + _String = "3"; + _StringBuffer = new StringBuffer("foo"); + _StringBuilder = new StringBuilder("foo"); + _Long = 4L; + _Integer = 5; + _Character = 'c'; + _Byte = "b".getBytes(Charsets.UTF_8)[0]; + _Double = 6d; + _Float = 7f; + _Short = (short) 8; + _BigDecimal = new BigDecimal(9); + _AtomicInteger = new AtomicInteger(10); + _AtomicLong = new AtomicLong(11); + _MutableInt = new MutableInt(12); + _IntegerArray = new Integer[] { 13 }; + _Date = new Date(System.currentTimeMillis() - 10000); + _Calendar = Calendar.getInstance(); + _Currency = Currency.getInstance("EUR"); + _ArrayList = new ArrayList<>(Arrays.asList("foo")); + _HashSet = new HashSet<>(); + _HashSet.add("14"); + + _HashMap = new HashMap<>(); + _HashMap.put("foo", 23); + _HashMap.put("bar", 42); + + _intArray = new int[] { 1, 2 }; + _longArray = new long[] { 1, 2 }; + _shortArray = new short[] { 1, 2 }; + _floatArray = new float[] { 1, 2 }; + _doubleArray = new double[] { 1, 2 }; + _byteArray = "42".getBytes(Charsets.UTF_8); + _charArray = "42".toCharArray(); + _StringArray = new String[] { "23", "42" }; + _PersonArray = new Person[] { createPerson("foo bar", Gender.MALE, 42) }; + + } + + public int getInt() { + return _int; + } + + public void setInt(final int i) { + _int = i; + } + + public long getLong() { + return _long; + } + + public void setLong(final long l) { + _long = l; + } + + public String getString() { + return _String; + } + + public void setString(final String string) { + _String = string; + } + + public Long getLongWrapper() { + return _Long; + } + + public void setLongWrapper(final Long l) { + _Long = l; + } + + public Integer getInteger() { + return _Integer; + } + + public void setInteger(final Integer integer) { + _Integer = integer; + } + + public Character getCharacter() { + return _Character; + } + + public void setCharacter(final Character character) { + _Character = character; + } + + public Byte getByte() { + return _Byte; + } + + public void setByte(final Byte b) { + _Byte = b; + } + + public Double getDouble() { + return _Double; + } + + public void setDouble(final Double d) { + _Double = d; + } + + public Float getFloat() { + return _Float; + } + + public void setFloat(final Float f) { + _Float = f; + } + + public Short getShort() { + return _Short; + } + + public void setShort(final Short s) { + _Short = s; + } + + public BigDecimal getBigDecimal() { + return _BigDecimal; + } + + public void setBigDecimal(final BigDecimal bigDecimal) { + _BigDecimal = bigDecimal; + } - public void setBigDecimal( final BigDecimal bigDecimal ) { - _BigDecimal = bigDecimal; - } + public AtomicInteger getAtomicInteger() { + return _AtomicInteger; + } - public AtomicInteger getAtomicInteger() { - return _AtomicInteger; - } + public void setAtomicInteger(final AtomicInteger atomicInteger) { + _AtomicInteger = atomicInteger; + } - public void setAtomicInteger( final AtomicInteger atomicInteger ) { - _AtomicInteger = atomicInteger; - } + public AtomicLong getAtomicLong() { + return _AtomicLong; + } - public AtomicLong getAtomicLong() { - return _AtomicLong; - } + public void setAtomicLong(final AtomicLong atomicLong) { + _AtomicLong = atomicLong; + } - public void setAtomicLong( final AtomicLong atomicLong ) { - _AtomicLong = atomicLong; - } + public MutableInt getMutableInt() { + return _MutableInt; + } - public MutableInt getMutableInt() { - return _MutableInt; - } + public void setMutableInt(final MutableInt mutableInt) { + _MutableInt = mutableInt; + } - public void setMutableInt( final MutableInt mutableInt ) { - _MutableInt = mutableInt; - } + public Integer[] getIntegerArray() { + return _IntegerArray; + } - public Integer[] getIntegerArray() { - return _IntegerArray; - } + public void setIntegerArray(final Integer[] integerArray) { + _IntegerArray = integerArray; + } - public void setIntegerArray( final Integer[] integerArray ) { - _IntegerArray = integerArray; - } + public Date getDate() { + return _Date; + } - public Date getDate() { - return _Date; - } + public void setDate(final Date date) { + _Date = date; + } - public void setDate( final Date date ) { - _Date = date; - } + public Calendar getCalendar() { + return _Calendar; + } - public Calendar getCalendar() { - return _Calendar; - } + public void setCalendar(final Calendar calendar) { + _Calendar = calendar; + } - public void setCalendar( final Calendar calendar ) { - _Calendar = calendar; - } + public List getArrayList() { + return _ArrayList; + } - public List getArrayList() { - return _ArrayList; - } + public void setArrayList(final List arrayList) { + _ArrayList = arrayList; + } - public void setArrayList( final List arrayList ) { - _ArrayList = arrayList; - } + public int[] getIntArray() { + return _intArray; + } - public int[] getIntArray() { - return _intArray; - } + public void setIntArray(final int[] intArray) { + _intArray = intArray; + } - public void setIntArray( final int[] intArray ) { - _intArray = intArray; - } + public long[] getLongArray() { + return _longArray; + } - public long[] getLongArray() { - return _longArray; - } + public void setLongArray(final long[] longArray) { + _longArray = longArray; + } - public void setLongArray( final long[] longArray ) { - _longArray = longArray; - } + public short[] getShortArray() { + return _shortArray; + } - public short[] getShortArray() { - return _shortArray; - } + public void setShortArray(final short[] shortArray) { + _shortArray = shortArray; + } - public void setShortArray( final short[] shortArray ) { - _shortArray = shortArray; - } + public float[] getFloatArray() { + return _floatArray; + } - public float[] getFloatArray() { - return _floatArray; - } + public void setFloatArray(final float[] floatArray) { + _floatArray = floatArray; + } - public void setFloatArray( final float[] floatArray ) { - _floatArray = floatArray; - } + public double[] getDoubleArray() { + return _doubleArray; + } - public double[] getDoubleArray() { - return _doubleArray; - } + public void setDoubleArray(final double[] doubleArray) { + _doubleArray = doubleArray; + } - public void setDoubleArray( final double[] doubleArray ) { - _doubleArray = doubleArray; - } + public byte[] getByteArray() { + return _byteArray; + } - public byte[] getByteArray() { - return _byteArray; - } + public void setByteArray(final byte[] byteArray) { + _byteArray = byteArray; + } - public void setByteArray( final byte[] byteArray ) { - _byteArray = byteArray; - } + public char[] getCharArray() { + return _charArray; + } - public char[] getCharArray() { - return _charArray; - } + public void setCharArray(final char[] charArray) { + _charArray = charArray; + } - public void setCharArray( final char[] charArray ) { - _charArray = charArray; - } + public String[] getStringArray() { + return _StringArray; + } - public String[] getStringArray() { - return _StringArray; - } + public void setStringArray(final String[] stringArray) { + _StringArray = stringArray; + } - public void setStringArray( final String[] stringArray ) { - _StringArray = stringArray; - } + public Person[] getPersonArray() { + return _PersonArray; + } - public Person[] getPersonArray() { - return _PersonArray; - } + public void setPersonArray(final Person[] personArray) { + _PersonArray = personArray; + } - public void setPersonArray( final Person[] personArray ) { - _PersonArray = personArray; - } + public Set getHashSet() { + return _HashSet; + } - public Set getHashSet() { - return _HashSet; - } + public Map getHashMap() { + return _HashMap; + } - public Map getHashMap() { - return _HashMap; - } + } - } + static class Holder { + T item; - static class Holder { - T item; - - /** - * Default constructor, added for kryo... - */ - public Holder() { - } + /** + * Default constructor, added for kryo... + */ + public Holder() { + } - public Holder( final T item ) { - this.item = item; - } - } + public Holder(final T item) { + this.item = item; + } + } - static class HolderList { - List> holders; + static class HolderList { + List> holders; - public HolderList( final List> holders ) { - this.holders = holders; - } - } + public HolderList(final List> holders) { + this.holders = holders; + } + } - static class CounterHolder { - AtomicInteger item; + static class CounterHolder { + AtomicInteger item; - public CounterHolder( final AtomicInteger item ) { - this.item = item; - } - } + public CounterHolder(final AtomicInteger item) { + this.item = item; + } + } - static class CounterHolderArray { - CounterHolder[] holders; + static class CounterHolderArray { + CounterHolder[] holders; - public CounterHolderArray( final CounterHolder... holders ) { - this.holders = holders; - } - } + public CounterHolderArray(final CounterHolder... holders) { + this.holders = holders; + } + } - static class HolderArray { - Holder[] holders; + static class HolderArray { + Holder[] holders; - public HolderArray( final Holder... holders ) { - this.holders = holders; - } - } + @SafeVarargs + public HolderArray(final Holder... holders) { + this.holders = holders; + } + } - public static class HashMapWithIntConstructorOnly extends HashMap { + public static class HashMapWithIntConstructorOnly extends HashMap { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - @SuppressWarnings( "unused" ) - private HashMapWithIntConstructorOnly() { - } + @SuppressWarnings("unused") + private HashMapWithIntConstructorOnly() { + } - public HashMapWithIntConstructorOnly( final int size ) { - super( size ); - } + public HashMapWithIntConstructorOnly(final int size) { + super(size); + } - } + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/UnicodeBlockSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/UnicodeBlockSerializerTest.java index cdafd4b6..c895e352 100644 --- a/src/test/java/de/javakaffee/kryoserializers/UnicodeBlockSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/UnicodeBlockSerializerTest.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers; import static de.javakaffee.kryoserializers.KryoTest.deserialize; @@ -5,15 +21,15 @@ import static org.testng.Assert.assertNull; import static org.testng.Assert.assertSame; -import com.esotericsoftware.kryo.Kryo; -import com.esotericsoftware.kryo.Kryo.DefaultInstantiatorStrategy; +import java.lang.Character.UnicodeBlock; import org.objenesis.ObjenesisStd; import org.objenesis.strategy.StdInstantiatorStrategy; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; -import java.lang.Character.UnicodeBlock; +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.Kryo.DefaultInstantiatorStrategy; /** * Test for {@link UnicodeBlockSerializer}. @@ -22,42 +38,42 @@ */ public class UnicodeBlockSerializerTest { - private static final String NONEXISTENT_BLOCK_NAME = "RURITANIAN"; - private Kryo kryo; - - private static class ThingWithUnicodeBlock { - final UnicodeBlock unicodeBlock; - - private ThingWithUnicodeBlock(UnicodeBlock unicodeBlock) { - this.unicodeBlock = unicodeBlock; - } - } - - @BeforeTest - protected void beforeTest() { - kryo = new Kryo(); - final DefaultInstantiatorStrategy instantiatorStrategy = new DefaultInstantiatorStrategy(); - instantiatorStrategy.setFallbackInstantiatorStrategy(new StdInstantiatorStrategy()); - kryo.setInstantiatorStrategy(instantiatorStrategy); - kryo.register(UnicodeBlock.class, new UnicodeBlockSerializer()); - } - - @Test - public void testBasicRoundTrip() { - byte[] serialized = serialize(kryo, UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS); - assertSame(deserialize(kryo, serialized, UnicodeBlock.class), - UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS); - } - - @Test - public void testDeserializingUnknownInstanceReturnsNull() { - byte[] serialized = serialize(kryo, new ObjenesisStd().newInstance(UnicodeBlock.class)); - assertNull(deserialize(kryo, serialized, UnicodeBlock.class)); - } - - @Test - public void testCopyContainingObject() { - ThingWithUnicodeBlock original = new ThingWithUnicodeBlock(UnicodeBlock.GREEK); - assertSame(kryo.copy(original).unicodeBlock, UnicodeBlock.GREEK); - } + private static final String NONEXISTENT_BLOCK_NAME = "RURITANIAN"; + private Kryo kryo; + + @BeforeTest + protected void beforeTest() { + kryo = new Kryo(); + final DefaultInstantiatorStrategy instantiatorStrategy = new DefaultInstantiatorStrategy(); + instantiatorStrategy.setFallbackInstantiatorStrategy(new StdInstantiatorStrategy()); + kryo.setInstantiatorStrategy(instantiatorStrategy); + kryo.register(UnicodeBlock.class, new UnicodeBlockSerializer()); + } + + @Test + public void testBasicRoundTrip() { + byte[] serialized = serialize(kryo, UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS); + assertSame(deserialize(kryo, serialized, UnicodeBlock.class), + UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS); + } + + @Test + public void testDeserializingUnknownInstanceReturnsNull() { + byte[] serialized = serialize(kryo, new ObjenesisStd().newInstance(UnicodeBlock.class)); + assertNull(deserialize(kryo, serialized, UnicodeBlock.class)); + } + + @Test + public void testCopyContainingObject() { + ThingWithUnicodeBlock original = new ThingWithUnicodeBlock(UnicodeBlock.GREEK); + assertSame(kryo.copy(original).unicodeBlock, UnicodeBlock.GREEK); + } + + private static class ThingWithUnicodeBlock { + final UnicodeBlock unicodeBlock; + + private ThingWithUnicodeBlock(UnicodeBlock unicodeBlock) { + this.unicodeBlock = unicodeBlock; + } + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/cglib/CGLibProxySerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/cglib/CGLibProxySerializerTest.java index 6294263f..0014381f 100644 --- a/src/test/java/de/javakaffee/kryoserializers/cglib/CGLibProxySerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/cglib/CGLibProxySerializerTest.java @@ -20,25 +20,14 @@ import static de.javakaffee.kryoserializers.KryoTest.serialize; import static org.testng.Assert.assertEquals; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; +import java.io.*; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import net.sf.cglib.core.DefaultNamingPolicy; -import net.sf.cglib.core.Predicate; -import net.sf.cglib.proxy.Enhancer; -import net.sf.cglib.proxy.InvocationHandler; - import org.objenesis.strategy.StdInstantiatorStrategy; - import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; @@ -49,240 +38,244 @@ import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.util.DefaultClassResolver; import com.esotericsoftware.kryo.util.MapReferenceResolver; -import com.esotericsoftware.minlog.Log; import de.javakaffee.kryoserializers.ArraysAsListSerializer; +import net.sf.cglib.core.DefaultNamingPolicy; +import net.sf.cglib.core.Predicate; +import net.sf.cglib.proxy.Enhancer; +import net.sf.cglib.proxy.InvocationHandler; + /** - * Test for {@link CGLibProxyFormat}. - * + * Test for {@link CGLibProxySerializer}. + * * @author Martin Grotzke */ public class CGLibProxySerializerTest { - - private Kryo _kryo; - - @BeforeTest - protected void beforeTest() { - _kryo = createKryo(); - } - - private Kryo createKryo() { - final DefaultClassResolver classResolver = new DefaultClassResolver() { - @Override - protected Class getTypeByName(final String className) { - if (className.indexOf(CGLibProxySerializer.DEFAULT_NAMING_MARKER) > 0) { - return CGLibProxySerializer.CGLibProxyMarker.class; - } - return super.getTypeByName(className); - } - }; - final Kryo kryo = new Kryo(classResolver, new MapReferenceResolver()) { - - @Override - @SuppressWarnings("rawtypes") - public Serializer getDefaultSerializer(final Class type) { - if ( CGLibProxySerializer.canSerialize( type ) ) { - return getSerializer(CGLibProxySerializer.CGLibProxyMarker.class); - } - return super.getDefaultSerializer(type); - } - - }; - // The default strategy is needed so that HashMap is created via the constructor, - // the StdInstantiatorStrategy (fallback) is needed for classes without default - // constructor (e.g. DelegatingHandler). - final DefaultInstantiatorStrategy instantiatorStrategy = new DefaultInstantiatorStrategy(); - instantiatorStrategy.setFallbackInstantiatorStrategy(new StdInstantiatorStrategy()); - kryo.setInstantiatorStrategy(instantiatorStrategy); - kryo.register( CGLibProxySerializer.CGLibProxyMarker.class, new CGLibProxySerializer() ); - kryo.register( Arrays.asList( "" ).getClass(), new ArraysAsListSerializer() ); - return kryo; - } - - @Test( enabled = false ) - public void testProxiesFromFileWrite() throws Exception { - Log.TRACE = true; - final ClassToProxy obj = new ClassToProxy(); - obj._value = "foo"; - final ClassToProxy proxy1 = createProxy( obj ); - final ClassToProxy proxy2 = createProxy( obj ); - final List proxies = Arrays.asList( proxy1, proxy2 ); - final OutputStream out = new FileOutputStream( new File( "/tmp/cglib-data-1.ser" ) ); - final Output output = new Output(out); - _kryo.writeClassAndObject(output, proxies); - output.close(); - } - - /** - * Uses data serialized by {@link #testProxiesFromFileWrite()} that got moved to src/main/resources. - * That serialized data is read from a file verifies that there's no hot class loader - * that might cache some proxy class. - */ - @SuppressWarnings("unchecked") - @Test( enabled = true ) - public void testProxiesFromFileRead() throws Exception { - Log.TRACE = true; - final InputStream in = new FileInputStream( new File( getClass().getResource("/cglib-data-1.ser").toURI() ) ); - final Input input = new Input(in); - final List proxies = (List) _kryo.readClassAndObject(input); - in.close(); - System.out.println(proxies); - assertEquals(2, proxies.size()); - final ClassToProxy proxy1 = proxies.get(0); - assertEquals( "foo", proxy1.getValue() ); - final ClassToProxy proxy2 = proxies.get(1); - assertEquals( "foo", proxy2.getValue() ); - // test that the proxied object is referenced by both proxies - proxy1.setValue("bar"); - assertEquals( "bar", proxy1.getValue() ); - assertEquals( "bar", proxy2.getValue() ); - } - - @Test( enabled = true ) - public void testContainerWithCGLibProxy() throws Exception { - - final CustomClassLoader loader = new CustomClassLoader( getClass().getClassLoader() ); - // _kryo.setClassLoader(loader); - - final Class myServiceClass = loader.loadClass( MyServiceImpl.class.getName() ); - final Object proxy = createProxy( myServiceClass.newInstance() ); - - final Class myContainerClass = loader.loadClass( MyContainer.class.getName() ); - final Object myContainer = myContainerClass.getConstructors()[0].newInstance( proxy ); - - System.out.println("---------------- test ------------------"); - System.out.println(proxy.getClass()); - System.out.println(Arrays.asList(proxy.getClass().getInterfaces())); - System.out.println(proxy.getClass().getSuperclass()); - System.out.println(Arrays.asList(proxy.getClass().getSuperclass().getInterfaces())); - System.out.println("---------------- END test ------------------"); - - final byte[] serialized = serialize(_kryo, myContainer); - - deserialize(_kryo, serialized, MyContainer.class); - // If we reached this kryo was able to deserialize the proxy, so we're fine - } - - @Test( enabled = true ) - public void testCGLibProxy() { - final ClassToProxy proxy = createProxy( new ClassToProxy() ); - proxy.setValue( "foo" ); - - final byte[] serialized = serialize(_kryo, proxy); - final ClassToProxy deserialized = deserialize(_kryo, serialized, proxy.getClass() ); - assertEquals( deserialized.getValue(), proxy.getValue() ); - } - - /** - * Test that a cglib proxy is handled correctly. - */ - @Test( enabled = true ) - public void testCGLibProxyForExistingFormat() { - final Map proxy = createProxy( new HashMap() ); - proxy.put( "foo", "bar" ); - assertEquals( proxy.get( "foo" ), "bar" ); - - final byte[] serialized = serialize(_kryo, proxy); - @SuppressWarnings( "unchecked" ) - final Map deserialized = deserialize(_kryo, serialized, proxy.getClass() ); - assertEquals( deserialized.get( "foo" ), proxy.get( "foo" ) ); - } - - @SuppressWarnings( "unchecked" ) - private T createProxy( final T obj ) { - - final Enhancer e = new Enhancer(); - e.setInterfaces( new Class[] { Serializable.class } ); - final Class class1 = obj.getClass(); - e.setSuperclass( class1 ); - e.setCallback( new DelegatingHandler( obj ) ); - e.setNamingPolicy( new DefaultNamingPolicy() { - @Override - public String getClassName(final String prefix, final String source, - final Object key, final Predicate names) { - return super.getClassName( "MSM_" + prefix, source, key, names ); - } - } ); - - return (T) e.create(); - } - - public static class DelegatingHandler implements InvocationHandler, Serializable { - - private static final long serialVersionUID = 1L; - - private final Object _delegate; - - public DelegatingHandler( final Object delegate ) { - _delegate = delegate; - } - - public Object invoke( final Object obj, final Method method, final Object[] args ) throws Throwable { - return method.invoke( _delegate, args ); - } - } - - public static class ClassToProxy { - private String _value; - - /** - * @param value the value to set - */ - public void setValue( final String value ) { - _value = value; - } - - /** - * @return the value - */ - public String getValue() { - return _value; - } + + private Kryo _kryo; + + @BeforeTest + protected void beforeTest() { + _kryo = createKryo(); + } + + private Kryo createKryo() { + final DefaultClassResolver classResolver = new DefaultClassResolver() { + @Override + protected Class getTypeByName(final String className) { + if (className.indexOf(CGLibProxySerializer.DEFAULT_NAMING_MARKER) > 0) { + return CGLibProxySerializer.CGLibProxyMarker.class; + } + return super.getTypeByName(className); + } + }; + final Kryo kryo = new Kryo(classResolver, new MapReferenceResolver()) { + + @Override + @SuppressWarnings("rawtypes") + public Serializer getDefaultSerializer(final Class type) { + if (CGLibProxySerializer.canSerialize(type)) { + return getSerializer(CGLibProxySerializer.CGLibProxyMarker.class); + } + return super.getDefaultSerializer(type); + } + + }; + // The default strategy is needed so that HashMap is created via the constructor, + // the StdInstantiatorStrategy (fallback) is needed for classes without default + // constructor (e.g. DelegatingHandler). + final DefaultInstantiatorStrategy instantiatorStrategy = new DefaultInstantiatorStrategy(); + instantiatorStrategy.setFallbackInstantiatorStrategy(new StdInstantiatorStrategy()); + kryo.setInstantiatorStrategy(instantiatorStrategy); + kryo.register(CGLibProxySerializer.CGLibProxyMarker.class, new CGLibProxySerializer()); + kryo.register(Arrays.asList("").getClass(), new ArraysAsListSerializer()); + return kryo; + } + + @Test(enabled = false) + public void testProxiesFromFileWrite() throws Exception { + //Log.TRACE = true; + final ClassToProxy obj = new ClassToProxy(); + obj._value = "foo"; + final ClassToProxy proxy1 = createProxy(obj); + final ClassToProxy proxy2 = createProxy(obj); + final List proxies = Arrays.asList(proxy1, proxy2); + final OutputStream out = new FileOutputStream(new File("/tmp/cglib-data-1.ser")); + final Output output = new Output(out); + _kryo.writeClassAndObject(output, proxies); + output.close(); + } + + /** + * Uses data serialized by {@link #testProxiesFromFileWrite()} that got moved to src/main/resources. + * That serialized data is read from a file verifies that there's no hot class loader + * that might cache some proxy class. + */ + @SuppressWarnings("unchecked") + @Test(enabled = true) + public void testProxiesFromFileRead() throws Exception { + //Log.TRACE = true; + final InputStream in = new FileInputStream(new File(getClass().getResource("/cglib-data-1.ser").toURI())); + final Input input = new Input(in); + final List proxies = (List) _kryo.readClassAndObject(input); + in.close(); + System.out.println(proxies); + assertEquals(2, proxies.size()); + final ClassToProxy proxy1 = proxies.get(0); + assertEquals("foo", proxy1.getValue()); + final ClassToProxy proxy2 = proxies.get(1); + assertEquals("foo", proxy2.getValue()); + // test that the proxied object is referenced by both proxies + proxy1.setValue("bar"); + assertEquals("bar", proxy1.getValue()); + assertEquals("bar", proxy2.getValue()); + } + + @Test(enabled = true) + public void testContainerWithCGLibProxy() throws Exception { + + final CustomClassLoader loader = new CustomClassLoader(getClass().getClassLoader()); + // _kryo.setClassLoader(loader); + + final Class myServiceClass = loader.loadClass(MyServiceImpl.class.getName()); + final Object proxy = createProxy(myServiceClass.newInstance()); + + final Class myContainerClass = loader.loadClass(MyContainer.class.getName()); + final Object myContainer = myContainerClass.getConstructors()[0].newInstance(proxy); + + System.out.println("---------------- test ------------------"); + System.out.println(proxy.getClass()); + System.out.println(Arrays.asList(proxy.getClass().getInterfaces())); + System.out.println(proxy.getClass().getSuperclass()); + System.out.println(Arrays.asList(proxy.getClass().getSuperclass().getInterfaces())); + System.out.println("---------------- END test ------------------"); + + final byte[] serialized = serialize(_kryo, myContainer); + + deserialize(_kryo, serialized, MyContainer.class); + // If we reached this kryo was able to deserialize the proxy, so we're fine + } + + @Test(enabled = true) + public void testCGLibProxy() { + final ClassToProxy proxy = createProxy(new ClassToProxy()); + proxy.setValue("foo"); + + final byte[] serialized = serialize(_kryo, proxy); + final ClassToProxy deserialized = deserialize(_kryo, serialized, proxy.getClass()); + assertEquals(deserialized.getValue(), proxy.getValue()); + } + + /** + * Test that a cglib proxy is handled correctly. + */ + @Test(enabled = true) + public void testCGLibProxyForExistingFormat() { + final Map proxy = createProxy(new HashMap()); + proxy.put("foo", "bar"); + assertEquals(proxy.get("foo"), "bar"); + + final byte[] serialized = serialize(_kryo, proxy); + @SuppressWarnings("unchecked") + final Map deserialized = deserialize(_kryo, serialized, proxy.getClass()); + assertEquals(deserialized.get("foo"), proxy.get("foo")); + } + + @SuppressWarnings("unchecked") + private T createProxy(final T obj) { + + final Enhancer e = new Enhancer(); + e.setInterfaces(new Class[] { Serializable.class }); + final Class class1 = obj.getClass(); + e.setSuperclass(class1); + e.setCallback(new DelegatingHandler(obj)); + e.setNamingPolicy(new DefaultNamingPolicy() { + @Override + public String getClassName(final String prefix, final String source, final Object key, + final Predicate names) { + return super.getClassName("MSM_" + prefix, source, key, names); + } + }); + + return (T) e.create(); + } + + public static interface MyService { + String sayHello(); + } + + public static class DelegatingHandler implements InvocationHandler, Serializable { + + private static final long serialVersionUID = 1L; + + private final Object _delegate; + + public DelegatingHandler(final Object delegate) { + _delegate = delegate; + } + + public Object invoke(final Object obj, final Method method, final Object[] args) throws Throwable { + return method.invoke(_delegate, args); + } + } + + public static class ClassToProxy { + private String _value; + + /** + * @return the value + */ + public String getValue() { + return _value; + } + + /** + * @param value the value to set + */ + public void setValue(final String value) { + _value = value; + } @Override public String toString() { return "ClassToProxy [_value=" + _value + "]"; } - } - - public static class MySpecialContainer extends MyContainer { - - public MySpecialContainer( final MyService myService ) { - super( myService ); - } - - } - - public static class MyContainer { - - private MyService _myService; - - public MyContainer( final MyService myService ) { - _myService = myService; - } - - public MyService getMyService() { - return _myService; - } - - public void setMyService( final MyService myService ) { - _myService = myService; - } - - } - - public static interface MyService { - String sayHello(); - } - - public static class MyServiceImpl implements MyService { - - @Override - public String sayHello() { - return "hi"; - } - - } + } + + public static class MySpecialContainer extends MyContainer { + + public MySpecialContainer(final MyService myService) { + super(myService); + } + + } + + public static class MyContainer { + + private MyService _myService; + + public MyContainer(final MyService myService) { + _myService = myService; + } + + public MyService getMyService() { + return _myService; + } + + public void setMyService(final MyService myService) { + _myService = myService; + } + + } + + public static class MyServiceImpl implements MyService { + + @Override + public String sayHello() { + return "hi"; + } + + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/cglib/CustomClassLoader.java b/src/test/java/de/javakaffee/kryoserializers/cglib/CustomClassLoader.java index 180ab653..0b84bef0 100644 --- a/src/test/java/de/javakaffee/kryoserializers/cglib/CustomClassLoader.java +++ b/src/test/java/de/javakaffee/kryoserializers/cglib/CustomClassLoader.java @@ -31,106 +31,100 @@ * other class it will use the super.loadClass() method * from ClassLoader, which will eventually pass the * request to the parent. - * - * @see Java ClassLoader (2) – Write your own ClassLoader * + * @see Java ClassLoader (2) – Write your own ClassLoader */ public class CustomClassLoader extends ClassLoader { - /** - * Parent ClassLoader passed to this constructor - * will be used if this ClassLoader can not resolve a - * particular class. - * - * @param parent Parent ClassLoader - * (may be from getClass().getClassLoader()) - */ - public CustomClassLoader(final ClassLoader parent) { - super(parent); - } + private final Set _definedClasses = new HashSet(); + + /** + * Parent ClassLoader passed to this constructor + * will be used if this ClassLoader can not resolve a + * particular class. + * + * @param parent Parent ClassLoader + * (may be from getClass().getClassLoader()) + */ + public CustomClassLoader(final ClassLoader parent) { + super(parent); + } - /** - * Loads a given class from .class file just like - * the default ClassLoader. This method could be - * changed to load the class over network from some - * other server or from the database. - * - * @param name Full class name - */ - private Class getClass(final String name) - throws ClassNotFoundException { - // We are getting a name that looks like - // javablogging.package.ClassToLoad - // and we have to convert it into the .class file name - // like javablogging/package/ClassToLoad.class - final String file = name.replace('.', File.separatorChar) - + ".class"; - byte[] b = null; - try { - // This loads the byte code data from the file - b = loadClassData(file); - // defineClass is inherited from the ClassLoader class - // and converts the byte array into a Class - final Class c = defineClass(name, b, 0, b.length); - resolveClass(c); - return c; - } catch (final IOException e) { - e.printStackTrace(); - return null; - } - } + /** + * Loads a given class from .class file just like + * the default ClassLoader. This method could be + * changed to load the class over network from some + * other server or from the database. + * + * @param name Full class name + */ + private Class getClass(final String name) throws ClassNotFoundException { + // We are getting a name that looks like + // javablogging.package.ClassToLoad + // and we have to convert it into the .class file name + // like javablogging/package/ClassToLoad.class + final String file = name.replace('.', File.separatorChar) + ".class"; + byte[] b = null; + try { + // This loads the byte code data from the file + b = loadClassData(file); + // defineClass is inherited from the ClassLoader class + // and converts the byte array into a Class + final Class c = defineClass(name, b, 0, b.length); + resolveClass(c); + return c; + } catch (final IOException e) { + e.printStackTrace(); + return null; + } + } - /** - * Every request for a class passes through this method. - * If the requested class is in "javablogging" package, - * it will load it using the - * {@link CustomClassLoader#getClass()} method. - * If not, it will use the super.loadClass() method - * which in turn will pass the request to the parent. - * - * @param name - * Full class name - */ - @Override - public Class loadClass(final String name) - throws ClassNotFoundException { - System.out.println("loading class '" + name + "'"); - if (name.startsWith( getClass().getPackage().getName() ) && !_definedClasses.contains( name ) ) { - System.out.println("-> custom loading class '" + name + "'"); - _definedClasses.add( name ); - return getClass(name); - } - return super.loadClass(name); - } + /** + * Every request for a class passes through this method. + * If the requested class is in "javablogging" package, + * it will load it using the + * {@link CustomClassLoader#getClass()} method. + * If not, it will use the super.loadClass() method + * which in turn will pass the request to the parent. + * + * @param name Full class name + */ + @Override + public Class loadClass(final String name) throws ClassNotFoundException { + System.out.println("loading class '" + name + "'"); + if (name.startsWith(getClass().getPackage().getName()) && !_definedClasses.contains(name)) { + System.out.println("-> custom loading class '" + name + "'"); + _definedClasses.add(name); + return getClass(name); + } + return super.loadClass(name); + } - private final Set _definedClasses = new HashSet(); + /** + * Loads a given file (presumably .class) into a byte array. + * The file should be accessible as a resource, for example + * it could be located on the classpath. + * + * @param name File name to load + * @return Byte array read from the file + * @throws IOException Is thrown when there + * was some problem reading the file + */ + private byte[] loadClassData(final String name) throws IOException { + // Opening the file + final InputStream stream = getClass().getClassLoader().getResourceAsStream(name); + final int size = stream.available(); + final byte buff[] = new byte[size]; + final DataInputStream in = new DataInputStream(stream); + // Reading the binary data + in.readFully(buff); + in.close(); + return buff; + } - /** - * Loads a given file (presumably .class) into a byte array. - * The file should be accessible as a resource, for example - * it could be located on the classpath. - * - * @param name File name to load - * @return Byte array read from the file - * @throws IOException Is thrown when there - * was some problem reading the file - */ - private byte[] loadClassData(final String name) throws IOException { - // Opening the file - final InputStream stream = getClass().getClassLoader() - .getResourceAsStream(name); - final int size = stream.available(); - final byte buff[] = new byte[size]; - final DataInputStream in = new DataInputStream(stream); - // Reading the binary data - in.readFully(buff); - in.close(); - return buff; - } - - @Override - protected void finalize() throws Throwable { - System.out.println( getClass().getSimpleName() + ".finalize() is being called." ); - super.finalize(); - } + @Override + protected void finalize() throws Throwable { + System.out.println(getClass().getSimpleName() + ".finalize() is being called."); + super.finalize(); + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/dexx/ListSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/dexx/ListSerializerTest.java index 021022cb..6bc36ec4 100644 --- a/src/test/java/de/javakaffee/kryoserializers/dexx/ListSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/dexx/ListSerializerTest.java @@ -1,84 +1,96 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.dexx; import static de.javakaffee.kryoserializers.KryoTest.deserialize; import static de.javakaffee.kryoserializers.KryoTest.serialize; +import static org.testng.Assert.*; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertTrue; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; import com.esotericsoftware.kryo.Kryo; - import com.github.andrewoma.dexx.collection.ArrayList; import com.github.andrewoma.dexx.collection.IndexedLists; import com.github.andrewoma.dexx.collection.List; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - /** * Test for {@link ListSerializer} */ public class ListSerializerTest { - private Kryo _kryo; - - @BeforeTest - public void setUp() throws Exception { - _kryo = new Kryo(); - - ListSerializer.registerSerializers(_kryo); - } - - @Test(enabled = true) - public void testEmpty() { - final List obj = IndexedLists.of(); - final byte[] serialized = serialize(_kryo, obj); - final List deserialized = deserialize(_kryo, serialized, List.class); - assertTrue(deserialized.isEmpty()); - assertEquals(deserialized.size(), obj.size()); - } - - @Test(enabled = true) - public void testRegular() { - final List obj = IndexedLists.of(3,4,5,6,7); - final byte[] serialized = serialize(_kryo, obj); - final List deserialized = deserialize(_kryo, serialized, List.class); - assertEquals(deserialized, obj); - } - - @Test(enabled = true) - public void testCopyOfIterable() { - final ArrayList iterable = new ArrayList(); - iterable.append(new Object()); - final List obj = IndexedLists.copyOf(iterable.asList()); - final byte[] serialized = serialize(_kryo, obj); - final List deserialized = deserialize(_kryo, serialized, List.class); - assertEquals(deserialized, obj); - } - - // Kryo#copy tests - - @Test(enabled = true) - public void testCopyEmpty() { - final List obj = IndexedLists.of(); - final List copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test(enabled = true) - public void testCopyRegular() { - final List obj = IndexedLists.of(2,3,4,5); - final List copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test(enabled = true) - public void testCopyCopyOfIterable() { - final ArrayList iterable = new ArrayList(); - iterable.append(new Object()); - final List obj = IndexedLists.copyOf(iterable.asList()); - List copied = _kryo.copy(obj); - assertSame(copied, obj); - } + private Kryo _kryo; + + @BeforeTest + public void setUp() throws Exception { + _kryo = new Kryo(); + + ListSerializer.registerSerializers(_kryo); + } + + @Test(enabled = true) + public void testEmpty() { + final List obj = IndexedLists.of(); + final byte[] serialized = serialize(_kryo, obj); + final List deserialized = deserialize(_kryo, serialized, List.class); + assertTrue(deserialized.isEmpty()); + assertEquals(deserialized.size(), obj.size()); + } + + @Test(enabled = true) + public void testRegular() { + final List obj = IndexedLists.of(3, 4, 5, 6, 7); + final byte[] serialized = serialize(_kryo, obj); + final List deserialized = deserialize(_kryo, serialized, List.class); + assertEquals(deserialized, obj); + } + + @Test(enabled = true) + public void testCopyOfIterable() { + final ArrayList iterable = new ArrayList(); + iterable.append(new Object()); + final List obj = IndexedLists.copyOf(iterable.asList()); + final byte[] serialized = serialize(_kryo, obj); + final List deserialized = deserialize(_kryo, serialized, List.class); + assertEquals(deserialized, obj); + } + + // Kryo#copy tests + + @Test(enabled = true) + public void testCopyEmpty() { + final List obj = IndexedLists.of(); + final List copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test(enabled = true) + public void testCopyRegular() { + final List obj = IndexedLists.of(2, 3, 4, 5); + final List copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test(enabled = true) + public void testCopyCopyOfIterable() { + final ArrayList iterable = new ArrayList(); + iterable.append(new Object()); + final List obj = IndexedLists.copyOf(iterable.asList()); + List copied = _kryo.copy(obj); + assertSame(copied, obj); + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/dexx/MapSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/dexx/MapSerializerTest.java index 72608128..0d635665 100644 --- a/src/test/java/de/javakaffee/kryoserializers/dexx/MapSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/dexx/MapSerializerTest.java @@ -1,61 +1,76 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.dexx; -import com.esotericsoftware.kryo.Kryo; +import static de.javakaffee.kryoserializers.KryoTest.deserialize; +import static de.javakaffee.kryoserializers.KryoTest.serialize; +import static org.testng.Assert.*; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.esotericsoftware.kryo.Kryo; import com.github.andrewoma.dexx.collection.Map; import com.github.andrewoma.dexx.collection.Maps; -import static de.javakaffee.kryoserializers.KryoTest.deserialize; -import static de.javakaffee.kryoserializers.KryoTest.serialize; -import static org.testng.Assert.*; - /** -* Test for {@link MapSerializer} + * Test for {@link MapSerializer} */ public class MapSerializerTest { - private Kryo _kryo; - - @BeforeTest - public void setUp() throws Exception { - _kryo = new Kryo(); - - MapSerializer.registerSerializers(_kryo); - } - - @Test(enabled = true) - public void testEmpty() { - final Map obj = Maps.of(); - final byte[] serialized = serialize(_kryo, obj); - final Map deserialized = deserialize(_kryo, serialized, Map.class); - assertTrue(deserialized.isEmpty()); - assertEquals(deserialized.size(), obj.size()); - } - - @Test(enabled = true) - public void testRegular() { - final Map obj = Maps.of(3, "k", 5, "r", 6, "y"); - final byte[] serialized = serialize(_kryo, obj); - final Map deserialized = deserialize(_kryo, serialized, Map.class); - assertEquals(deserialized, obj); - } - - // Kryo#copy tests - - @Test(enabled = true) - public void testCopyEmpty() { - final Map obj = Maps.of(); - final Map copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test(enabled = true) - public void testCopyRegular() { - final Map obj = Maps.of(1, 2, 3, 4); - final Map copied = _kryo.copy(obj); - assertSame(copied, obj); - } + private Kryo _kryo; + + @BeforeTest + public void setUp() throws Exception { + _kryo = new Kryo(); + + MapSerializer.registerSerializers(_kryo); + } + + @Test(enabled = true) + public void testEmpty() { + final Map obj = Maps.of(); + final byte[] serialized = serialize(_kryo, obj); + final Map deserialized = deserialize(_kryo, serialized, Map.class); + assertTrue(deserialized.isEmpty()); + assertEquals(deserialized.size(), obj.size()); + } + + @Test(enabled = true) + public void testRegular() { + final Map obj = Maps.of(3, "k", 5, "r", 6, "y"); + final byte[] serialized = serialize(_kryo, obj); + final Map deserialized = deserialize(_kryo, serialized, Map.class); + assertEquals(deserialized, obj); + } + + // Kryo#copy tests + + @Test(enabled = true) + public void testCopyEmpty() { + final Map obj = Maps.of(); + final Map copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test(enabled = true) + public void testCopyRegular() { + final Map obj = Maps.of(1, 2, 3, 4); + final Map copied = _kryo.copy(obj); + assertSame(copied, obj); + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/dexx/SetSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/dexx/SetSerializerTest.java index 7c47d79b..8d2f4be5 100644 --- a/src/test/java/de/javakaffee/kryoserializers/dexx/SetSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/dexx/SetSerializerTest.java @@ -1,14 +1,29 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.dexx; -import com.esotericsoftware.kryo.Kryo; +import static de.javakaffee.kryoserializers.KryoTest.deserialize; +import static de.javakaffee.kryoserializers.KryoTest.serialize; import static org.testng.Assert.*; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; -import static de.javakaffee.kryoserializers.KryoTest.deserialize; -import static de.javakaffee.kryoserializers.KryoTest.serialize; - +import com.esotericsoftware.kryo.Kryo; import com.github.andrewoma.dexx.collection.Set; import com.github.andrewoma.dexx.collection.Sets; @@ -17,45 +32,45 @@ */ public class SetSerializerTest { - private Kryo _kryo; - - @BeforeTest - public void setUp() throws Exception { - _kryo = new Kryo(); - - SetSerializer.registerSerializers(_kryo); - } - - @Test(enabled = true) - public void testEmpty() { - final Set obj = Sets.of(); - final byte[] serialized = serialize( _kryo, obj ); - final Set deserialized = deserialize(_kryo, serialized, Set.class); - assertTrue(deserialized.isEmpty()); - assertEquals(deserialized.size(), obj.size()); - } - - @Test(enabled = true) - public void testRegular() { - final Set obj = Sets.of(3, 4, 5, 6); - final byte[] serialized = serialize( _kryo, obj ); - final Set deserialized = deserialize(_kryo, serialized, Set.class); - assertEquals(deserialized, obj); - } - - // Kryo#copy tests - - @Test(enabled = true) - public void testCopyEmpty() { - final Set obj = Sets.of(); - final Set copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test(enabled = true) - public void testCopyRegular() { - final Set obj = Sets.of(1, 2, 3); - final Set copied = _kryo.copy(obj); - assertSame(copied, obj); - } + private Kryo _kryo; + + @BeforeTest + public void setUp() throws Exception { + _kryo = new Kryo(); + + SetSerializer.registerSerializers(_kryo); + } + + @Test(enabled = true) + public void testEmpty() { + final Set obj = Sets.of(); + final byte[] serialized = serialize(_kryo, obj); + final Set deserialized = deserialize(_kryo, serialized, Set.class); + assertTrue(deserialized.isEmpty()); + assertEquals(deserialized.size(), obj.size()); + } + + @Test(enabled = true) + public void testRegular() { + final Set obj = Sets.of(3, 4, 5, 6); + final byte[] serialized = serialize(_kryo, obj); + final Set deserialized = deserialize(_kryo, serialized, Set.class); + assertEquals(deserialized, obj); + } + + // Kryo#copy tests + + @Test(enabled = true) + public void testCopyEmpty() { + final Set obj = Sets.of(); + final Set copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test(enabled = true) + public void testCopyRegular() { + final Set obj = Sets.of(1, 2, 3); + final Set copied = _kryo.copy(obj); + assertSame(copied, obj); + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/guava/ArrayListMultimapSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/guava/ArrayListMultimapSerializerTest.java index c8a2a597..8e3882f0 100644 --- a/src/test/java/de/javakaffee/kryoserializers/guava/ArrayListMultimapSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/guava/ArrayListMultimapSerializerTest.java @@ -1,30 +1,46 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; -import de.javakaffee.kryoserializers.KryoTest; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import com.esotericsoftware.kryo.Kryo; - import com.google.common.collect.ArrayListMultimap; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; +import de.javakaffee.kryoserializers.KryoTest; public class ArrayListMultimapSerializerTest extends MultimapSerializerTestBase { - private Kryo _kryo; - - @BeforeClass - public void initializeKyroWithSerializer() { - _kryo = new Kryo(); - ArrayListMultimapSerializer.registerSerializers(_kryo); - } - - @Test(dataProvider = "Google Guava multimaps") - public void testMultimap(Object[] contents) { - final ArrayListMultimap multimap = ArrayListMultimap.create(); - populateMultimap(multimap, contents); - final byte[] serialized = KryoTest.serialize(_kryo, multimap); - final ArrayListMultimap deserialized = KryoTest.deserialize(_kryo, serialized, ArrayListMultimap.class); - assertEqualMultimaps(false, true, deserialized, multimap); - } + private Kryo _kryo; + + @BeforeClass + public void initializeKyroWithSerializer() { + _kryo = new Kryo(); + ArrayListMultimapSerializer.registerSerializers(_kryo); + } + + @Test(dataProvider = "Google Guava multimaps") + public void testMultimap(Object[] contents) { + final ArrayListMultimap multimap = ArrayListMultimap.create(); + populateMultimap(multimap, contents); + final byte[] serialized = KryoTest.serialize(_kryo, multimap); + final ArrayListMultimap deserialized = + KryoTest.deserialize(_kryo, serialized, ArrayListMultimap.class); + assertEqualMultimaps(false, true, deserialized, multimap); + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/guava/HashMultimapSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/guava/HashMultimapSerializerTest.java index 215d3977..01e7051e 100644 --- a/src/test/java/de/javakaffee/kryoserializers/guava/HashMultimapSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/guava/HashMultimapSerializerTest.java @@ -1,30 +1,45 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; -import de.javakaffee.kryoserializers.KryoTest; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import com.esotericsoftware.kryo.Kryo; - import com.google.common.collect.HashMultimap; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; +import de.javakaffee.kryoserializers.KryoTest; public class HashMultimapSerializerTest extends MultimapSerializerTestBase { - private Kryo _kryo; - - @BeforeClass - public void initializeKyroWithSerializer() { - _kryo = new Kryo(); - HashMultimapSerializer.registerSerializers(_kryo); - } - - @Test(dataProvider = "Google Guava multimaps") - public void testMultimap(Object[] contents) { - final HashMultimap multimap = HashMultimap.create(); - populateMultimap(multimap, contents); - final byte[] serialized = KryoTest.serialize(_kryo, multimap); - final HashMultimap deserialized = KryoTest.deserialize(_kryo, serialized, HashMultimap.class); - assertEqualMultimaps(false, false, deserialized, multimap); - } + private Kryo _kryo; + + @BeforeClass + public void initializeKyroWithSerializer() { + _kryo = new Kryo(); + HashMultimapSerializer.registerSerializers(_kryo); + } + + @Test(dataProvider = "Google Guava multimaps") + public void testMultimap(Object[] contents) { + final HashMultimap multimap = HashMultimap.create(); + populateMultimap(multimap, contents); + final byte[] serialized = KryoTest.serialize(_kryo, multimap); + final HashMultimap deserialized = KryoTest.deserialize(_kryo, serialized, HashMultimap.class); + assertEqualMultimaps(false, false, deserialized, multimap); + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableListSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableListSerializerTest.java index fceb3801..1ec7996d 100644 --- a/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableListSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableListSerializerTest.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; import static de.javakaffee.kryoserializers.KryoTest.deserialize; @@ -8,140 +24,135 @@ import org.testng.annotations.Test; import com.esotericsoftware.kryo.Kryo; -import com.google.common.collect.HashBasedTable; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableTable; -import com.google.common.collect.Lists; -import com.google.common.collect.Table; - +import com.google.common.collect.*; /** * Test for {@link ImmutableListSerializer}. */ public class ImmutableListSerializerTest { - private Kryo _kryo; - - @BeforeTest - public void setUp() throws Exception { - _kryo = new Kryo(); - - ImmutableListSerializer.registerSerializers(_kryo); - } - - @Test( enabled = true ) - public void testEmpty() { - final ImmutableList obj = ImmutableList.of(); - final byte[] serialized = serialize( _kryo, obj ); - final ImmutableList deserialized = deserialize(_kryo, serialized, ImmutableList.class); - assertTrue(deserialized.isEmpty()); - assertEquals(deserialized.size(), obj.size()); - } - - @Test( enabled = true ) - public void testSingleton() { - final ImmutableList obj = ImmutableList.of(3); - final byte[] serialized = serialize( _kryo, obj ); - final ImmutableList deserialized = deserialize(_kryo, serialized, ImmutableList.class); - assertEquals(deserialized, obj); - } - - @Test( enabled = true ) - public void testRegular() { - final ImmutableList obj = ImmutableList.of(3, 4, 5, 6); - final byte[] serialized = serialize( _kryo, obj ); - final ImmutableList deserialized = deserialize(_kryo, serialized, ImmutableList.class); - assertEquals(deserialized, obj); - } - - @Test( enabled = true ) - public void testSubList() { - final ImmutableList obj = ImmutableList.of(3, 4, 5, 6).subList(1, 3); - final byte[] serialized = serialize( _kryo, obj ); - final ImmutableList deserialized = deserialize(_kryo, serialized, ImmutableList.class); - assertEquals(deserialized, obj); - } - - @Test( enabled = true ) - public void testReverse() { - final ImmutableList obj = ImmutableList.of(3,4,5).reverse(); - final byte[] serialized = serialize( _kryo, obj ); - final ImmutableList deserialized = deserialize(_kryo, serialized, ImmutableList.class); - assertEquals(deserialized, obj); - } - - @Test( enabled = true ) - public void testStringAsImmutableList() { - final ImmutableList obj = Lists.charactersOf("KryoRocks"); - final byte[] serialized = serialize( _kryo, obj ); - final ImmutableList deserialized = deserialize(_kryo, serialized, ImmutableList.class); - assertEquals(deserialized, obj); - } - - @Test( enabled = true ) - public void testValues() { - Table baseTable = HashBasedTable.create(); - baseTable.put(1, 2, 3); - baseTable.put(4, 5, 6); - Table table = ImmutableTable.copyOf(baseTable); - final ImmutableList obj = (ImmutableList) table.values(); - final byte[] serialized = serialize( _kryo, obj ); - final ImmutableList deserialized = deserialize(_kryo, serialized, ImmutableList.class); - assertEquals(deserialized, obj); - } - - // Kryo#copy tests - - @Test( enabled = true ) - public void testCopyEmpty() { - final ImmutableList obj = ImmutableList.of(); - final ImmutableList copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test( enabled = true ) - public void testCopySingleton() { - final ImmutableList obj = ImmutableList.of(1); - final ImmutableList copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test( enabled = true ) - public void testCopyRegular() { - final ImmutableList obj = ImmutableList.of(1, 2, 3); - final ImmutableList copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test( enabled = true ) - public void testCopySubList() { - final ImmutableList obj = ImmutableList.of(1, 2, 3, 4).subList(1, 3); - final ImmutableList copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test( enabled = true ) - public void testCopyReverse() { - final ImmutableList obj = ImmutableList.of(1,2,3).reverse(); - final ImmutableList copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test( enabled = true ) - public void testCopyStringAsImmutableList() { - final ImmutableList obj = Lists.charactersOf("KryoRocks"); - final ImmutableList copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test( enabled = true ) - public void testCopyValues() { - Table baseTable = HashBasedTable.create(); - baseTable.put(1, 2, 3); - baseTable.put(4, 5, 6); - Table table = ImmutableTable.copyOf(baseTable); - final ImmutableList obj = (ImmutableList) table.values(); - final ImmutableList copied = _kryo.copy(obj); - assertSame(copied, obj); - } + private Kryo _kryo; + + @BeforeTest + public void setUp() throws Exception { + _kryo = new Kryo(); + + ImmutableListSerializer.registerSerializers(_kryo); + } + + @Test(enabled = true) + public void testEmpty() { + final ImmutableList obj = ImmutableList.of(); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableList deserialized = deserialize(_kryo, serialized, ImmutableList.class); + assertTrue(deserialized.isEmpty()); + assertEquals(deserialized.size(), obj.size()); + } + + @Test(enabled = true) + public void testSingleton() { + final ImmutableList obj = ImmutableList.of(3); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableList deserialized = deserialize(_kryo, serialized, ImmutableList.class); + assertEquals(deserialized, obj); + } + + @Test(enabled = true) + public void testRegular() { + final ImmutableList obj = ImmutableList.of(3, 4, 5, 6); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableList deserialized = deserialize(_kryo, serialized, ImmutableList.class); + assertEquals(deserialized, obj); + } + + @Test(enabled = true) + public void testSubList() { + final ImmutableList obj = ImmutableList.of(3, 4, 5, 6).subList(1, 3); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableList deserialized = deserialize(_kryo, serialized, ImmutableList.class); + assertEquals(deserialized, obj); + } + + @Test(enabled = true) + public void testReverse() { + final ImmutableList obj = ImmutableList.of(3, 4, 5).reverse(); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableList deserialized = deserialize(_kryo, serialized, ImmutableList.class); + assertEquals(deserialized, obj); + } + + @Test(enabled = true) + public void testStringAsImmutableList() { + final ImmutableList obj = Lists.charactersOf("KryoRocks"); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableList deserialized = deserialize(_kryo, serialized, ImmutableList.class); + assertEquals(deserialized, obj); + } + + @Test(enabled = true) + public void testValues() { + Table baseTable = HashBasedTable.create(); + baseTable.put(1, 2, 3); + baseTable.put(4, 5, 6); + Table table = ImmutableTable.copyOf(baseTable); + final ImmutableList obj = (ImmutableList) table.values(); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableList deserialized = deserialize(_kryo, serialized, ImmutableList.class); + assertEquals(deserialized, obj); + } + + // Kryo#copy tests + + @Test(enabled = true) + public void testCopyEmpty() { + final ImmutableList obj = ImmutableList.of(); + final ImmutableList copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test(enabled = true) + public void testCopySingleton() { + final ImmutableList obj = ImmutableList.of(1); + final ImmutableList copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test(enabled = true) + public void testCopyRegular() { + final ImmutableList obj = ImmutableList.of(1, 2, 3); + final ImmutableList copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test(enabled = true) + public void testCopySubList() { + final ImmutableList obj = ImmutableList.of(1, 2, 3, 4).subList(1, 3); + final ImmutableList copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test(enabled = true) + public void testCopyReverse() { + final ImmutableList obj = ImmutableList.of(1, 2, 3).reverse(); + final ImmutableList copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test(enabled = true) + public void testCopyStringAsImmutableList() { + final ImmutableList obj = Lists.charactersOf("KryoRocks"); + final ImmutableList copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test(enabled = true) + public void testCopyValues() { + Table baseTable = HashBasedTable.create(); + baseTable.put(1, 2, 3); + baseTable.put(4, 5, 6); + Table table = ImmutableTable.copyOf(baseTable); + final ImmutableList obj = (ImmutableList) table.values(); + final ImmutableList copied = _kryo.copy(obj); + assertSame(copied, obj); + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableMapSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableMapSerializerTest.java index 282d3d78..1db57e8b 100644 --- a/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableMapSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableMapSerializerTest.java @@ -1,94 +1,113 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; -import com.esotericsoftware.kryo.Kryo; -import com.google.common.collect.ImmutableMap; +import static de.javakaffee.kryoserializers.KryoTest.deserialize; +import static de.javakaffee.kryoserializers.KryoTest.serialize; import static org.testng.Assert.*; +import java.util.EnumMap; + import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; -import java.util.EnumMap; - -import static de.javakaffee.kryoserializers.KryoTest.deserialize; -import static de.javakaffee.kryoserializers.KryoTest.serialize; +import com.esotericsoftware.kryo.Kryo; +import com.google.common.collect.ImmutableMap; /** * Created by pmarcos on 29/06/15. */ public class ImmutableMapSerializerTest { - private enum Planet { - MERCURY, VENUS, EARTH, MARS; - } - - private Kryo _kryo; - - @BeforeTest - public void setUp() throws Exception { - _kryo = new Kryo(); - - ImmutableMapSerializer.registerSerializers(_kryo); - } - - @Test - public void testEmpty() { - final ImmutableMap obj = ImmutableMap.of(); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableMap deserialized = deserialize(_kryo, serialized, ImmutableMap.class); - assertTrue(deserialized.isEmpty()); - assertEquals(deserialized.size(), obj.size()); - } - - @Test - public void testSingleton() { - final ImmutableMap obj = ImmutableMap.of(3, "k"); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableMap deserialized = deserialize(_kryo, serialized, ImmutableMap.class); - assertEquals(deserialized, obj); - } - - @Test - public void testRegular() { - final ImmutableMap obj = ImmutableMap.of(3, "k", 5, "r", 6, "y"); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableMap deserialized = deserialize(_kryo, serialized, ImmutableMap.class); - assertEquals(deserialized, obj); - } - - @Test - public void testEnum() { - final EnumMap obj = new EnumMap(Planet.class); - for (Planet p : Planet.values()) { - obj.put(p, p.name()); - } - - final ImmutableMap immutableObj = ImmutableMap.copyOf(obj); - final byte[] serialized = serialize(_kryo, immutableObj); - final ImmutableMap deserialized = deserialize(_kryo, serialized, ImmutableMap.class); - assertEquals(deserialized, immutableObj); - } - - // Kryo#copy tests - - @Test - public void testCopyEmpty() { - final ImmutableMap obj = ImmutableMap.of(); - final ImmutableMap copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test - public void testCopySingleton() { - final ImmutableMap obj = ImmutableMap.of(1, 1); - final ImmutableMap copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test - public void testCopyRegular() { - final ImmutableMap obj = ImmutableMap.of(1, 2, 3, 4); - final ImmutableMap copied = _kryo.copy(obj); - assertSame(copied, obj); - } - -} \ No newline at end of file + private Kryo _kryo; + + @BeforeTest + public void setUp() throws Exception { + _kryo = new Kryo(); + + ImmutableMapSerializer.registerSerializers(_kryo); + } + + @Test + public void testEmpty() { + final ImmutableMap obj = ImmutableMap.of(); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableMap deserialized = deserialize(_kryo, serialized, ImmutableMap.class); + assertTrue(deserialized.isEmpty()); + assertEquals(deserialized.size(), obj.size()); + } + + @Test + public void testSingleton() { + final ImmutableMap obj = ImmutableMap.of(3, "k"); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableMap deserialized = deserialize(_kryo, serialized, ImmutableMap.class); + assertEquals(deserialized, obj); + } + + @Test + public void testRegular() { + final ImmutableMap obj = ImmutableMap.of(3, "k", 5, "r", 6, "y"); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableMap deserialized = deserialize(_kryo, serialized, ImmutableMap.class); + assertEquals(deserialized, obj); + } + + @Test + public void testEnum() { + final EnumMap obj = new EnumMap(Planet.class); + for (Planet p : Planet.values()) { + obj.put(p, p.name()); + } + + final ImmutableMap immutableObj = ImmutableMap.copyOf(obj); + final byte[] serialized = serialize(_kryo, immutableObj); + final ImmutableMap deserialized = deserialize(_kryo, serialized, ImmutableMap.class); + assertEquals(deserialized, immutableObj); + } + + @Test + public void testCopyEmpty() { + final ImmutableMap obj = ImmutableMap.of(); + final ImmutableMap copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + // Kryo#copy tests + + @Test + public void testCopySingleton() { + final ImmutableMap obj = ImmutableMap.of(1, 1); + final ImmutableMap copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test + public void testCopyRegular() { + final ImmutableMap obj = ImmutableMap.of(1, 2, 3, 4); + final ImmutableMap copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + private enum Planet { + MERCURY, + VENUS, + EARTH, + MARS; + } + +} diff --git a/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableMultimapSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableMultimapSerializerTest.java index 2612e94f..e0432e8e 100644 --- a/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableMultimapSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableMultimapSerializerTest.java @@ -1,208 +1,223 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; -import com.esotericsoftware.kryo.Kryo; -import com.google.common.collect.ImmutableListMultimap; -import com.google.common.collect.ImmutableMultimap; - +import static de.javakaffee.kryoserializers.KryoTest.deserialize; +import static de.javakaffee.kryoserializers.KryoTest.serialize; import static org.testng.Assert.*; -import com.google.common.collect.ImmutableSetMultimap; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; -import static de.javakaffee.kryoserializers.KryoTest.deserialize; -import static de.javakaffee.kryoserializers.KryoTest.serialize; +import com.esotericsoftware.kryo.Kryo; +import com.google.common.collect.ImmutableListMultimap; +import com.google.common.collect.ImmutableMultimap; +import com.google.common.collect.ImmutableSetMultimap; public class ImmutableMultimapSerializerTest { - private Kryo _kryo; - - @BeforeTest - public void setUp() throws Exception { - _kryo = new Kryo(); - - ImmutableMultimapSerializer.registerSerializers(_kryo); - } - - @Test - public void testRegularEmpty() { - final ImmutableMultimap obj = ImmutableMultimap.of(); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableMultimap.class); - assertTrue(deserialized.isEmpty()); - assertEquals(deserialized, obj); - } - - @Test - public void testImmutableListMultimapEmpty() { - final ImmutableMultimap obj = ImmutableListMultimap.of(); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableListMultimap.class); - assertTrue(deserialized.isEmpty()); - assertEquals(deserialized, obj); - } - - @Test - public void testImmutableSetMultimapEmpty() { - final ImmutableMultimap obj = ImmutableSetMultimap.of(); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableSetMultimap.class); - assertTrue(deserialized.isEmpty()); - assertEquals(deserialized, obj); - } - - @Test - public void testRegularSingleton() { - final ImmutableMultimap obj = ImmutableMultimap.of(3, "k"); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableMultimap.class); - assertEquals(deserialized, obj); - } - - @Test - public void testImmutableListMultimapSingleton() { - final ImmutableMultimap obj = ImmutableListMultimap.of(3, "k"); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableListMultimap.class); - assertEquals(deserialized, obj); - } - - @Test - public void testImmutableSetMultimapSingleton() { - final ImmutableMultimap obj = ImmutableSetMultimap.of(3, "k"); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableSetMultimap.class); - assertEquals(deserialized.getClass(), obj.getClass()); - assertEquals(deserialized, obj); - } - - @Test - public void testRegular() { - final ImmutableMultimap obj = ImmutableMultimap.of(3, "k", 5, "r", 6, "y"); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableMultimap.class); - assertEquals(deserialized, obj); - } - - @Test - public void testImmutableListMultimap() { - final ImmutableMultimap obj = ImmutableListMultimap.of(3, "k", 5, "r", 6, "y"); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableListMultimap.class); - assertEquals(deserialized, obj); - } - - @Test - public void testImmutableSetMultimap() { - final ImmutableMultimap obj = ImmutableSetMultimap.of(3, "k", 5, "r", 6, "y"); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableSetMultimap.class); - assertEquals(deserialized.getClass(), obj.getClass()); - assertEquals(deserialized, obj); - } - - @Test - public void testRegularMultipleElementsPerKey() { - final ImmutableMultimap obj = ImmutableMultimap.of(3, "k", 3, "r", 4, "y", 4, "o"); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableMultimap.class); - assertEquals(deserialized, obj); - } - - @Test - public void testImmutableListMultimapMultipleElementsPerKey() { - final ImmutableMultimap obj = ImmutableListMultimap.of(3, "k", 3, "r", 4, "y", 4, "o"); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableListMultimap.class); - assertEquals(deserialized, obj); - } - - @Test - public void testImmutableSetMultimapMultipleElementsPerKey() { - final ImmutableMultimap obj = ImmutableSetMultimap.of(3, "k", 3, "r", 4, "y", 4, "o"); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableSetMultimap.class); - assertEquals(deserialized, obj); - } - - @Test - public void testImmutableMapSerializerAlreadyRegistered() { - ImmutableMapSerializer.registerSerializers(_kryo); - final ImmutableMultimap obj = ImmutableMultimap.of(); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableMultimap.class); - assertTrue(deserialized.isEmpty()); - assertEquals(deserialized, obj); - } - - @Test - public void testImmutableListSerializerAlreadyRegistered() { - ImmutableListSerializer.registerSerializers(_kryo); - final ImmutableMultimap obj = ImmutableListMultimap.of(); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableListMultimap.class); - assertTrue(deserialized.isEmpty()); - assertEquals(deserialized, obj); - } - - @Test - public void testImmutableSetSerializerAlreadyRegistered() { - ImmutableSetSerializer.registerSerializers(_kryo); - final ImmutableMultimap obj = ImmutableSetMultimap.of(); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableSetMultimap.class); - assertTrue(deserialized.isEmpty()); - assertEquals(deserialized, obj); - } - - // Kryo#copy tests - - @Test - public void testCopyEmpty() { - final ImmutableMultimap obj = ImmutableMultimap.of(); - final ImmutableMultimap copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test - public void testCopySingleton() { - final ImmutableMultimap obj = ImmutableMultimap.of(1, "k"); - final ImmutableMultimap copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test - public void testCopyRegular() { - final ImmutableMultimap obj = ImmutableMultimap.of(1, "k", 2, "r", 3, "y"); - final ImmutableMultimap copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test - public void testCopyImmutableListMultimap() { - final ImmutableMultimap obj = ImmutableListMultimap.of(1, "k", 2, "r", 3, "y"); - final ImmutableMultimap copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test - public void testCopyImmutableListMultimapEmpty() { - final ImmutableMultimap obj = ImmutableListMultimap.of(); - final ImmutableMultimap copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test - public void testCopyImmutableSetMultimap() { - final ImmutableMultimap obj = ImmutableSetMultimap.of(1, "k", 2, "r", 3, "y"); - final ImmutableMultimap copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test - public void testCopyImmutableSetMultimapEmpty() { - final ImmutableMultimap obj = ImmutableSetMultimap.of(); - final ImmutableMultimap copied = _kryo.copy(obj); - assertSame(copied, obj); - } -} \ No newline at end of file + private Kryo _kryo; + + @BeforeTest + public void setUp() throws Exception { + _kryo = new Kryo(); + + ImmutableMultimapSerializer.registerSerializers(_kryo); + } + + @Test + public void testRegularEmpty() { + final ImmutableMultimap obj = ImmutableMultimap.of(); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableMultimap.class); + assertTrue(deserialized.isEmpty()); + assertEquals(deserialized, obj); + } + + @Test + public void testImmutableListMultimapEmpty() { + final ImmutableMultimap obj = ImmutableListMultimap.of(); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableListMultimap.class); + assertTrue(deserialized.isEmpty()); + assertEquals(deserialized, obj); + } + + @Test + public void testImmutableSetMultimapEmpty() { + final ImmutableMultimap obj = ImmutableSetMultimap.of(); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableSetMultimap.class); + assertTrue(deserialized.isEmpty()); + assertEquals(deserialized, obj); + } + + @Test + public void testRegularSingleton() { + final ImmutableMultimap obj = ImmutableMultimap.of(3, "k"); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableMultimap.class); + assertEquals(deserialized, obj); + } + + @Test + public void testImmutableListMultimapSingleton() { + final ImmutableMultimap obj = ImmutableListMultimap.of(3, "k"); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableListMultimap.class); + assertEquals(deserialized, obj); + } + + @Test + public void testImmutableSetMultimapSingleton() { + final ImmutableMultimap obj = ImmutableSetMultimap.of(3, "k"); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableSetMultimap.class); + assertEquals(deserialized.getClass(), obj.getClass()); + assertEquals(deserialized, obj); + } + + @Test + public void testRegular() { + final ImmutableMultimap obj = ImmutableMultimap.of(3, "k", 5, "r", 6, "y"); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableMultimap.class); + assertEquals(deserialized, obj); + } + + @Test + public void testImmutableListMultimap() { + final ImmutableMultimap obj = ImmutableListMultimap.of(3, "k", 5, "r", 6, "y"); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableListMultimap.class); + assertEquals(deserialized, obj); + } + + @Test + public void testImmutableSetMultimap() { + final ImmutableMultimap obj = ImmutableSetMultimap.of(3, "k", 5, "r", 6, "y"); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableSetMultimap.class); + assertEquals(deserialized.getClass(), obj.getClass()); + assertEquals(deserialized, obj); + } + + @Test + public void testRegularMultipleElementsPerKey() { + final ImmutableMultimap obj = ImmutableMultimap.of(3, "k", 3, "r", 4, "y", 4, "o"); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableMultimap.class); + assertEquals(deserialized, obj); + } + + @Test + public void testImmutableListMultimapMultipleElementsPerKey() { + final ImmutableMultimap obj = ImmutableListMultimap.of(3, "k", 3, "r", 4, "y", 4, "o"); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableListMultimap.class); + assertEquals(deserialized, obj); + } + + @Test + public void testImmutableSetMultimapMultipleElementsPerKey() { + final ImmutableMultimap obj = ImmutableSetMultimap.of(3, "k", 3, "r", 4, "y", 4, "o"); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableSetMultimap.class); + assertEquals(deserialized, obj); + } + + @Test + public void testImmutableMapSerializerAlreadyRegistered() { + ImmutableMapSerializer.registerSerializers(_kryo); + final ImmutableMultimap obj = ImmutableMultimap.of(); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableMultimap.class); + assertTrue(deserialized.isEmpty()); + assertEquals(deserialized, obj); + } + + @Test + public void testImmutableListSerializerAlreadyRegistered() { + ImmutableListSerializer.registerSerializers(_kryo); + final ImmutableMultimap obj = ImmutableListMultimap.of(); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableListMultimap.class); + assertTrue(deserialized.isEmpty()); + assertEquals(deserialized, obj); + } + + @Test + public void testImmutableSetSerializerAlreadyRegistered() { + ImmutableSetSerializer.registerSerializers(_kryo); + final ImmutableMultimap obj = ImmutableSetMultimap.of(); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableMultimap deserialized = deserialize(_kryo, serialized, ImmutableSetMultimap.class); + assertTrue(deserialized.isEmpty()); + assertEquals(deserialized, obj); + } + + // Kryo#copy tests + + @Test + public void testCopyEmpty() { + final ImmutableMultimap obj = ImmutableMultimap.of(); + final ImmutableMultimap copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test + public void testCopySingleton() { + final ImmutableMultimap obj = ImmutableMultimap.of(1, "k"); + final ImmutableMultimap copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test + public void testCopyRegular() { + final ImmutableMultimap obj = ImmutableMultimap.of(1, "k", 2, "r", 3, "y"); + final ImmutableMultimap copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test + public void testCopyImmutableListMultimap() { + final ImmutableMultimap obj = ImmutableListMultimap.of(1, "k", 2, "r", 3, "y"); + final ImmutableMultimap copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test + public void testCopyImmutableListMultimapEmpty() { + final ImmutableMultimap obj = ImmutableListMultimap.of(); + final ImmutableMultimap copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test + public void testCopyImmutableSetMultimap() { + final ImmutableMultimap obj = ImmutableSetMultimap.of(1, "k", 2, "r", 3, "y"); + final ImmutableMultimap copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test + public void testCopyImmutableSetMultimapEmpty() { + final ImmutableMultimap obj = ImmutableSetMultimap.of(); + final ImmutableMultimap copied = _kryo.copy(obj); + assertSame(copied, obj); + } +} diff --git a/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableSetSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableSetSerializerTest.java index 07c23f0e..d64314ab 100644 --- a/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableSetSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableSetSerializerTest.java @@ -1,85 +1,99 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; -import com.esotericsoftware.kryo.Kryo; -import com.google.common.collect.*; +import static de.javakaffee.kryoserializers.KryoTest.deserialize; +import static de.javakaffee.kryoserializers.KryoTest.serialize; import static org.testng.Assert.*; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; -import static de.javakaffee.kryoserializers.KryoTest.deserialize; -import static de.javakaffee.kryoserializers.KryoTest.serialize; +import com.esotericsoftware.kryo.Kryo; +import com.google.common.collect.ImmutableSet; /** * Test for {@link ImmutableSetSerializer}. */ public class ImmutableSetSerializerTest { - private Kryo _kryo; - - @BeforeTest - public void setUp() throws Exception { - _kryo = new Kryo(); - - ImmutableSetSerializer.registerSerializers(_kryo); - } - - @Test - public void testEmpty() { - final ImmutableSet obj = ImmutableSet.of(); - final byte[] serialized = serialize( _kryo, obj ); - final ImmutableSet deserialized = deserialize(_kryo, serialized, ImmutableSet.class); - assertTrue(deserialized.isEmpty()); - assertEquals(deserialized.size(), obj.size()); - } - - @Test - public void testSingleton() { - final ImmutableSet obj = ImmutableSet.of(3); - final byte[] serialized = serialize( _kryo, obj ); - final ImmutableSet deserialized = deserialize(_kryo, serialized, ImmutableSet.class); - assertEquals(deserialized, obj); - } - - @Test - public void testRegular() { - final ImmutableSet obj = ImmutableSet.of(3, 4, 5, 6); - final byte[] serialized = serialize( _kryo, obj ); - final ImmutableSet deserialized = deserialize(_kryo, serialized, ImmutableSet.class); - assertEquals(deserialized, obj); - } - - @Test - public void testStringAsImmutableSet() { - final ImmutableSet obj = ImmutableSet.of("K","r", "y", "o"); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableSet deserialized = deserialize(_kryo, serialized, ImmutableSet.class); - assertEquals(deserialized, obj); - } - - // Kryo#copy tests - - @Test - public void testCopyEmpty() { - final ImmutableSet obj = ImmutableSet.of(); - final ImmutableSet copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test - public void testCopySingleton() { - final ImmutableSet obj = ImmutableSet.of(1); - final ImmutableSet copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test - public void testCopyRegular() { - final ImmutableSet obj = ImmutableSet.of(1, 2, 3); - final ImmutableSet copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - - -} \ No newline at end of file + private Kryo _kryo; + + @BeforeTest + public void setUp() throws Exception { + _kryo = new Kryo(); + + ImmutableSetSerializer.registerSerializers(_kryo); + } + + @Test + public void testEmpty() { + final ImmutableSet obj = ImmutableSet.of(); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableSet deserialized = deserialize(_kryo, serialized, ImmutableSet.class); + assertTrue(deserialized.isEmpty()); + assertEquals(deserialized.size(), obj.size()); + } + + @Test + public void testSingleton() { + final ImmutableSet obj = ImmutableSet.of(3); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableSet deserialized = deserialize(_kryo, serialized, ImmutableSet.class); + assertEquals(deserialized, obj); + } + + @Test + public void testRegular() { + final ImmutableSet obj = ImmutableSet.of(3, 4, 5, 6); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableSet deserialized = deserialize(_kryo, serialized, ImmutableSet.class); + assertEquals(deserialized, obj); + } + + @Test + public void testStringAsImmutableSet() { + final ImmutableSet obj = ImmutableSet.of("K", "r", "y", "o"); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableSet deserialized = deserialize(_kryo, serialized, ImmutableSet.class); + assertEquals(deserialized, obj); + } + + // Kryo#copy tests + + @Test + public void testCopyEmpty() { + final ImmutableSet obj = ImmutableSet.of(); + final ImmutableSet copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test + public void testCopySingleton() { + final ImmutableSet obj = ImmutableSet.of(1); + final ImmutableSet copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test + public void testCopyRegular() { + final ImmutableSet obj = ImmutableSet.of(1, 2, 3); + final ImmutableSet copied = _kryo.copy(obj); + assertSame(copied, obj); + } + +} diff --git a/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableSortedMapSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableSortedMapSerializerTest.java index 98ba60bd..be2288bf 100644 --- a/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableSortedMapSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableSortedMapSerializerTest.java @@ -1,100 +1,117 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; -import com.esotericsoftware.kryo.Kryo; -import com.google.common.collect.ImmutableSortedMap; -import com.google.common.collect.ImmutableSortedMap; -import com.google.common.collect.ImmutableSortedSet; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import java.util.EnumMap; - import static de.javakaffee.kryoserializers.KryoTest.deserialize; import static de.javakaffee.kryoserializers.KryoTest.serialize; import static org.testng.Assert.*; +import java.util.EnumMap; + +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; + +import com.esotericsoftware.kryo.Kryo; +import com.google.common.collect.ImmutableSortedMap; + public class ImmutableSortedMapSerializerTest { - private enum Planet { - MERCURY, VENUS, EARTH, MARS; - } - - private Kryo _kryo; - - @BeforeTest - public void setUp() throws Exception { - _kryo = new Kryo(); - ImmutableSortedMapSerializer.registerSerializers(_kryo); - } - - @Test - public void testEmpty() { - final ImmutableSortedMap obj = ImmutableSortedMap.of(); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableSortedMap deserialized = deserialize(_kryo, serialized, ImmutableSortedMap.class); - assertTrue(deserialized.isEmpty()); - assertEquals(deserialized.size(), obj.size()); - } - - @Test - public void testSingleton() { - final ImmutableSortedMap obj = ImmutableSortedMap.of(3, "k"); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableSortedMap deserialized = deserialize(_kryo, serialized, ImmutableSortedMap.class); - assertEquals(deserialized, obj); - } - - @Test - public void testRegular() { - final ImmutableSortedMap obj = ImmutableSortedMap.of(5, "r", 3, "k", 6, "y"); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableSortedMap deserialized = deserialize(_kryo, serialized, ImmutableSortedMap.class); - assertEquals(deserialized, obj); - } - - - @Test - public void testDescending() { - final ImmutableSortedMap obj = ImmutableSortedMap.of(1, "a", 5, "e", 3, "c").descendingMap(); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableSortedMap deserialized = deserialize(_kryo, serialized, ImmutableSortedMap.class); - assertEquals(deserialized, obj); - } - - @Test - public void testEnum() { - final EnumMap obj = new EnumMap(Planet.class); - for (Planet p : Planet.values()) { - obj.put(p, p.name()); - } - - final ImmutableSortedMap immutableObj = ImmutableSortedMap.copyOf(obj); - final byte[] serialized = serialize(_kryo, immutableObj); - final ImmutableSortedMap deserialized = deserialize(_kryo, serialized, ImmutableSortedMap.class); - assertEquals(deserialized, immutableObj); - } - - // Kryo#copy tests - - @Test - public void testCopyEmpty() { - final ImmutableSortedMap obj = ImmutableSortedMap.of(); - final ImmutableSortedMap copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test - public void testCopySingleton() { - final ImmutableSortedMap obj = ImmutableSortedMap.of(1, 1); - final ImmutableSortedMap copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test - public void testCopyRegular() { - final ImmutableSortedMap obj = ImmutableSortedMap.of(1, 2, 3, 4); - final ImmutableSortedMap copied = _kryo.copy(obj); - assertSame(copied, obj); - } - -} \ No newline at end of file + private Kryo _kryo; + + @BeforeTest + public void setUp() throws Exception { + _kryo = new Kryo(); + ImmutableSortedMapSerializer.registerSerializers(_kryo); + } + + @Test + public void testEmpty() { + final ImmutableSortedMap obj = ImmutableSortedMap.of(); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableSortedMap deserialized = deserialize(_kryo, serialized, ImmutableSortedMap.class); + assertTrue(deserialized.isEmpty()); + assertEquals(deserialized.size(), obj.size()); + } + + @Test + public void testSingleton() { + final ImmutableSortedMap obj = ImmutableSortedMap.of(3, "k"); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableSortedMap deserialized = deserialize(_kryo, serialized, ImmutableSortedMap.class); + assertEquals(deserialized, obj); + } + + @Test + public void testRegular() { + final ImmutableSortedMap obj = ImmutableSortedMap.of(5, "r", 3, "k", 6, "y"); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableSortedMap deserialized = deserialize(_kryo, serialized, ImmutableSortedMap.class); + assertEquals(deserialized, obj); + } + + @Test + public void testDescending() { + final ImmutableSortedMap obj = ImmutableSortedMap.of(1, "a", 5, "e", 3, "c").descendingMap(); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableSortedMap deserialized = deserialize(_kryo, serialized, ImmutableSortedMap.class); + assertEquals(deserialized, obj); + } + + @Test + public void testEnum() { + final EnumMap obj = new EnumMap(Planet.class); + for (Planet p : Planet.values()) { + obj.put(p, p.name()); + } + + final ImmutableSortedMap immutableObj = ImmutableSortedMap.copyOf(obj); + final byte[] serialized = serialize(_kryo, immutableObj); + final ImmutableSortedMap deserialized = deserialize(_kryo, serialized, ImmutableSortedMap.class); + assertEquals(deserialized, immutableObj); + } + + @Test + public void testCopyEmpty() { + final ImmutableSortedMap obj = ImmutableSortedMap.of(); + final ImmutableSortedMap copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + // Kryo#copy tests + + @Test + public void testCopySingleton() { + final ImmutableSortedMap obj = ImmutableSortedMap.of(1, 1); + final ImmutableSortedMap copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test + public void testCopyRegular() { + final ImmutableSortedMap obj = ImmutableSortedMap.of(1, 2, 3, 4); + final ImmutableSortedMap copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + private enum Planet { + MERCURY, + VENUS, + EARTH, + MARS; + } + +} diff --git a/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableSortedSetSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableSortedSetSerializerTest.java index 99c6cd29..090f7fc4 100644 --- a/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableSortedSetSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/guava/ImmutableSortedSetSerializerTest.java @@ -1,98 +1,113 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; import static de.javakaffee.kryoserializers.KryoTest.deserialize; import static de.javakaffee.kryoserializers.KryoTest.serialize; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertTrue; +import static org.testng.Assert.*; -import com.esotericsoftware.kryo.Kryo; -import com.google.common.collect.ImmutableSortedSet; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.esotericsoftware.kryo.Kryo; +import com.google.common.collect.ImmutableSortedSet; + /** * Test for {@link ImmutableSortedSetSerializer}. */ public class ImmutableSortedSetSerializerTest { - private Kryo _kryo; - - @BeforeTest - public void setUp() throws Exception { - _kryo = new Kryo(); - - ImmutableSortedSetSerializer.registerSerializers(_kryo); - } - - @Test - public void testEmpty() { - final ImmutableSortedSet obj = ImmutableSortedSet.of(); - final byte[] serialized = serialize( _kryo, obj ); - final ImmutableSortedSet deserialized = deserialize(_kryo, serialized, ImmutableSortedSet.class); - assertTrue(deserialized.isEmpty()); - assertEquals(deserialized.size(), obj.size()); - } - - @Test - public void testSingleton() { - final ImmutableSortedSet obj = ImmutableSortedSet.of(3); - final byte[] serialized = serialize( _kryo, obj ); - final ImmutableSortedSet deserialized = deserialize(_kryo, serialized, ImmutableSortedSet.class); - assertEquals(deserialized, obj); - } - - @Test - public void testDescending() { - final ImmutableSortedSet obj = ImmutableSortedSet.of(3, 4, 5, 6).descendingSet (); - final byte[] serialized = serialize( _kryo, obj ); - final ImmutableSortedSet deserialized = deserialize(_kryo, serialized, ImmutableSortedSet.class); - assertEquals(deserialized, obj); - } - - @Test - public void testRegular() { - final ImmutableSortedSet obj = ImmutableSortedSet.of(3, 4, 5, 6); - final byte[] serialized = serialize( _kryo, obj ); - final ImmutableSortedSet deserialized = deserialize(_kryo, serialized, ImmutableSortedSet.class); - assertEquals(deserialized, obj); - } - - @Test - public void testStringAsImmutableSortedSet() { - final ImmutableSortedSet obj = ImmutableSortedSet.of("K","r", "y", "o"); - final byte[] serialized = serialize(_kryo, obj); - final ImmutableSortedSet deserialized = deserialize(_kryo, serialized, ImmutableSortedSet.class); - assertEquals(deserialized, obj); - } - - // Kryo#copy tests - - @Test - public void testCopyEmpty() { - final ImmutableSortedSet obj = ImmutableSortedSet.of(); - final ImmutableSortedSet copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test - public void testCopySingleton() { - final ImmutableSortedSet obj = ImmutableSortedSet.of(1); - final ImmutableSortedSet copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test - public void testCopyDescending() { - final ImmutableSortedSet obj = ImmutableSortedSet.of(1, 2, 3).descendingSet (); - final ImmutableSortedSet copied = _kryo.copy(obj); - assertSame(copied, obj); - } - - @Test - public void testCopyRegular() { - final ImmutableSortedSet obj = ImmutableSortedSet.of(1, 2, 3); - final ImmutableSortedSet copied = _kryo.copy(obj); - assertSame(copied, obj); - } -} \ No newline at end of file + private Kryo _kryo; + + @BeforeTest + public void setUp() throws Exception { + _kryo = new Kryo(); + + ImmutableSortedSetSerializer.registerSerializers(_kryo); + } + + @Test + public void testEmpty() { + final ImmutableSortedSet obj = ImmutableSortedSet.of(); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableSortedSet deserialized = deserialize(_kryo, serialized, ImmutableSortedSet.class); + assertTrue(deserialized.isEmpty()); + assertEquals(deserialized.size(), obj.size()); + } + + @Test + public void testSingleton() { + final ImmutableSortedSet obj = ImmutableSortedSet.of(3); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableSortedSet deserialized = deserialize(_kryo, serialized, ImmutableSortedSet.class); + assertEquals(deserialized, obj); + } + + @Test + public void testDescending() { + final ImmutableSortedSet obj = ImmutableSortedSet.of(3, 4, 5, 6).descendingSet(); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableSortedSet deserialized = deserialize(_kryo, serialized, ImmutableSortedSet.class); + assertEquals(deserialized, obj); + } + + @Test + public void testRegular() { + final ImmutableSortedSet obj = ImmutableSortedSet.of(3, 4, 5, 6); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableSortedSet deserialized = deserialize(_kryo, serialized, ImmutableSortedSet.class); + assertEquals(deserialized, obj); + } + + @Test + public void testStringAsImmutableSortedSet() { + final ImmutableSortedSet obj = ImmutableSortedSet.of("K", "r", "y", "o"); + final byte[] serialized = serialize(_kryo, obj); + final ImmutableSortedSet deserialized = deserialize(_kryo, serialized, ImmutableSortedSet.class); + assertEquals(deserialized, obj); + } + + // Kryo#copy tests + + @Test + public void testCopyEmpty() { + final ImmutableSortedSet obj = ImmutableSortedSet.of(); + final ImmutableSortedSet copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test + public void testCopySingleton() { + final ImmutableSortedSet obj = ImmutableSortedSet.of(1); + final ImmutableSortedSet copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test + public void testCopyDescending() { + final ImmutableSortedSet obj = ImmutableSortedSet.of(1, 2, 3).descendingSet(); + final ImmutableSortedSet copied = _kryo.copy(obj); + assertSame(copied, obj); + } + + @Test + public void testCopyRegular() { + final ImmutableSortedSet obj = ImmutableSortedSet.of(1, 2, 3); + final ImmutableSortedSet copied = _kryo.copy(obj); + assertSame(copied, obj); + } +} diff --git a/src/test/java/de/javakaffee/kryoserializers/guava/LinkedHashMultimapSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/guava/LinkedHashMultimapSerializerTest.java index a8a4ceff..9924387f 100644 --- a/src/test/java/de/javakaffee/kryoserializers/guava/LinkedHashMultimapSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/guava/LinkedHashMultimapSerializerTest.java @@ -1,30 +1,46 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; -import de.javakaffee.kryoserializers.KryoTest; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import com.esotericsoftware.kryo.Kryo; - import com.google.common.collect.LinkedHashMultimap; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; +import de.javakaffee.kryoserializers.KryoTest; public class LinkedHashMultimapSerializerTest extends MultimapSerializerTestBase { - private Kryo _kryo; - - @BeforeClass - public void initializeKyroWithSerializer() { - _kryo = new Kryo(); - LinkedHashMultimapSerializer.registerSerializers(_kryo); - } - - @Test(dataProvider = "Google Guava multimaps") - public void testMultimap(Object[] contents) { - final LinkedHashMultimap multimap = LinkedHashMultimap.create(); - populateMultimap(multimap, contents); - final byte[] serialized = KryoTest.serialize(_kryo, multimap); - final LinkedHashMultimap deserialized = KryoTest.deserialize(_kryo, serialized, LinkedHashMultimap.class); - assertEqualMultimaps(true, true, deserialized, multimap); - } + private Kryo _kryo; + + @BeforeClass + public void initializeKyroWithSerializer() { + _kryo = new Kryo(); + LinkedHashMultimapSerializer.registerSerializers(_kryo); + } + + @Test(dataProvider = "Google Guava multimaps") + public void testMultimap(Object[] contents) { + final LinkedHashMultimap multimap = LinkedHashMultimap.create(); + populateMultimap(multimap, contents); + final byte[] serialized = KryoTest.serialize(_kryo, multimap); + final LinkedHashMultimap deserialized = + KryoTest.deserialize(_kryo, serialized, LinkedHashMultimap.class); + assertEqualMultimaps(true, true, deserialized, multimap); + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/guava/LinkedListMultimapSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/guava/LinkedListMultimapSerializerTest.java index 129d4a03..d6af8d3c 100644 --- a/src/test/java/de/javakaffee/kryoserializers/guava/LinkedListMultimapSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/guava/LinkedListMultimapSerializerTest.java @@ -1,30 +1,46 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; -import de.javakaffee.kryoserializers.KryoTest; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import com.esotericsoftware.kryo.Kryo; - import com.google.common.collect.LinkedListMultimap; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; +import de.javakaffee.kryoserializers.KryoTest; public class LinkedListMultimapSerializerTest extends MultimapSerializerTestBase { - private Kryo _kryo; - - @BeforeClass - public void initializeKyroWithSerializer() { - _kryo = new Kryo(); - LinkedListMultimapSerializer.registerSerializers(_kryo); - } - - @Test(dataProvider = "Google Guava multimaps") - public void testMultimap(Object[] contents) { - final LinkedListMultimap multimap = LinkedListMultimap.create(); - populateMultimap(multimap, contents); - final byte[] serialized = KryoTest.serialize(_kryo, multimap); - final LinkedListMultimap deserialized = KryoTest.deserialize(_kryo, serialized, LinkedListMultimap.class); - assertEqualMultimaps(true, true, deserialized, multimap); - } + private Kryo _kryo; + + @BeforeClass + public void initializeKyroWithSerializer() { + _kryo = new Kryo(); + LinkedListMultimapSerializer.registerSerializers(_kryo); + } + + @Test(dataProvider = "Google Guava multimaps") + public void testMultimap(Object[] contents) { + final LinkedListMultimap multimap = LinkedListMultimap.create(); + populateMultimap(multimap, contents); + final byte[] serialized = KryoTest.serialize(_kryo, multimap); + final LinkedListMultimap deserialized = + KryoTest.deserialize(_kryo, serialized, LinkedListMultimap.class); + assertEqualMultimaps(true, true, deserialized, multimap); + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/guava/MultimapSerializerTestBase.java b/src/test/java/de/javakaffee/kryoserializers/guava/MultimapSerializerTestBase.java index 1371427d..9f91c061 100644 --- a/src/test/java/de/javakaffee/kryoserializers/guava/MultimapSerializerTestBase.java +++ b/src/test/java/de/javakaffee/kryoserializers/guava/MultimapSerializerTestBase.java @@ -1,70 +1,86 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; -import com.google.common.collect.Multimap; import java.util.ArrayList; import java.util.List; import org.testng.Assert; import org.testng.annotations.DataProvider; +import com.google.common.collect.Multimap; + +@SuppressWarnings("unchecked") public abstract class MultimapSerializerTestBase { - protected void populateMultimap(Multimap multimap, Object[] contents) { - for (int index = 0; index < contents.length;) { - multimap.put((K) contents[index++], (V) contents[index++]); - } - } + protected void populateMultimap(Multimap multimap, Object[] contents) { + for (int index = 0; index < contents.length; ) { + multimap.put((K) contents[index++], (V) contents[index++]); + } + } - protected void assertEqualMultimaps(boolean orderedKeys, boolean orderedValues, - Multimap actual, Multimap expected) { - if (orderedKeys) { - Assert.assertEquals(actual.keySet(), expected.keySet()); - } else { - Assert.assertEqualsNoOrder(actual.keySet().toArray(), expected.keySet().toArray()); - } - for (final K key : expected.keySet()) { - if (orderedValues) { - Assert.assertEquals(actual.get(key), expected.get(key)); - } else { - Assert.assertEqualsNoOrder(actual.get(key).toArray(), expected.get(key).toArray()); - } - } - } + protected void assertEqualMultimaps(boolean orderedKeys, boolean orderedValues, Multimap actual, + Multimap expected) { + if (orderedKeys) { + Assert.assertEquals(actual.keySet(), expected.keySet()); + } else { + Assert.assertEqualsNoOrder(actual.keySet().toArray(), expected.keySet().toArray()); + } + for (final K key : expected.keySet()) { + if (orderedValues) { + Assert.assertEquals(actual.get(key), expected.get(key)); + } else { + Assert.assertEqualsNoOrder(actual.get(key).toArray(), expected.get(key).toArray()); + } + } + } - @DataProvider(name = "Google Guava multimaps") - public Object[][][] getMultimaps() { - final Object[][] multimaps = new Object[][]{new Object[]{}, - new Object[]{"foo", "bar"}, - new Object[]{"foo", null}, - new Object[]{null, "bar"}, - new Object[]{null, null}, - new Object[]{"new", Thread.State.NEW, "run", Thread.State.RUNNABLE}, - new Object[]{1.0, "foo", null, "bar", 1.0, null, null, "baz", 1.0, "wibble"}, - new Object[]{'a', 1, 'b', 2, 'c', 3, 'a', 4, 'b', 5}, - new Object[]{'a', 1, 'b', 2, 'c', 3, 'a', 1, 'b', 2}}; - final Object[][][] toProvide = new Object[multimaps.length][][]; - int index = 0; - for (final Object[] multimap : multimaps) { - toProvide[index++] = new Object[][]{multimap}; - } - return toProvide; - } + @DataProvider(name = "Google Guava multimaps") + public Object[][][] getMultimaps() { + final Object[][] multimaps = + new Object[][] { new Object[] {}, new Object[] { "foo", "bar" }, new Object[] { "foo", null }, + new Object[] { null, "bar" }, new Object[] { null, null }, + new Object[] { "new", Thread.State.NEW, "run", Thread.State.RUNNABLE }, + new Object[] { 1.0, "foo", null, "bar", 1.0, null, null, "baz", 1.0, "wibble" }, + new Object[] { 'a', 1, 'b', 2, 'c', 3, 'a', 4, 'b', 5 }, + new Object[] { 'a', 1, 'b', 2, 'c', 3, 'a', 1, 'b', 2 } }; + final Object[][][] toProvide = new Object[multimaps.length][][]; + int index = 0; + for (final Object[] multimap : multimaps) { + toProvide[index++] = new Object[][] { multimap }; + } + return toProvide; + } - @DataProvider(name = "Google Guava multimaps (no nulls)") - public Object[][][] getMultimapsNoNulls() { - final List multimaps = new ArrayList(); - for (final Object[][] multimap : getMultimaps()) { - boolean isNull = false; - for (final Object element : multimap[0]) { - if (element == null) { - isNull = true; - break; - } - } - if (!isNull) { - multimaps.add(multimap); - } - } - return multimaps.toArray(new Object[multimaps.size()][][]); - } + @DataProvider(name = "Google Guava multimaps (no nulls)") + public Object[][][] getMultimapsNoNulls() { + final List multimaps = new ArrayList(); + for (final Object[][] multimap : getMultimaps()) { + boolean isNull = false; + for (final Object element : multimap[0]) { + if (element == null) { + isNull = true; + break; + } + } + if (!isNull) { + multimaps.add(multimap); + } + } + return multimaps.toArray(new Object[multimaps.size()][][]); + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/guava/ReverseListSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/guava/ReverseListSerializerTest.java index bc367d19..8fbb4b8a 100644 --- a/src/test/java/de/javakaffee/kryoserializers/guava/ReverseListSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/guava/ReverseListSerializerTest.java @@ -1,123 +1,137 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; -import com.google.common.collect.Lists; - -import com.esotericsoftware.kryo.Kryo; - -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; +import static de.javakaffee.kryoserializers.KryoTest.deserialize; +import static de.javakaffee.kryoserializers.KryoTest.serialize; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; import java.util.Arrays; import java.util.Collections; import java.util.List; -import static de.javakaffee.kryoserializers.KryoTest.deserialize; -import static de.javakaffee.kryoserializers.KryoTest.serialize; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; +import com.esotericsoftware.kryo.Kryo; +import com.google.common.collect.Lists; /** * Test for {@link ReverseListSerializer}. */ public class ReverseListSerializerTest { - private Kryo _kryo; - - @BeforeTest - public void setUp() throws Exception { - _kryo = new Kryo(); - - ReverseListSerializer.registerSerializers(_kryo); - } - - @Test( enabled = true ) - public void testEmptyReverseList() { - testEmpty(Lists.reverse(Lists.newLinkedList())); - } - - @Test( enabled = true ) - public void testEmptyRandomAccessReverseList() { - testEmpty(Lists.reverse(Lists.newArrayList())); - } - - private void testEmpty(final List reverseList) { - final byte[] serialized = serialize( _kryo, reverseList ); - final List deserialized = deserialize(_kryo, serialized, reverseList.getClass()); - assertEquals(deserialized.getClass(), reverseList.getClass()); - assertTrue(deserialized.isEmpty()); - assertEquals(deserialized.size(), reverseList.size()); - } - - @Test( enabled = true ) - public void testSingletonReverseList() { - testSingleton(Lists.reverse(Lists.newLinkedList(Collections.singleton(3)))); - } - - @Test( enabled = true ) - public void testSingletonRandomAccessReverseList() { - testSingleton(Lists.reverse(Lists.newArrayList(Collections.singleton(3)))); - } - - private void testSingleton(final List reverseList) { - final byte[] serialized = serialize( _kryo, reverseList ); - final List deserialized = deserialize(_kryo, serialized, reverseList.getClass()); - assertEquals(deserialized.getClass(), reverseList.getClass()); - assertEquals(deserialized, reverseList); - } - - @Test( enabled = true ) - public void testRegularReverseList() { - testRegular(Lists.reverse(Lists.newLinkedList(Arrays.asList(3, 4, 5, 6)))); - } - - @Test( enabled = true ) - public void testRegularRandomAccessReverseList() { - testRegular(Lists.reverse(Lists.newArrayList(3, 4, 5, 6))); - } - - private void testRegular(final List reverseList) { - final byte[] serialized = serialize( _kryo, reverseList ); - final List deserialized = deserialize(_kryo, serialized, reverseList.getClass()); - assertEquals(deserialized.getClass(), reverseList.getClass()); - assertEquals(deserialized, reverseList); - } - - // Kryo#copy tests - - @Test( enabled = true ) - public void testCopyEmptyReverseList() { - testCopy(Lists.reverse(Lists.newLinkedList())); - } - - @Test( enabled = true ) - public void testCopyEmptyRandomAccessReverseList() { - testCopy(Lists.reverse(Lists.newArrayList())); - } - - @Test( enabled = true ) - public void testCopySingletonReverseList() { - testCopy(Lists.reverse(Lists.newLinkedList(Collections.singleton(3)))); - } - - @Test( enabled = true ) - public void testCopySingletonRandomAccessReverseList() { - testCopy(Lists.reverse(Lists.newArrayList(Collections.singleton(3)))); - } - - @Test( enabled = true ) - public void testCopyRegularReverseList() { - testCopy(Lists.reverse(Lists.newLinkedList(Arrays.asList(3, 4, 5, 6)))); - } - - @Test( enabled = true ) - public void testCopyRegularRandomAccessReverseList() { - testCopy(Lists.reverse(Lists.newArrayList(3, 4, 5, 6))); - } - - private void testCopy(List obj) { - final List copied = _kryo.copy(obj); - assertEquals(copied.getClass(), obj.getClass()); - assertEquals(copied, obj); - } + private Kryo _kryo; + + @BeforeTest + public void setUp() throws Exception { + _kryo = new Kryo(); + + ReverseListSerializer.registerSerializers(_kryo); + } + + @Test(enabled = true) + public void testEmptyReverseList() { + testEmpty(Lists.reverse(Lists.newLinkedList())); + } + + @Test(enabled = true) + public void testEmptyRandomAccessReverseList() { + testEmpty(Lists.reverse(Lists.newArrayList())); + } + + private void testEmpty(final List reverseList) { + final byte[] serialized = serialize(_kryo, reverseList); + final List deserialized = deserialize(_kryo, serialized, reverseList.getClass()); + assertEquals(deserialized.getClass(), reverseList.getClass()); + assertTrue(deserialized.isEmpty()); + assertEquals(deserialized.size(), reverseList.size()); + } + + @Test(enabled = true) + public void testSingletonReverseList() { + testSingleton(Lists.reverse(Lists.newLinkedList(Collections.singleton(3)))); + } + + @Test(enabled = true) + public void testSingletonRandomAccessReverseList() { + testSingleton(Lists.reverse(Lists.newArrayList(Collections.singleton(3)))); + } + + private void testSingleton(final List reverseList) { + final byte[] serialized = serialize(_kryo, reverseList); + final List deserialized = deserialize(_kryo, serialized, reverseList.getClass()); + assertEquals(deserialized.getClass(), reverseList.getClass()); + assertEquals(deserialized, reverseList); + } + + @Test(enabled = true) + public void testRegularReverseList() { + testRegular(Lists.reverse(Lists.newLinkedList(Arrays.asList(3, 4, 5, 6)))); + } + + @Test(enabled = true) + public void testRegularRandomAccessReverseList() { + testRegular(Lists.reverse(Lists.newArrayList(3, 4, 5, 6))); + } + + private void testRegular(final List reverseList) { + final byte[] serialized = serialize(_kryo, reverseList); + final List deserialized = deserialize(_kryo, serialized, reverseList.getClass()); + assertEquals(deserialized.getClass(), reverseList.getClass()); + assertEquals(deserialized, reverseList); + } + + // Kryo#copy tests + + @Test(enabled = true) + public void testCopyEmptyReverseList() { + testCopy(Lists.reverse(Lists.newLinkedList())); + } + + @Test(enabled = true) + public void testCopyEmptyRandomAccessReverseList() { + testCopy(Lists.reverse(Lists.newArrayList())); + } + + @Test(enabled = true) + public void testCopySingletonReverseList() { + testCopy(Lists.reverse(Lists.newLinkedList(Collections.singleton(3)))); + } + + @Test(enabled = true) + public void testCopySingletonRandomAccessReverseList() { + testCopy(Lists.reverse(Lists.newArrayList(Collections.singleton(3)))); + } + + @Test(enabled = true) + public void testCopyRegularReverseList() { + testCopy(Lists.reverse(Lists.newLinkedList(Arrays.asList(3, 4, 5, 6)))); + } + + @Test(enabled = true) + public void testCopyRegularRandomAccessReverseList() { + testCopy(Lists.reverse(Lists.newArrayList(3, 4, 5, 6))); + } + + private void testCopy(List obj) { + final List copied = _kryo.copy(obj); + assertEquals(copied.getClass(), obj.getClass()); + assertEquals(copied, obj); + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/guava/TreeMultimapSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/guava/TreeMultimapSerializerTest.java index b0b81534..f82b7115 100644 --- a/src/test/java/de/javakaffee/kryoserializers/guava/TreeMultimapSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/guava/TreeMultimapSerializerTest.java @@ -1,30 +1,46 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; -import de.javakaffee.kryoserializers.KryoTest; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import com.esotericsoftware.kryo.Kryo; - import com.google.common.collect.TreeMultimap; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; +import de.javakaffee.kryoserializers.KryoTest; public class TreeMultimapSerializerTest extends MultimapSerializerTestBase { - private Kryo _kryo; - - @BeforeClass - public void initializeKyroWithSerializer() { - _kryo = new Kryo(); - TreeMultimapSerializer.registerSerializers(_kryo); - } - - @Test(dataProvider = "Google Guava multimaps (no nulls)") - public void testMultimap(Object[] contents) { - final TreeMultimap multimap = TreeMultimap.create(); - populateMultimap(multimap, contents); - final byte[] serialized = KryoTest.serialize(_kryo, multimap); - final TreeMultimap deserialized = KryoTest.deserialize(_kryo, serialized, TreeMultimap.class); - assertEqualMultimaps(true, true, deserialized, multimap); - } + private Kryo _kryo; + + @BeforeClass + public void initializeKyroWithSerializer() { + _kryo = new Kryo(); + TreeMultimapSerializer.registerSerializers(_kryo); + } + + @Test(dataProvider = "Google Guava multimaps (no nulls)") + public void testMultimap(Object[] contents) { + final TreeMultimap multimap = TreeMultimap.create(); + populateMultimap(multimap, contents); + final byte[] serialized = KryoTest.serialize(_kryo, multimap); + final TreeMultimap deserialized = + KryoTest.deserialize(_kryo, serialized, TreeMultimap.class); + assertEqualMultimaps(true, true, deserialized, multimap); + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/guava/UnmodifiableNavigableSetSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/guava/UnmodifiableNavigableSetSerializerTest.java index 464f6034..f170abbb 100644 --- a/src/test/java/de/javakaffee/kryoserializers/guava/UnmodifiableNavigableSetSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/guava/UnmodifiableNavigableSetSerializerTest.java @@ -1,198 +1,216 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.guava; import static de.javakaffee.kryoserializers.KryoTest.deserialize; import static de.javakaffee.kryoserializers.KryoTest.serialize; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.fail; +import static org.testng.Assert.*; import java.util.NavigableSet; import java.util.TreeSet; import java.util.concurrent.ConcurrentSkipListSet; -import com.esotericsoftware.kryo.Kryo; -import com.google.common.collect.Sets; - import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.esotericsoftware.kryo.Kryo; +import com.google.common.collect.Sets; + /** * Test for {@link ImmutableSortedSetSerializer}. */ -@SuppressWarnings({"rawtypes", "unchecked"}) +@SuppressWarnings({ "rawtypes", "unchecked" }) public class UnmodifiableNavigableSetSerializerTest { - private Kryo _kryo; - - @BeforeTest - public void setUp() { - _kryo = new Kryo(); - - UnmodifiableNavigableSetSerializer.registerSerializers(_kryo); - } - - Class unmodifiableClass; - { - unmodifiableClass = (Class) Sets.unmodifiableNavigableSet(new TreeSet()).getClass(); - } - - UnmodifiableNavigableSetSerializer forUnwrapping = new UnmodifiableNavigableSetSerializer(); - - private void assertUnderlyingSet(NavigableSet deserialized, Class class1) { - assertEquals( - forUnwrapping.getDelegateFromUnmodifiableNavigableSet(deserialized).getClass(), - class1, - "Expected underlying class to match"); - } - - @Test - public void testEmptyTreeSet() { - final TreeSet coreSet = Sets.newTreeSet(); - final NavigableSet obj = Sets.unmodifiableNavigableSet(coreSet); - final byte[] serialized = serialize(_kryo, obj); - final NavigableSet deserialized = deserialize(_kryo, serialized, unmodifiableClass); - assertTrue(deserialized.isEmpty()); - assertEquals(deserialized.size(), obj.size()); - // And ensure what we get is truly unmodifiable - try { - deserialized.add("a"); - fail("Should have been unable to add a field to an unmodifiable collection post deserialization"); - } catch (UnsupportedOperationException expected) {} - assertUnderlyingSet(deserialized, coreSet.getClass()); - } - - @Test - public void testEmptySkipList() { - final ConcurrentSkipListSet coreSet = new ConcurrentSkipListSet(); - final NavigableSet obj = Sets.unmodifiableNavigableSet(coreSet); - final byte[] serialized = serialize(_kryo, obj); - final NavigableSet deserialized = deserialize(_kryo, serialized, unmodifiableClass); - assertTrue(deserialized.isEmpty()); - assertEquals(deserialized.size(), obj.size()); - // And ensure what we get is truly unmodifiable - try { - deserialized.add("a"); - fail("Should have been unable to add a field to an unmodifiable collection post deserialization"); - } catch (UnsupportedOperationException expected) {} - assertUnderlyingSet(deserialized, coreSet.getClass()); - } - - @Test - public void testPopulatedTreeSet() { - final TreeSet coreSet = Sets.newTreeSet(); - coreSet.add("k"); - coreSet.add("r"); - coreSet.add("y"); - coreSet.add("o"); - final NavigableSet obj = Sets.unmodifiableNavigableSet(coreSet); - final byte[] serialized = serialize(_kryo, obj); - final NavigableSet deserialized = deserialize(_kryo, serialized, unmodifiableClass); - assertFalse(deserialized.isEmpty()); - assertEquals(deserialized.size(), obj.size()); - assertEquals(deserialized, obj); - // And ensure what we get is truly unmodifiable - try { - deserialized.add("a"); - fail("Should have been unable to add a field to an unmodifiable collection post deserialization"); - } catch (UnsupportedOperationException expected) {} - assertUnderlyingSet(deserialized, coreSet.getClass()); - } - - @Test - public void testPopulatedSkipList() { - final ConcurrentSkipListSet coreSet = new ConcurrentSkipListSet(); - coreSet.add("k"); - coreSet.add("r"); - coreSet.add("y"); - coreSet.add("o"); - final NavigableSet obj = Sets.unmodifiableNavigableSet(coreSet); - final byte[] serialized = serialize(_kryo, obj); - final NavigableSet deserialized = deserialize(_kryo, serialized, unmodifiableClass); - assertFalse(deserialized.isEmpty()); - assertEquals(deserialized.size(), obj.size()); - assertEquals(deserialized, obj); - // And ensure what we get is truly unmodifiable - try { - deserialized.add("a"); - fail("Should have been unable to add a field to an unmodifiable collection post deserialization"); - } catch (UnsupportedOperationException expected) {} - assertUnderlyingSet(deserialized, coreSet.getClass()); - } - - // Kryo#copy tests - - @Test - public void testCopyEmptyTreeSet() { - final TreeSet coreSet = Sets.newTreeSet(); - final NavigableSet obj = Sets.unmodifiableNavigableSet(coreSet); - final NavigableSet copied = _kryo.copy(obj); - assertTrue(copied.isEmpty()); - assertEquals(copied.size(), obj.size()); - - // And ensure what we get is truly unmodifiable - try { - copied.add("a"); - fail("Should have been unable to add a field to an unmodifiable collection post deserialization"); - } catch (UnsupportedOperationException expected) {} - assertUnderlyingSet(copied, coreSet.getClass()); - } - - @Test - public void testCopyEmptySkipList() { - final ConcurrentSkipListSet coreSet = new ConcurrentSkipListSet(); - final NavigableSet obj = Sets.unmodifiableNavigableSet(coreSet); - final NavigableSet copied = _kryo.copy(obj); - assertTrue(copied.isEmpty()); - assertEquals(copied.size(), obj.size()); - - // And ensure what we get is truly unmodifiable - try { - copied.add("a"); - fail("Should have been unable to add a field to an unmodifiable collection post deserialization"); - } catch (UnsupportedOperationException expected) {} - assertUnderlyingSet(copied, coreSet.getClass()); - } - - @Test - public void testCopyPopulatedTreeSet() { - final TreeSet coreSet = Sets.newTreeSet(); - coreSet.add("k"); - coreSet.add("r"); - coreSet.add("y"); - coreSet.add("o"); - final NavigableSet obj = Sets.unmodifiableNavigableSet(coreSet); - final NavigableSet copied = _kryo.copy(obj); - assertFalse(copied.isEmpty()); - assertEquals(copied.size(), obj.size()); - assertEquals(copied, obj); - - // And ensure what we get is truly unmodifiable - try { - copied.add("a"); - fail("Should have been unable to add a field to an unmodifiable collection post deserialization"); - } catch (UnsupportedOperationException expected) {} - assertUnderlyingSet(copied, coreSet.getClass()); - } - - @Test - public void testCopyPopulatedSkipList() { - final ConcurrentSkipListSet coreSet = new ConcurrentSkipListSet(); - coreSet.add("k"); - coreSet.add("r"); - coreSet.add("y"); - coreSet.add("o"); - final NavigableSet obj = Sets.unmodifiableNavigableSet(coreSet); - final NavigableSet copied = _kryo.copy(obj); - assertFalse(copied.isEmpty()); - assertEquals(copied.size(), obj.size()); - assertEquals(copied, obj); - - // And ensure what we get is truly unmodifiable - try { - copied.add("a"); - fail("Should have been unable to add a field to an unmodifiable collection post deserialization"); - } catch (UnsupportedOperationException expected) {} - assertUnderlyingSet(copied, coreSet.getClass()); - } + Class unmodifiableClass; + UnmodifiableNavigableSetSerializer forUnwrapping = new UnmodifiableNavigableSetSerializer(); + private Kryo _kryo; + + { + unmodifiableClass = (Class) Sets.unmodifiableNavigableSet(new TreeSet()).getClass(); + } + + @BeforeTest + public void setUp() { + _kryo = new Kryo(); + + UnmodifiableNavigableSetSerializer.registerSerializers(_kryo); + } + + private void assertUnderlyingSet(NavigableSet deserialized, Class class1) { + assertEquals(forUnwrapping.getDelegateFromUnmodifiableNavigableSet(deserialized).getClass(), class1, + "Expected underlying class to match"); + } + + @Test + public void testEmptyTreeSet() { + final TreeSet coreSet = Sets.newTreeSet(); + final NavigableSet obj = Sets.unmodifiableNavigableSet(coreSet); + final byte[] serialized = serialize(_kryo, obj); + final NavigableSet deserialized = deserialize(_kryo, serialized, unmodifiableClass); + assertTrue(deserialized.isEmpty()); + assertEquals(deserialized.size(), obj.size()); + // And ensure what we get is truly unmodifiable + try { + deserialized.add("a"); + fail("Should have been unable to add a field to an unmodifiable collection post deserialization"); + } catch (UnsupportedOperationException expected) { + } + assertUnderlyingSet(deserialized, coreSet.getClass()); + } + + @Test + public void testEmptySkipList() { + final ConcurrentSkipListSet coreSet = new ConcurrentSkipListSet(); + final NavigableSet obj = Sets.unmodifiableNavigableSet(coreSet); + final byte[] serialized = serialize(_kryo, obj); + final NavigableSet deserialized = deserialize(_kryo, serialized, unmodifiableClass); + assertTrue(deserialized.isEmpty()); + assertEquals(deserialized.size(), obj.size()); + // And ensure what we get is truly unmodifiable + try { + deserialized.add("a"); + fail("Should have been unable to add a field to an unmodifiable collection post deserialization"); + } catch (UnsupportedOperationException expected) { + } + assertUnderlyingSet(deserialized, coreSet.getClass()); + } + + @Test + public void testPopulatedTreeSet() { + final TreeSet coreSet = Sets.newTreeSet(); + coreSet.add("k"); + coreSet.add("r"); + coreSet.add("y"); + coreSet.add("o"); + final NavigableSet obj = Sets.unmodifiableNavigableSet(coreSet); + final byte[] serialized = serialize(_kryo, obj); + final NavigableSet deserialized = deserialize(_kryo, serialized, unmodifiableClass); + assertFalse(deserialized.isEmpty()); + assertEquals(deserialized.size(), obj.size()); + assertEquals(deserialized, obj); + // And ensure what we get is truly unmodifiable + try { + deserialized.add("a"); + fail("Should have been unable to add a field to an unmodifiable collection post deserialization"); + } catch (UnsupportedOperationException expected) { + } + assertUnderlyingSet(deserialized, coreSet.getClass()); + } + + @Test + public void testPopulatedSkipList() { + final ConcurrentSkipListSet coreSet = new ConcurrentSkipListSet(); + coreSet.add("k"); + coreSet.add("r"); + coreSet.add("y"); + coreSet.add("o"); + final NavigableSet obj = Sets.unmodifiableNavigableSet(coreSet); + final byte[] serialized = serialize(_kryo, obj); + final NavigableSet deserialized = deserialize(_kryo, serialized, unmodifiableClass); + assertFalse(deserialized.isEmpty()); + assertEquals(deserialized.size(), obj.size()); + assertEquals(deserialized, obj); + // And ensure what we get is truly unmodifiable + try { + deserialized.add("a"); + fail("Should have been unable to add a field to an unmodifiable collection post deserialization"); + } catch (UnsupportedOperationException expected) { + } + assertUnderlyingSet(deserialized, coreSet.getClass()); + } + + // Kryo#copy tests + + @Test + public void testCopyEmptyTreeSet() { + final TreeSet coreSet = Sets.newTreeSet(); + final NavigableSet obj = Sets.unmodifiableNavigableSet(coreSet); + final NavigableSet copied = _kryo.copy(obj); + assertTrue(copied.isEmpty()); + assertEquals(copied.size(), obj.size()); + + // And ensure what we get is truly unmodifiable + try { + copied.add("a"); + fail("Should have been unable to add a field to an unmodifiable collection post deserialization"); + } catch (UnsupportedOperationException expected) { + } + assertUnderlyingSet(copied, coreSet.getClass()); + } + + @Test + public void testCopyEmptySkipList() { + final ConcurrentSkipListSet coreSet = new ConcurrentSkipListSet(); + final NavigableSet obj = Sets.unmodifiableNavigableSet(coreSet); + final NavigableSet copied = _kryo.copy(obj); + assertTrue(copied.isEmpty()); + assertEquals(copied.size(), obj.size()); + + // And ensure what we get is truly unmodifiable + try { + copied.add("a"); + fail("Should have been unable to add a field to an unmodifiable collection post deserialization"); + } catch (UnsupportedOperationException expected) { + } + assertUnderlyingSet(copied, coreSet.getClass()); + } + + @Test + public void testCopyPopulatedTreeSet() { + final TreeSet coreSet = Sets.newTreeSet(); + coreSet.add("k"); + coreSet.add("r"); + coreSet.add("y"); + coreSet.add("o"); + final NavigableSet obj = Sets.unmodifiableNavigableSet(coreSet); + final NavigableSet copied = _kryo.copy(obj); + assertFalse(copied.isEmpty()); + assertEquals(copied.size(), obj.size()); + assertEquals(copied, obj); + + // And ensure what we get is truly unmodifiable + try { + copied.add("a"); + fail("Should have been unable to add a field to an unmodifiable collection post deserialization"); + } catch (UnsupportedOperationException expected) { + } + assertUnderlyingSet(copied, coreSet.getClass()); + } + + @Test + public void testCopyPopulatedSkipList() { + final ConcurrentSkipListSet coreSet = new ConcurrentSkipListSet(); + coreSet.add("k"); + coreSet.add("r"); + coreSet.add("y"); + coreSet.add("o"); + final NavigableSet obj = Sets.unmodifiableNavigableSet(coreSet); + final NavigableSet copied = _kryo.copy(obj); + assertFalse(copied.isEmpty()); + assertEquals(copied.size(), obj.size()); + assertEquals(copied, obj); + + // And ensure what we get is truly unmodifiable + try { + copied.add("a"); + fail("Should have been unable to add a field to an unmodifiable collection post deserialization"); + } catch (UnsupportedOperationException expected) { + } + assertUnderlyingSet(copied, coreSet.getClass()); + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/jodatime/JodaDateTimeSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/jodatime/JodaDateTimeSerializerTest.java index 715c6956..9a16e71b 100644 --- a/src/test/java/de/javakaffee/kryoserializers/jodatime/JodaDateTimeSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/jodatime/JodaDateTimeSerializerTest.java @@ -28,32 +28,32 @@ /** * Test for {@link JodaDateTimeSerializer}. - * + * * @author Martin Grotzke */ public class JodaDateTimeSerializerTest { - - private Kryo _kryo; - - @BeforeTest - protected void beforeTest() { - _kryo = new Kryo(); - _kryo.register( DateTime.class, new JodaDateTimeSerializer() ); - } - - @Test( enabled = true ) - public void testJodaDateTime() { - final DateTime obj = new DateTime().withDayOfYear( 42 ); - final byte[] serialized = serialize( _kryo, obj ); - final DateTime deserialized = deserialize( _kryo, serialized, DateTime.class ); - Assert.assertEquals( deserialized, obj ); - } - - @Test( enabled = true ) - public void testCopyJodaDateTime() { - final DateTime obj = new DateTime().withDayOfYear( 42 ); - final DateTime copy = _kryo.copy(obj); - Assert.assertEquals( copy, obj ); - } + + private Kryo _kryo; + + @BeforeTest + protected void beforeTest() { + _kryo = new Kryo(); + _kryo.register(DateTime.class, new JodaDateTimeSerializer()); + } + + @Test(enabled = true) + public void testJodaDateTime() { + final DateTime obj = new DateTime().withDayOfYear(42); + final byte[] serialized = serialize(_kryo, obj); + final DateTime deserialized = deserialize(_kryo, serialized, DateTime.class); + Assert.assertEquals(deserialized, obj); + } + + @Test(enabled = true) + public void testCopyJodaDateTime() { + final DateTime obj = new DateTime().withDayOfYear(42); + final DateTime copy = _kryo.copy(obj); + Assert.assertEquals(copy, obj); + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/jodatime/JodaIntervalSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/jodatime/JodaIntervalSerializerTest.java index ba37b8c4..38d1cc80 100644 --- a/src/test/java/de/javakaffee/kryoserializers/jodatime/JodaIntervalSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/jodatime/JodaIntervalSerializerTest.java @@ -1,4 +1,6 @@ /* + * Copyright 2018 Martin Grotzke + * * 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 @@ -28,31 +30,30 @@ /** * Test for {@link JodaIntervalSerializer}. - * */ public class JodaIntervalSerializerTest { - - private Kryo _kryo; - - @BeforeTest - protected void beforeTest() { - _kryo = new Kryo(); - _kryo.register( Interval.class, new JodaIntervalSerializer() ); - } - - @Test( enabled = true ) - public void testJodaInterval() { - final Interval obj = new Interval(new DateTime(1942,1,1,0,0,0,0), Days.days(42)); - final byte[] serialized = serialize( _kryo, obj ); - final Interval deserialized = deserialize( _kryo, serialized, Interval.class ); - Assert.assertEquals( deserialized, obj ); - } - - @Test( enabled = true ) - public void testCopyJodaDateTime() { - final Interval obj = new Interval(new DateTime(1942,1,1,0,0,0,0), Days.days(42)); - final Interval copy = _kryo.copy(obj); - Assert.assertEquals( copy, obj ); - } + + private Kryo _kryo; + + @BeforeTest + protected void beforeTest() { + _kryo = new Kryo(); + _kryo.register(Interval.class, new JodaIntervalSerializer()); + } + + @Test(enabled = true) + public void testJodaInterval() { + final Interval obj = new Interval(new DateTime(1942, 1, 1, 0, 0, 0, 0), Days.days(42)); + final byte[] serialized = serialize(_kryo, obj); + final Interval deserialized = deserialize(_kryo, serialized, Interval.class); + Assert.assertEquals(deserialized, obj); + } + + @Test(enabled = true) + public void testCopyJodaDateTime() { + final Interval obj = new Interval(new DateTime(1942, 1, 1, 0, 0, 0, 0), Days.days(42)); + final Interval copy = _kryo.copy(obj); + Assert.assertEquals(copy, obj); + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/jodatime/JodaLocalDateSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/jodatime/JodaLocalDateSerializerTest.java index 191a0d34..24ac70c0 100644 --- a/src/test/java/de/javakaffee/kryoserializers/jodatime/JodaLocalDateSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/jodatime/JodaLocalDateSerializerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 Rennie Petersen + * Copyright 2018 Martin Grotzke * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,27 +33,27 @@ */ public class JodaLocalDateSerializerTest { - private Kryo _kryo; - - @BeforeTest - protected void beforeTest() { - _kryo = new Kryo(); - _kryo.register(LocalDate.class, new JodaLocalDateSerializer()); - } - - @Test(enabled = true) - public void testJodaLocalDate() { - final LocalDate obj = new LocalDate().withDayOfYear(42); - final byte[] serialized = serialize(_kryo, obj); - final LocalDate deserialized = deserialize(_kryo, serialized, LocalDate.class); - Assert.assertEquals(deserialized, obj); - } - - @Test(enabled = true) - public void testCopyJodaLocalDate() { - final LocalDate obj = new LocalDate().withDayOfYear(42); - final LocalDate copy = _kryo.copy(obj); - Assert.assertEquals(copy, obj); - } + private Kryo _kryo; + + @BeforeTest + protected void beforeTest() { + _kryo = new Kryo(); + _kryo.register(LocalDate.class, new JodaLocalDateSerializer()); + } + + @Test(enabled = true) + public void testJodaLocalDate() { + final LocalDate obj = new LocalDate().withDayOfYear(42); + final byte[] serialized = serialize(_kryo, obj); + final LocalDate deserialized = deserialize(_kryo, serialized, LocalDate.class); + Assert.assertEquals(deserialized, obj); + } + + @Test(enabled = true) + public void testCopyJodaLocalDate() { + final LocalDate obj = new LocalDate().withDayOfYear(42); + final LocalDate copy = _kryo.copy(obj); + Assert.assertEquals(copy, obj); + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/jodatime/JodaLocalDateTimeSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/jodatime/JodaLocalDateTimeSerializerTest.java index c3af3fcd..588bb5f9 100644 --- a/src/test/java/de/javakaffee/kryoserializers/jodatime/JodaLocalDateTimeSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/jodatime/JodaLocalDateTimeSerializerTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 Rennie Petersen + * Copyright 2018 Martin Grotzke * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,27 +33,27 @@ */ public class JodaLocalDateTimeSerializerTest { - private Kryo _kryo; - - @BeforeTest - protected void beforeTest() { - _kryo = new Kryo(); - _kryo.register(LocalDateTime.class, new JodaLocalDateTimeSerializer()); - } - - @Test(enabled = true) - public void testJodaLocalDateTime() { - final LocalDateTime obj = new LocalDateTime().withDayOfYear(42); - final byte[] serialized = serialize(_kryo, obj); - final LocalDateTime deserialized = deserialize(_kryo, serialized, LocalDateTime.class); - Assert.assertEquals(deserialized, obj); - } - - @Test(enabled = true) - public void testCopyJodaLocalDateTime() { - final LocalDateTime obj = new LocalDateTime().withDayOfYear(42); - final LocalDateTime copy = _kryo.copy(obj); - Assert.assertEquals(copy, obj); - } + private Kryo _kryo; + + @BeforeTest + protected void beforeTest() { + _kryo = new Kryo(); + _kryo.register(LocalDateTime.class, new JodaLocalDateTimeSerializer()); + } + + @Test(enabled = true) + public void testJodaLocalDateTime() { + final LocalDateTime obj = new LocalDateTime().withDayOfYear(42); + final byte[] serialized = serialize(_kryo, obj); + final LocalDateTime deserialized = deserialize(_kryo, serialized, LocalDateTime.class); + Assert.assertEquals(deserialized, obj); + } + + @Test(enabled = true) + public void testCopyJodaLocalDateTime() { + final LocalDateTime obj = new LocalDateTime().withDayOfYear(42); + final LocalDateTime copy = _kryo.copy(obj); + Assert.assertEquals(copy, obj); + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/jodatime/JodaLocalTimeSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/jodatime/JodaLocalTimeSerializerTest.java index e391f887..af4c9c6f 100644 --- a/src/test/java/de/javakaffee/kryoserializers/jodatime/JodaLocalTimeSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/jodatime/JodaLocalTimeSerializerTest.java @@ -1,14 +1,33 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.jodatime; -import com.esotericsoftware.kryo.Kryo; -import org.joda.time.*; +import static de.javakaffee.kryoserializers.KryoTest.deserialize; +import static de.javakaffee.kryoserializers.KryoTest.serialize; + +import org.joda.time.Chronology; +import org.joda.time.DateTimeZone; +import org.joda.time.LocalTime; import org.joda.time.chrono.GregorianChronology; import org.testng.Assert; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; -import static de.javakaffee.kryoserializers.KryoTest.deserialize; -import static de.javakaffee.kryoserializers.KryoTest.serialize; +import com.esotericsoftware.kryo.Kryo; /** * Tests for {@link JodaLocalTimeSerializer}. @@ -16,30 +35,30 @@ * @author Rob Reeves */ public class JodaLocalTimeSerializerTest { - private Kryo _kryo; + private Kryo _kryo; - @BeforeTest - protected void beforeTest() { - _kryo = new Kryo(); - _kryo.register(LocalTime.class, new JodaLocalTimeSerializer()); - } + @BeforeTest + protected void beforeTest() { + _kryo = new Kryo(); + _kryo.register(LocalTime.class, new JodaLocalTimeSerializer()); + } - @Test(enabled = true) - public void testJodaLocalTime() { - final DateTimeZone tz = DateTimeZone.forID("America/Los_Angeles"); - final Chronology chronology = GregorianChronology.getInstance(tz); - final LocalTime obj = new LocalTime(null, chronology); - final byte[] serialized = serialize(_kryo, obj); - final LocalTime deserialized = deserialize(_kryo, serialized, LocalTime.class); - Assert.assertEquals(deserialized, obj); - } + @Test(enabled = true) + public void testJodaLocalTime() { + final DateTimeZone tz = DateTimeZone.forID("America/Los_Angeles"); + final Chronology chronology = GregorianChronology.getInstance(tz); + final LocalTime obj = new LocalTime(null, chronology); + final byte[] serialized = serialize(_kryo, obj); + final LocalTime deserialized = deserialize(_kryo, serialized, LocalTime.class); + Assert.assertEquals(deserialized, obj); + } - @Test(enabled = true) - public void testCopyJodaLocalTime() { - final DateTimeZone tz = DateTimeZone.forID("America/Los_Angeles"); - final Chronology chronology = GregorianChronology.getInstance(tz); - final LocalTime obj = new LocalTime(52341234, chronology); - final LocalTime copy = _kryo.copy(obj); - Assert.assertEquals(copy, obj); - } + @Test(enabled = true) + public void testCopyJodaLocalTime() { + final DateTimeZone tz = DateTimeZone.forID("America/Los_Angeles"); + final Chronology chronology = GregorianChronology.getInstance(tz); + final LocalTime obj = new LocalTime(52341234, chronology); + final LocalTime copy = _kryo.copy(obj); + Assert.assertEquals(copy, obj); + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/protobuf/ProtobufSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/protobuf/ProtobufSerializerTest.java index fb10c6dd..7d4058cc 100644 --- a/src/test/java/de/javakaffee/kryoserializers/protobuf/ProtobufSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/protobuf/ProtobufSerializerTest.java @@ -1,184 +1,206 @@ +/* + * Copyright 2018 Martin Grotzke + * + * 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 de.javakaffee.kryoserializers.protobuf; +import static org.testng.Assert.*; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; + import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; + import de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA; import de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; - -import static org.testng.Assert.*; - +@SuppressWarnings("unchecked") public class ProtobufSerializerTest { - private Kryo _kryo; - - @BeforeTest - public void setUp() throws Exception { - _kryo = new Kryo(); - _kryo.register(SampleProtoA.class, new ProtobufSerializer()); - _kryo.register(SampleProtoB.class, new ProtobufSerializer()); - } - - @Test - /** - * Verifies that the Serializer works over a single Protobuf object - */ - public void testSerializerWithProtoA() throws Exception { - Integer expectedMessageId = 12332; - String expectedName = "Esteban"; - - SampleProtoA protoA = createSampleProtoA(expectedMessageId, expectedName); - - // Attempt to serialize - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - Output o = new Output(outStream, 4096); - _kryo.getSerializer(protoA.getClass()).write(_kryo, o, protoA); - - // Attempt to deserialize - Input i = new Input(new ByteArrayInputStream(outStream.toByteArray()), 4096); - SampleProtoA verifyProtoA = (SampleProtoA) _kryo.getSerializer(protoA.getClass()).read(_kryo, i, SampleProtoA.class); - - // Verify it - assertEquals((Integer)expectedMessageId, (Integer)verifyProtoA.getMessageId(), "MessageId is correct"); - assertEquals((String)expectedName, (String)verifyProtoA.getName(), "Name is correct"); - } - - @Test - /** - * Verifies that the Serializer works back to back with multiple protobufs instances of the same type (SampleProtoA) - */ - public void testSerializerWithMultipleInstances() throws Exception { - // Create first instance - Integer expectedMessageId1 = 12332; - String expectedName1 = "Esteban"; - SampleProtoA protoA1 = createSampleProtoA(expectedMessageId1, expectedName1); - - // Create 2nd instance - Integer expectedMessageId2 = 531; - String expectedName2 = "Bergo"; - SampleProtoA protoA2 = createSampleProtoA(expectedMessageId2, expectedName2); - - // Attempt to serialize instance 1 - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - Output o = new Output(outStream, 4096); - _kryo.getSerializer(protoA1.getClass()).write(_kryo, o, protoA1); - byte[] serializedProtoA1 = outStream.toByteArray(); - - // Attempt to serialize instance 2 - outStream = new ByteArrayOutputStream(); - o = new Output(outStream, 4096); - _kryo.getSerializer(protoA1.getClass()).write(_kryo, o, protoA2); - byte[] serializedProtoA2 = outStream.toByteArray(); - - // Attempt to deserialize instance 1 - Input i = new Input(new ByteArrayInputStream(serializedProtoA1), 4096); - SampleProtoA testProtoA1 = (SampleProtoA) _kryo.getSerializer(protoA1.getClass()).read(_kryo, i, SampleProtoA.class); - - // Attempt to deserialize instance 2 - i = new Input(new ByteArrayInputStream(serializedProtoA2), 4096); - SampleProtoA testProtoA2 = (SampleProtoA) _kryo.getSerializer(protoA1.getClass()).read(_kryo, i, SampleProtoA.class); - - // Verify instance 1 - assertEquals((Integer)expectedMessageId1, (Integer)testProtoA1.getMessageId(), "MessageId is correct"); - assertEquals((String)expectedName1, (String)testProtoA1.getName(), "Name is correct"); - - // Verify instance 2 - assertEquals((Integer)expectedMessageId2, (Integer)testProtoA2.getMessageId(), "MessageId is correct"); - assertEquals((String)expectedName2, (String)testProtoA2.getName(), "Name is correct"); - } - - @Test - /** - * Verifies that the Serializer works back to back with multiple protobufs instances of different types (SampleProtoA and SampleProtoB) - */ - public void testSerializerWithMultipleInstancesDifferentTypes() throws Exception { - // Create first instance - Integer expectedMessageId = 12332; - String expectedName = "Esteban"; - SampleProtoA protoA = createSampleProtoA(expectedMessageId, expectedName); - - // Create 2nd instance - Integer expectedIdentifier = 543; - String expectedCity = "Atlanta"; - String expectedState = "Georgia"; - SampleProtoB protoB = createSampleProtoB(expectedIdentifier, expectedCity, expectedState); - - // Attempt to serialize instance 1 - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - Output o = new Output(outStream, 4096); - _kryo.getSerializer(protoA.getClass()).write(_kryo, o, protoA); - byte[] serializedProtoA = outStream.toByteArray(); - - // Attempt to serialize instance 2 - outStream = new ByteArrayOutputStream(); - o = new Output(outStream, 4096); - ProtobufSerializer protoBSerializer = new ProtobufSerializer(); - _kryo.getSerializer(protoB.getClass()).write(_kryo, o, protoB); - byte[] serializedProtoB = outStream.toByteArray(); - - // Attempt to deserialize instance 1 - Input i = new Input(new ByteArrayInputStream(serializedProtoA), 4096); - SampleProtoA testProtoA = (SampleProtoA) _kryo.getSerializer(protoA.getClass()).read(_kryo, i, SampleProtoA.class); - - // Attempt to deserialize instance 2 - i = new Input(new ByteArrayInputStream(serializedProtoB), 4096); - SampleProtoB testProtoB = (SampleProtoB) _kryo.getSerializer(protoB.getClass()).read(_kryo, i, SampleProtoB.class); - - // Verify instance 1 - assertEquals((Integer)expectedMessageId, (Integer)testProtoA.getMessageId(), "MessageId is correct"); - assertEquals((String)expectedName, (String)testProtoA.getName(), "Name is correct"); - - // Verify instance 2 - assertEquals((Integer)expectedIdentifier, (Integer)testProtoB.getIdentifier(), "Identifier is correct"); - assertEquals((String)expectedCity, (String)testProtoB.getCity(), "City is correct"); - assertEquals((String)expectedState, (String)testProtoB.getState(), "State is correct"); - } - - @Test - public void testGetAcceptsNull() throws Exception { - ProtobufSerializer serializer = new ProtobufSerializer(); - assertTrue(serializer.getAcceptsNull(), "Accepts null"); - } - - @Test - public void testNull() { - SampleProtoA sampleProtoA = null; - - // Attempt to serialize null - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - Output o = new Output(outStream, 4096); - _kryo.getSerializer(SampleProtoA.class).write(_kryo, o, sampleProtoA); - byte[] serializedNullValue = outStream.toByteArray(); - - // Attempt to deserialize - Input i = new Input(new ByteArrayInputStream(serializedNullValue), 4096); - SampleProtoA testNullProto = (SampleProtoA) _kryo.getSerializer(SampleProtoA.class).read(_kryo, i, SampleProtoA.class); - assertNull(testNullProto); - } - - private SampleProtoA createSampleProtoA(Integer messageId, String name) { - // Create builder - SampleProtoA.Builder builder = SampleProtoA.newBuilder(); - builder.setMessageId(messageId); - builder.setName(name); - - // Build protobuf - return builder.build(); - } - - private SampleProtoB createSampleProtoB(Integer identifier, String city, String state) { - // Create builder - SampleProtoB.Builder builder = SampleProtoB.newBuilder(); - builder.setIdentifier(identifier); - builder.setCity(city); - builder.setState(state); - - // Build protobuf - return builder.build(); - } -} \ No newline at end of file + private Kryo _kryo; + + @BeforeTest + public void setUp() { + _kryo = new Kryo(); + _kryo.register(SampleProtoA.class, new ProtobufSerializer()); + _kryo.register(SampleProtoB.class, new ProtobufSerializer()); + } + + /** + * Verifies that the Serializer works over a single Protobuf object + */ + @Test + public void testSerializerWithProtoA() { + Integer expectedMessageId = 12332; + String expectedName = "Esteban"; + + SampleProtoA protoA = createSampleProtoA(expectedMessageId, expectedName); + + // Attempt to serialize + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + Output o = new Output(outStream, 4096); + _kryo.getSerializer(protoA.getClass()).write(_kryo, o, protoA); + + // Attempt to deserialize + Input i = new Input(new ByteArrayInputStream(outStream.toByteArray()), 4096); + SampleProtoA verifyProtoA = + (SampleProtoA) _kryo.getSerializer(protoA.getClass()).read(_kryo, i, SampleProtoA.class); + + // Verify it + assertEquals(expectedMessageId, (Integer) verifyProtoA.getMessageId(), "MessageId is correct"); + assertEquals(expectedName, verifyProtoA.getName(), "Name is correct"); + } + + /** + * Verifies that the Serializer works back to back with multiple protobufs instances of the same type (SampleProtoA) + */ + @Test + public void testSerializerWithMultipleInstances() { + // Create first instance + Integer expectedMessageId1 = 12332; + String expectedName1 = "Esteban"; + SampleProtoA protoA1 = createSampleProtoA(expectedMessageId1, expectedName1); + + // Create 2nd instance + Integer expectedMessageId2 = 531; + String expectedName2 = "Bergo"; + SampleProtoA protoA2 = createSampleProtoA(expectedMessageId2, expectedName2); + + // Attempt to serialize instance 1 + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + Output o = new Output(outStream, 4096); + _kryo.getSerializer(protoA1.getClass()).write(_kryo, o, protoA1); + byte[] serializedProtoA1 = outStream.toByteArray(); + + // Attempt to serialize instance 2 + outStream = new ByteArrayOutputStream(); + o = new Output(outStream, 4096); + _kryo.getSerializer(protoA1.getClass()).write(_kryo, o, protoA2); + byte[] serializedProtoA2 = outStream.toByteArray(); + + // Attempt to deserialize instance 1 + Input i = new Input(new ByteArrayInputStream(serializedProtoA1), 4096); + SampleProtoA testProtoA1 = + (SampleProtoA) _kryo.getSerializer(protoA1.getClass()).read(_kryo, i, SampleProtoA.class); + + // Attempt to deserialize instance 2 + i = new Input(new ByteArrayInputStream(serializedProtoA2), 4096); + SampleProtoA testProtoA2 = + (SampleProtoA) _kryo.getSerializer(protoA1.getClass()).read(_kryo, i, SampleProtoA.class); + + // Verify instance 1 + assertEquals(expectedMessageId1, (Integer) testProtoA1.getMessageId(), "MessageId is correct"); + assertEquals(expectedName1, testProtoA1.getName(), "Name is correct"); + + // Verify instance 2 + assertEquals(expectedMessageId2, (Integer) testProtoA2.getMessageId(), "MessageId is correct"); + assertEquals(expectedName2, testProtoA2.getName(), "Name is correct"); + } + + /** + * Verifies that the Serializer works back to back with multiple protobufs instances of different types (SampleProtoA and SampleProtoB) + */ + @Test + public void testSerializerWithMultipleInstancesDifferentTypes() { + // Create first instance + Integer expectedMessageId = 12332; + String expectedName = "Esteban"; + SampleProtoA protoA = createSampleProtoA(expectedMessageId, expectedName); + + // Create 2nd instance + Integer expectedIdentifier = 543; + String expectedCity = "Atlanta"; + String expectedState = "Georgia"; + SampleProtoB protoB = createSampleProtoB(expectedIdentifier, expectedCity, expectedState); + + // Attempt to serialize instance 1 + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + Output o = new Output(outStream, 4096); + _kryo.getSerializer(protoA.getClass()).write(_kryo, o, protoA); + byte[] serializedProtoA = outStream.toByteArray(); + + // Attempt to serialize instance 2 + outStream = new ByteArrayOutputStream(); + o = new Output(outStream, 4096); + _kryo.getSerializer(protoB.getClass()).write(_kryo, o, protoB); + byte[] serializedProtoB = outStream.toByteArray(); + + // Attempt to deserialize instance 1 + Input i = new Input(new ByteArrayInputStream(serializedProtoA), 4096); + SampleProtoA testProtoA = + (SampleProtoA) _kryo.getSerializer(protoA.getClass()).read(_kryo, i, SampleProtoA.class); + + // Attempt to deserialize instance 2 + i = new Input(new ByteArrayInputStream(serializedProtoB), 4096); + SampleProtoB testProtoB = + (SampleProtoB) _kryo.getSerializer(protoB.getClass()).read(_kryo, i, SampleProtoB.class); + + // Verify instance 1 + assertEquals(expectedMessageId, (Integer) testProtoA.getMessageId(), "MessageId is correct"); + assertEquals(expectedName, testProtoA.getName(), "Name is correct"); + + // Verify instance 2 + assertEquals(expectedIdentifier, (Integer) testProtoB.getIdentifier(), "Identifier is correct"); + assertEquals(expectedCity, testProtoB.getCity(), "City is correct"); + assertEquals(expectedState, testProtoB.getState(), "State is correct"); + } + + @Test + public void testGetAcceptsNull() { + ProtobufSerializer serializer = new ProtobufSerializer(); + assertTrue(serializer.getAcceptsNull(), "Accepts null"); + } + + @Test + public void testNull() { + // Attempt to serialize null + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + Output o = new Output(outStream, 4096); + _kryo.getSerializer(SampleProtoA.class).write(_kryo, o, null); + byte[] serializedNullValue = outStream.toByteArray(); + + // Attempt to deserialize + Input i = new Input(new ByteArrayInputStream(serializedNullValue), 4096); + SampleProtoA testNullProto = + (SampleProtoA) _kryo.getSerializer(SampleProtoA.class).read(_kryo, i, SampleProtoA.class); + assertNull(testNullProto); + } + + private SampleProtoA createSampleProtoA(Integer messageId, String name) { + // Create builder + SampleProtoA.Builder builder = SampleProtoA.newBuilder(); + builder.setMessageId(messageId); + builder.setName(name); + + // Build protobuf + return builder.build(); + } + + private SampleProtoB createSampleProtoB(Integer identifier, String city, String state) { + // Create builder + SampleProtoB.Builder builder = SampleProtoB.newBuilder(); + builder.setIdentifier(identifier); + builder.setCity(city); + builder.setState(state); + + // Build protobuf + return builder.build(); + } +} diff --git a/src/test/java/de/javakaffee/kryoserializers/protobuf/SampleProtoAOuterClass.java b/src/test/java/de/javakaffee/kryoserializers/protobuf/SampleProtoAOuterClass.java deleted file mode 100644 index 59103e48..00000000 --- a/src/test/java/de/javakaffee/kryoserializers/protobuf/SampleProtoAOuterClass.java +++ /dev/null @@ -1,605 +0,0 @@ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: SampleProtoA.proto - -package de.javakaffee.kryoserializers.protobuf; - -public final class SampleProtoAOuterClass { - private SampleProtoAOuterClass() {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - } - public interface SampleProtoAOrBuilder extends - // @@protoc_insertion_point(interface_extends:ProtocolBuffers.SampleProtoA) - com.google.protobuf.MessageOrBuilder { - - /** - * optional string name = 1; - */ - boolean hasName(); - /** - * optional string name = 1; - */ - java.lang.String getName(); - /** - * optional string name = 1; - */ - com.google.protobuf.ByteString - getNameBytes(); - - /** - * optional uint32 message_id = 2; - */ - boolean hasMessageId(); - /** - * optional uint32 message_id = 2; - */ - int getMessageId(); - } - /** - * Protobuf type {@code ProtocolBuffers.SampleProtoA} - */ - public static final class SampleProtoA extends - com.google.protobuf.GeneratedMessage implements - // @@protoc_insertion_point(message_implements:ProtocolBuffers.SampleProtoA) - SampleProtoAOrBuilder { - // Use SampleProtoA.newBuilder() to construct. - private SampleProtoA(com.google.protobuf.GeneratedMessage.Builder builder) { - super(builder); - this.unknownFields = builder.getUnknownFields(); - } - private SampleProtoA(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } - - private static final SampleProtoA defaultInstance; - public static SampleProtoA getDefaultInstance() { - return defaultInstance; - } - - public SampleProtoA getDefaultInstanceForType() { - return defaultInstance; - } - - private final com.google.protobuf.UnknownFieldSet unknownFields; - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return this.unknownFields; - } - private SampleProtoA( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - initFields(); - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownField(input, unknownFields, - extensionRegistry, tag)) { - done = true; - } - break; - } - case 10: { - com.google.protobuf.ByteString bs = input.readBytes(); - bitField0_ |= 0x00000001; - name_ = bs; - break; - } - case 16: { - bitField0_ |= 0x00000002; - messageId_ = input.readUInt32(); - break; - } - } - } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e.getMessage()).setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } - } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.internal_static_ProtocolBuffers_SampleProtoA_descriptor; - } - - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.internal_static_ProtocolBuffers_SampleProtoA_fieldAccessorTable - .ensureFieldAccessorsInitialized( - de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA.class, de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA.Builder.class); - } - - public static com.google.protobuf.Parser PARSER = - new com.google.protobuf.AbstractParser() { - public SampleProtoA parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new SampleProtoA(input, extensionRegistry); - } - }; - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - private int bitField0_; - public static final int NAME_FIELD_NUMBER = 1; - private java.lang.Object name_; - /** - * optional string name = 1; - */ - public boolean hasName() { - return ((bitField0_ & 0x00000001) == 0x00000001); - } - /** - * optional string name = 1; - */ - public java.lang.String getName() { - java.lang.Object ref = name_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - name_ = s; - } - return s; - } - } - /** - * optional string name = 1; - */ - public com.google.protobuf.ByteString - getNameBytes() { - java.lang.Object ref = name_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - name_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - public static final int MESSAGE_ID_FIELD_NUMBER = 2; - private int messageId_; - /** - * optional uint32 message_id = 2; - */ - public boolean hasMessageId() { - return ((bitField0_ & 0x00000002) == 0x00000002); - } - /** - * optional uint32 message_id = 2; - */ - public int getMessageId() { - return messageId_; - } - - private void initFields() { - name_ = ""; - messageId_ = 0; - } - private byte memoizedIsInitialized = -1; - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; - - memoizedIsInitialized = 1; - return true; - } - - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - getSerializedSize(); - if (((bitField0_ & 0x00000001) == 0x00000001)) { - output.writeBytes(1, getNameBytes()); - } - if (((bitField0_ & 0x00000002) == 0x00000002)) { - output.writeUInt32(2, messageId_); - } - getUnknownFields().writeTo(output); - } - - private int memoizedSerializedSize = -1; - public int getSerializedSize() { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (((bitField0_ & 0x00000001) == 0x00000001)) { - size += com.google.protobuf.CodedOutputStream - .computeBytesSize(1, getNameBytes()); - } - if (((bitField0_ & 0x00000002) == 0x00000002)) { - size += com.google.protobuf.CodedOutputStream - .computeUInt32Size(2, messageId_); - } - size += getUnknownFields().getSerializedSize(); - memoizedSerializedSize = size; - return size; - } - - private static final long serialVersionUID = 0L; - @java.lang.Override - protected java.lang.Object writeReplace() - throws java.io.ObjectStreamException { - return super.writeReplace(); - } - - public static de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA parseFrom(java.io.InputStream input) - throws java.io.IOException { - return PARSER.parseFrom(input); - } - public static de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseFrom(input, extensionRegistry); - } - public static de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return PARSER.parseDelimitedFrom(input); - } - public static de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseDelimitedFrom(input, extensionRegistry); - } - public static de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return PARSER.parseFrom(input); - } - public static de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseFrom(input, extensionRegistry); - } - - public static Builder newBuilder() { return Builder.create(); } - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder(de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA prototype) { - return newBuilder().mergeFrom(prototype); - } - public Builder toBuilder() { return newBuilder(this); } - - @java.lang.Override - protected Builder newBuilderForType( - com.google.protobuf.GeneratedMessage.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } - /** - * Protobuf type {@code ProtocolBuffers.SampleProtoA} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder implements - // @@protoc_insertion_point(builder_implements:ProtocolBuffers.SampleProtoA) - de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoAOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.internal_static_ProtocolBuffers_SampleProtoA_descriptor; - } - - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.internal_static_ProtocolBuffers_SampleProtoA_fieldAccessorTable - .ensureFieldAccessorsInitialized( - de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA.class, de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA.Builder.class); - } - - // Construct using de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder( - com.google.protobuf.GeneratedMessage.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { - } - } - private static Builder create() { - return new Builder(); - } - - public Builder clear() { - super.clear(); - name_ = ""; - bitField0_ = (bitField0_ & ~0x00000001); - messageId_ = 0; - bitField0_ = (bitField0_ & ~0x00000002); - return this; - } - - public Builder clone() { - return create().mergeFrom(buildPartial()); - } - - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.internal_static_ProtocolBuffers_SampleProtoA_descriptor; - } - - public de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA getDefaultInstanceForType() { - return de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA.getDefaultInstance(); - } - - public de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA build() { - de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA buildPartial() { - de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA result = new de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA(this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - if (((from_bitField0_ & 0x00000001) == 0x00000001)) { - to_bitField0_ |= 0x00000001; - } - result.name_ = name_; - if (((from_bitField0_ & 0x00000002) == 0x00000002)) { - to_bitField0_ |= 0x00000002; - } - result.messageId_ = messageId_; - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA) { - return mergeFrom((de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA)other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA other) { - if (other == de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA.getDefaultInstance()) return this; - if (other.hasName()) { - bitField0_ |= 0x00000001; - name_ = other.name_; - onChanged(); - } - if (other.hasMessageId()) { - setMessageId(other.getMessageId()); - } - this.mergeUnknownFields(other.getUnknownFields()); - return this; - } - - public final boolean isInitialized() { - return true; - } - - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (de.javakaffee.kryoserializers.protobuf.SampleProtoAOuterClass.SampleProtoA) e.getUnfinishedMessage(); - throw e; - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - private int bitField0_; - - private java.lang.Object name_ = ""; - /** - * optional string name = 1; - */ - public boolean hasName() { - return ((bitField0_ & 0x00000001) == 0x00000001); - } - /** - * optional string name = 1; - */ - public java.lang.String getName() { - java.lang.Object ref = name_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - name_ = s; - } - return s; - } else { - return (java.lang.String) ref; - } - } - /** - * optional string name = 1; - */ - public com.google.protobuf.ByteString - getNameBytes() { - java.lang.Object ref = name_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - name_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - /** - * optional string name = 1; - */ - public Builder setName( - java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000001; - name_ = value; - onChanged(); - return this; - } - /** - * optional string name = 1; - */ - public Builder clearName() { - bitField0_ = (bitField0_ & ~0x00000001); - name_ = getDefaultInstance().getName(); - onChanged(); - return this; - } - /** - * optional string name = 1; - */ - public Builder setNameBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000001; - name_ = value; - onChanged(); - return this; - } - - private int messageId_ ; - /** - * optional uint32 message_id = 2; - */ - public boolean hasMessageId() { - return ((bitField0_ & 0x00000002) == 0x00000002); - } - /** - * optional uint32 message_id = 2; - */ - public int getMessageId() { - return messageId_; - } - /** - * optional uint32 message_id = 2; - */ - public Builder setMessageId(int value) { - bitField0_ |= 0x00000002; - messageId_ = value; - onChanged(); - return this; - } - /** - * optional uint32 message_id = 2; - */ - public Builder clearMessageId() { - bitField0_ = (bitField0_ & ~0x00000002); - messageId_ = 0; - onChanged(); - return this; - } - - // @@protoc_insertion_point(builder_scope:ProtocolBuffers.SampleProtoA) - } - - static { - defaultInstance = new SampleProtoA(true); - defaultInstance.initFields(); - } - - // @@protoc_insertion_point(class_scope:ProtocolBuffers.SampleProtoA) - } - - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_ProtocolBuffers_SampleProtoA_descriptor; - private static - com.google.protobuf.GeneratedMessage.FieldAccessorTable - internal_static_ProtocolBuffers_SampleProtoA_fieldAccessorTable; - - public static com.google.protobuf.Descriptors.FileDescriptor - getDescriptor() { - return descriptor; - } - private static com.google.protobuf.Descriptors.FileDescriptor - descriptor; - static { - java.lang.String[] descriptorData = { - "\n\022SampleProtoA.proto\022\017ProtocolBuffers\"0\n" + - "\014SampleProtoA\022\014\n\004name\030\001 \001(\t\022\022\n\nmessage_i" + - "d\030\002 \001(\rB@\n&de.javakaffee.kryoserializers" + - ".protobufB\026SampleProtoAOuterClass" - }; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = - new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } - }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom(descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[] { - }, assigner); - internal_static_ProtocolBuffers_SampleProtoA_descriptor = - getDescriptor().getMessageTypes().get(0); - internal_static_ProtocolBuffers_SampleProtoA_fieldAccessorTable = new - com.google.protobuf.GeneratedMessage.FieldAccessorTable( - internal_static_ProtocolBuffers_SampleProtoA_descriptor, - new java.lang.String[] { "Name", "MessageId", }); - } - - // @@protoc_insertion_point(outer_class_scope) -} diff --git a/src/test/java/de/javakaffee/kryoserializers/protobuf/SampleProtoBOuterClass.java b/src/test/java/de/javakaffee/kryoserializers/protobuf/SampleProtoBOuterClass.java deleted file mode 100644 index cdc0d424..00000000 --- a/src/test/java/de/javakaffee/kryoserializers/protobuf/SampleProtoBOuterClass.java +++ /dev/null @@ -1,787 +0,0 @@ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: SampleProtoB.proto - -package de.javakaffee.kryoserializers.protobuf; - -public final class SampleProtoBOuterClass { - private SampleProtoBOuterClass() {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - } - public interface SampleProtoBOrBuilder extends - // @@protoc_insertion_point(interface_extends:ProtocolBuffers.SampleProtoB) - com.google.protobuf.MessageOrBuilder { - - /** - * required uint32 identifier = 1; - */ - boolean hasIdentifier(); - /** - * required uint32 identifier = 1; - */ - int getIdentifier(); - - /** - * required string state = 2; - */ - boolean hasState(); - /** - * required string state = 2; - */ - java.lang.String getState(); - /** - * required string state = 2; - */ - com.google.protobuf.ByteString - getStateBytes(); - - /** - * required string city = 3; - */ - boolean hasCity(); - /** - * required string city = 3; - */ - java.lang.String getCity(); - /** - * required string city = 3; - */ - com.google.protobuf.ByteString - getCityBytes(); - } - /** - * Protobuf type {@code ProtocolBuffers.SampleProtoB} - */ - public static final class SampleProtoB extends - com.google.protobuf.GeneratedMessage implements - // @@protoc_insertion_point(message_implements:ProtocolBuffers.SampleProtoB) - SampleProtoBOrBuilder { - // Use SampleProtoB.newBuilder() to construct. - private SampleProtoB(com.google.protobuf.GeneratedMessage.Builder builder) { - super(builder); - this.unknownFields = builder.getUnknownFields(); - } - private SampleProtoB(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } - - private static final SampleProtoB defaultInstance; - public static SampleProtoB getDefaultInstance() { - return defaultInstance; - } - - public SampleProtoB getDefaultInstanceForType() { - return defaultInstance; - } - - private final com.google.protobuf.UnknownFieldSet unknownFields; - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return this.unknownFields; - } - private SampleProtoB( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - initFields(); - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownField(input, unknownFields, - extensionRegistry, tag)) { - done = true; - } - break; - } - case 8: { - bitField0_ |= 0x00000001; - identifier_ = input.readUInt32(); - break; - } - case 18: { - com.google.protobuf.ByteString bs = input.readBytes(); - bitField0_ |= 0x00000002; - state_ = bs; - break; - } - case 26: { - com.google.protobuf.ByteString bs = input.readBytes(); - bitField0_ |= 0x00000004; - city_ = bs; - break; - } - } - } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e.getMessage()).setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } - } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.internal_static_ProtocolBuffers_SampleProtoB_descriptor; - } - - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.internal_static_ProtocolBuffers_SampleProtoB_fieldAccessorTable - .ensureFieldAccessorsInitialized( - de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB.class, de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB.Builder.class); - } - - public static com.google.protobuf.Parser PARSER = - new com.google.protobuf.AbstractParser() { - public SampleProtoB parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new SampleProtoB(input, extensionRegistry); - } - }; - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - private int bitField0_; - public static final int IDENTIFIER_FIELD_NUMBER = 1; - private int identifier_; - /** - * required uint32 identifier = 1; - */ - public boolean hasIdentifier() { - return ((bitField0_ & 0x00000001) == 0x00000001); - } - /** - * required uint32 identifier = 1; - */ - public int getIdentifier() { - return identifier_; - } - - public static final int STATE_FIELD_NUMBER = 2; - private java.lang.Object state_; - /** - * required string state = 2; - */ - public boolean hasState() { - return ((bitField0_ & 0x00000002) == 0x00000002); - } - /** - * required string state = 2; - */ - public java.lang.String getState() { - java.lang.Object ref = state_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - state_ = s; - } - return s; - } - } - /** - * required string state = 2; - */ - public com.google.protobuf.ByteString - getStateBytes() { - java.lang.Object ref = state_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - state_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - public static final int CITY_FIELD_NUMBER = 3; - private java.lang.Object city_; - /** - * required string city = 3; - */ - public boolean hasCity() { - return ((bitField0_ & 0x00000004) == 0x00000004); - } - /** - * required string city = 3; - */ - public java.lang.String getCity() { - java.lang.Object ref = city_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - city_ = s; - } - return s; - } - } - /** - * required string city = 3; - */ - public com.google.protobuf.ByteString - getCityBytes() { - java.lang.Object ref = city_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - city_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - private void initFields() { - identifier_ = 0; - state_ = ""; - city_ = ""; - } - private byte memoizedIsInitialized = -1; - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; - - if (!hasIdentifier()) { - memoizedIsInitialized = 0; - return false; - } - if (!hasState()) { - memoizedIsInitialized = 0; - return false; - } - if (!hasCity()) { - memoizedIsInitialized = 0; - return false; - } - memoizedIsInitialized = 1; - return true; - } - - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - getSerializedSize(); - if (((bitField0_ & 0x00000001) == 0x00000001)) { - output.writeUInt32(1, identifier_); - } - if (((bitField0_ & 0x00000002) == 0x00000002)) { - output.writeBytes(2, getStateBytes()); - } - if (((bitField0_ & 0x00000004) == 0x00000004)) { - output.writeBytes(3, getCityBytes()); - } - getUnknownFields().writeTo(output); - } - - private int memoizedSerializedSize = -1; - public int getSerializedSize() { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (((bitField0_ & 0x00000001) == 0x00000001)) { - size += com.google.protobuf.CodedOutputStream - .computeUInt32Size(1, identifier_); - } - if (((bitField0_ & 0x00000002) == 0x00000002)) { - size += com.google.protobuf.CodedOutputStream - .computeBytesSize(2, getStateBytes()); - } - if (((bitField0_ & 0x00000004) == 0x00000004)) { - size += com.google.protobuf.CodedOutputStream - .computeBytesSize(3, getCityBytes()); - } - size += getUnknownFields().getSerializedSize(); - memoizedSerializedSize = size; - return size; - } - - private static final long serialVersionUID = 0L; - @java.lang.Override - protected java.lang.Object writeReplace() - throws java.io.ObjectStreamException { - return super.writeReplace(); - } - - public static de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB parseFrom(java.io.InputStream input) - throws java.io.IOException { - return PARSER.parseFrom(input); - } - public static de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseFrom(input, extensionRegistry); - } - public static de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return PARSER.parseDelimitedFrom(input); - } - public static de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseDelimitedFrom(input, extensionRegistry); - } - public static de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return PARSER.parseFrom(input); - } - public static de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return PARSER.parseFrom(input, extensionRegistry); - } - - public static Builder newBuilder() { return Builder.create(); } - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder(de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB prototype) { - return newBuilder().mergeFrom(prototype); - } - public Builder toBuilder() { return newBuilder(this); } - - @java.lang.Override - protected Builder newBuilderForType( - com.google.protobuf.GeneratedMessage.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } - /** - * Protobuf type {@code ProtocolBuffers.SampleProtoB} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder implements - // @@protoc_insertion_point(builder_implements:ProtocolBuffers.SampleProtoB) - de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoBOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.internal_static_ProtocolBuffers_SampleProtoB_descriptor; - } - - protected com.google.protobuf.GeneratedMessage.FieldAccessorTable - internalGetFieldAccessorTable() { - return de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.internal_static_ProtocolBuffers_SampleProtoB_fieldAccessorTable - .ensureFieldAccessorsInitialized( - de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB.class, de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB.Builder.class); - } - - // Construct using de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder( - com.google.protobuf.GeneratedMessage.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { - } - } - private static Builder create() { - return new Builder(); - } - - public Builder clear() { - super.clear(); - identifier_ = 0; - bitField0_ = (bitField0_ & ~0x00000001); - state_ = ""; - bitField0_ = (bitField0_ & ~0x00000002); - city_ = ""; - bitField0_ = (bitField0_ & ~0x00000004); - return this; - } - - public Builder clone() { - return create().mergeFrom(buildPartial()); - } - - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.internal_static_ProtocolBuffers_SampleProtoB_descriptor; - } - - public de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB getDefaultInstanceForType() { - return de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB.getDefaultInstance(); - } - - public de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB build() { - de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB buildPartial() { - de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB result = new de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB(this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - if (((from_bitField0_ & 0x00000001) == 0x00000001)) { - to_bitField0_ |= 0x00000001; - } - result.identifier_ = identifier_; - if (((from_bitField0_ & 0x00000002) == 0x00000002)) { - to_bitField0_ |= 0x00000002; - } - result.state_ = state_; - if (((from_bitField0_ & 0x00000004) == 0x00000004)) { - to_bitField0_ |= 0x00000004; - } - result.city_ = city_; - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB) { - return mergeFrom((de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB)other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB other) { - if (other == de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB.getDefaultInstance()) return this; - if (other.hasIdentifier()) { - setIdentifier(other.getIdentifier()); - } - if (other.hasState()) { - bitField0_ |= 0x00000002; - state_ = other.state_; - onChanged(); - } - if (other.hasCity()) { - bitField0_ |= 0x00000004; - city_ = other.city_; - onChanged(); - } - this.mergeUnknownFields(other.getUnknownFields()); - return this; - } - - public final boolean isInitialized() { - if (!hasIdentifier()) { - - return false; - } - if (!hasState()) { - - return false; - } - if (!hasCity()) { - - return false; - } - return true; - } - - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (de.javakaffee.kryoserializers.protobuf.SampleProtoBOuterClass.SampleProtoB) e.getUnfinishedMessage(); - throw e; - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - private int bitField0_; - - private int identifier_ ; - /** - * required uint32 identifier = 1; - */ - public boolean hasIdentifier() { - return ((bitField0_ & 0x00000001) == 0x00000001); - } - /** - * required uint32 identifier = 1; - */ - public int getIdentifier() { - return identifier_; - } - /** - * required uint32 identifier = 1; - */ - public Builder setIdentifier(int value) { - bitField0_ |= 0x00000001; - identifier_ = value; - onChanged(); - return this; - } - /** - * required uint32 identifier = 1; - */ - public Builder clearIdentifier() { - bitField0_ = (bitField0_ & ~0x00000001); - identifier_ = 0; - onChanged(); - return this; - } - - private java.lang.Object state_ = ""; - /** - * required string state = 2; - */ - public boolean hasState() { - return ((bitField0_ & 0x00000002) == 0x00000002); - } - /** - * required string state = 2; - */ - public java.lang.String getState() { - java.lang.Object ref = state_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - state_ = s; - } - return s; - } else { - return (java.lang.String) ref; - } - } - /** - * required string state = 2; - */ - public com.google.protobuf.ByteString - getStateBytes() { - java.lang.Object ref = state_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - state_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - /** - * required string state = 2; - */ - public Builder setState( - java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000002; - state_ = value; - onChanged(); - return this; - } - /** - * required string state = 2; - */ - public Builder clearState() { - bitField0_ = (bitField0_ & ~0x00000002); - state_ = getDefaultInstance().getState(); - onChanged(); - return this; - } - /** - * required string state = 2; - */ - public Builder setStateBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000002; - state_ = value; - onChanged(); - return this; - } - - private java.lang.Object city_ = ""; - /** - * required string city = 3; - */ - public boolean hasCity() { - return ((bitField0_ & 0x00000004) == 0x00000004); - } - /** - * required string city = 3; - */ - public java.lang.String getCity() { - java.lang.Object ref = city_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - if (bs.isValidUtf8()) { - city_ = s; - } - return s; - } else { - return (java.lang.String) ref; - } - } - /** - * required string city = 3; - */ - public com.google.protobuf.ByteString - getCityBytes() { - java.lang.Object ref = city_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); - city_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - /** - * required string city = 3; - */ - public Builder setCity( - java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000004; - city_ = value; - onChanged(); - return this; - } - /** - * required string city = 3; - */ - public Builder clearCity() { - bitField0_ = (bitField0_ & ~0x00000004); - city_ = getDefaultInstance().getCity(); - onChanged(); - return this; - } - /** - * required string city = 3; - */ - public Builder setCityBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - bitField0_ |= 0x00000004; - city_ = value; - onChanged(); - return this; - } - - // @@protoc_insertion_point(builder_scope:ProtocolBuffers.SampleProtoB) - } - - static { - defaultInstance = new SampleProtoB(true); - defaultInstance.initFields(); - } - - // @@protoc_insertion_point(class_scope:ProtocolBuffers.SampleProtoB) - } - - private static final com.google.protobuf.Descriptors.Descriptor - internal_static_ProtocolBuffers_SampleProtoB_descriptor; - private static - com.google.protobuf.GeneratedMessage.FieldAccessorTable - internal_static_ProtocolBuffers_SampleProtoB_fieldAccessorTable; - - public static com.google.protobuf.Descriptors.FileDescriptor - getDescriptor() { - return descriptor; - } - private static com.google.protobuf.Descriptors.FileDescriptor - descriptor; - static { - java.lang.String[] descriptorData = { - "\n\022SampleProtoB.proto\022\017ProtocolBuffers\"?\n" + - "\014SampleProtoB\022\022\n\nidentifier\030\001 \002(\r\022\r\n\005sta" + - "te\030\002 \002(\t\022\014\n\004city\030\003 \002(\tB@\n&de.javakaffee." + - "kryoserializers.protobufB\026SampleProtoBOu" + - "terClass" - }; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = - new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } - }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom(descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[] { - }, assigner); - internal_static_ProtocolBuffers_SampleProtoB_descriptor = - getDescriptor().getMessageTypes().get(0); - internal_static_ProtocolBuffers_SampleProtoB_fieldAccessorTable = new - com.google.protobuf.GeneratedMessage.FieldAccessorTable( - internal_static_ProtocolBuffers_SampleProtoB_descriptor, - new java.lang.String[] { "Identifier", "State", "City", }); - } - - // @@protoc_insertion_point(outer_class_scope) -} diff --git a/src/test/java/de/javakaffee/kryoserializers/wicket/MiniMapSerializerTest.java b/src/test/java/de/javakaffee/kryoserializers/wicket/MiniMapSerializerTest.java index a8a2fd4e..1d4a101c 100644 --- a/src/test/java/de/javakaffee/kryoserializers/wicket/MiniMapSerializerTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/wicket/MiniMapSerializerTest.java @@ -1,5 +1,5 @@ /* -* Copyright 2010 Martin Grotzke + * Copyright 2018 Martin Grotzke * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,67 +32,67 @@ /** * Test for {@link JodaDateTimeSerializer}. - * + * * @author Martin Grotzke */ public class MiniMapSerializerTest { - - private Kryo _kryo; - @BeforeTest - protected void beforeTest() { - _kryo = new Kryo(); - _kryo.register( MiniMap.class, new MiniMapSerializer() ); - } + private Kryo _kryo; + + @BeforeTest + protected void beforeTest() { + _kryo = new Kryo(); + _kryo.register(MiniMap.class, new MiniMapSerializer()); + } + + @Test(enabled = true) + public void testMiniMapEmpty() { + final MiniMap obj = new MiniMap(0); + final byte[] serialized = serialize(_kryo, obj); + final MiniMap deserialized = deserialize(_kryo, serialized, MiniMap.class); + Assert.assertEquals(deserialized.size(), obj.size()); + } - @Test( enabled = true ) - public void testMiniMapEmpty() { - final MiniMap obj = new MiniMap( 0 ); - final byte[] serialized = serialize( _kryo, obj ); - final MiniMap deserialized = deserialize( _kryo, serialized, MiniMap.class ); - Assert.assertEquals( deserialized.size(), obj.size() ); - } + @Test(enabled = true) + public void testMiniMapExactNumberOfEntries() { + final MiniMap obj = new MiniMap(1); + obj.put("foo", "bar"); + final byte[] serialized = serialize(_kryo, obj); + final MiniMap deserialized = deserialize(_kryo, serialized, MiniMap.class); + Assert.assertEquals(deserialized.size(), obj.size()); + final Entry deserializedNext = deserialized.entrySet().iterator().next(); + final Entry origNext = obj.entrySet().iterator().next(); + Assert.assertEquals(deserializedNext.getKey(), origNext.getKey()); + Assert.assertEquals(deserializedNext.getValue(), origNext.getValue()); + } - @Test( enabled = true ) - public void testMiniMapExactNumberOfEntries() { - final MiniMap obj = new MiniMap( 1 ); - obj.put( "foo", "bar" ); - final byte[] serialized = serialize( _kryo, obj ); - final MiniMap deserialized = deserialize( _kryo, serialized, MiniMap.class ); - Assert.assertEquals( deserialized.size(), obj.size() ); - final Entry deserializedNext = deserialized.entrySet().iterator().next(); - final Entry origNext = obj.entrySet().iterator().next(); - Assert.assertEquals( deserializedNext.getKey(), origNext.getKey() ); - Assert.assertEquals( deserializedNext.getValue(), origNext.getValue() ); - } + @Test(enabled = true) + public void testMiniMapLessThanMaxEntries() { + final MiniMap obj = new MiniMap(2); + obj.put("foo", "bar"); + final byte[] serialized = serialize(_kryo, obj); + final MiniMap deserialized = deserialize(_kryo, serialized, MiniMap.class); + Assert.assertEquals(deserialized.size(), obj.size()); + } - @Test( enabled = true ) - public void testMiniMapLessThanMaxEntries() { - final MiniMap obj = new MiniMap( 2 ); - obj.put( "foo", "bar" ); - final byte[] serialized = serialize( _kryo, obj ); - final MiniMap deserialized = deserialize( _kryo, serialized, MiniMap.class ); - Assert.assertEquals( deserialized.size(), obj.size() ); - } + @SuppressWarnings("unchecked") + @Test(enabled = true) + public void testMiniMapAddEntriesAfterDeserialization() { + final MiniMap obj = new MiniMap(2); + obj.put("foo", "bar"); + final byte[] serialized = serialize(_kryo, obj); + final MiniMap deserialized = deserialize(_kryo, serialized, MiniMap.class); + Assert.assertEquals(deserialized.size(), obj.size()); - @SuppressWarnings("unchecked") - @Test( enabled = true ) - public void testMiniMapAddEntriesAfterDeserialization() { - final MiniMap obj = new MiniMap( 2 ); - obj.put( "foo", "bar" ); - final byte[] serialized = serialize( _kryo, obj ); - final MiniMap deserialized = deserialize( _kryo, serialized, MiniMap.class ); - Assert.assertEquals( deserialized.size(), obj.size() ); - - deserialized.put( "bar", "baz" ); - try { - deserialized.put( "this should", "fail" ); - Assert.fail( "We told the orig MiniMap to accept 2 entries at max," + - " therefore we should not be allowed to put more." ); - } catch( final RuntimeException e ) { - // this is expected - didn't use @Test.expectedExceptions - // as this would tie us to the exactly thrown exception - } - } + deserialized.put("bar", "baz"); + try { + deserialized.put("this should", "fail"); + Assert.fail("We told the orig MiniMap to accept 2 entries at max," + + " therefore we should not be allowed to put more."); + } catch (final RuntimeException e) { + // this is expected - didn't use @Test.expectedExceptions + // as this would tie us to the exactly thrown exception + } + } } diff --git a/src/test/java/de/javakaffee/kryoserializers/wicket/WicketTest.java b/src/test/java/de/javakaffee/kryoserializers/wicket/WicketTest.java index fb57f9cc..a1b4701e 100644 --- a/src/test/java/de/javakaffee/kryoserializers/wicket/WicketTest.java +++ b/src/test/java/de/javakaffee/kryoserializers/wicket/WicketTest.java @@ -1,5 +1,5 @@ /* -* Copyright 2010 Martin Grotzke + * Copyright 2018 Martin Grotzke * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,81 +41,81 @@ /** * A general test for several wicket serializations that don't require * specific serializers. - * + * * @author Martin Grotzke */ public class WicketTest { - public static final String SERIALIZED_CLASS_NAME = MarkupContainer.class.getName() + "$ChildList"; - - private Kryo _kryo; - private WicketTester _wicketTester; - - @BeforeTest - @SuppressWarnings( "unchecked" ) - protected void beforeTest() { - _kryo = new KryoReflectionFactorySupport() { - - @SuppressWarnings("rawtypes") - @Override - public Serializer getDefaultSerializer( final Class type ) { - if ( SERIALIZED_CLASS_NAME.equals( type.getName() ) ) { - return new FieldSerializer( this, type ); - } - return super.getDefaultSerializer(type); - } - - }; - _kryo.setRegistrationRequired( false ); - - final WebApplication application = new WebApplication() { - - @Override - public Class getHomePage() { - return null; - } - - }; - - _wicketTester = new WicketTester( application ); - } - - @AfterTest - protected void afterTest() { - _wicketTester.destroy(); - } - - /** - * Tests that MarkupContainer.ChildList is serialized/deserialized correctly. - * It needs ReflectionFactory support, ReferenceFieldSerializer as default - * serializer and the FieldSerializer for MarkupContainer.ChildList (instead of - * default CollectionSerializer). - * - * @throws Exception - */ - @Test( enabled = true ) - public void testMarkupContainerChildList() throws Exception { - final MarkupContainer markupContainer = new WebMarkupContainer("foo"); - markupContainer.add( new Label( "label1", "foo" ) ); - markupContainer.add( new Label( "label", "hello" ) ); - final byte[] serialized = serialize( _kryo, markupContainer ); - final MarkupContainer deserialized = deserialize( _kryo, serialized, markupContainer.getClass() ); - KryoTest.assertDeepEquals( deserialized, markupContainer ); - } - - @Test( enabled = true ) - public void testFeedbackPanel() throws Exception { - final FeedbackPanel markupContainer = new FeedbackPanel("foo"); - //markupContainer.info( "foo" ); - final Component child = markupContainer.get( 0 ); - child.isVisible(); - final byte[] serialized = serialize( _kryo, markupContainer ); - final MarkupContainer deserialized = deserialize( _kryo, serialized, markupContainer.getClass() ); - - final Component deserializedChild = deserialized.get( 0 ); - deserializedChild.isVisible(); - - KryoTest.assertDeepEquals( deserialized, markupContainer ); - } + public static final String SERIALIZED_CLASS_NAME = MarkupContainer.class.getName() + "$ChildList"; + + private Kryo _kryo; + private WicketTester _wicketTester; + + @BeforeTest + @SuppressWarnings("unchecked") + protected void beforeTest() { + _kryo = new KryoReflectionFactorySupport() { + + @SuppressWarnings("rawtypes") + @Override + public Serializer getDefaultSerializer(final Class type) { + if (SERIALIZED_CLASS_NAME.equals(type.getName())) { + return new FieldSerializer(this, type); + } + return super.getDefaultSerializer(type); + } + + }; + _kryo.setRegistrationRequired(false); + + final WebApplication application = new WebApplication() { + + @Override + public Class getHomePage() { + return null; + } + + }; + + _wicketTester = new WicketTester(application); + } + + @AfterTest + protected void afterTest() { + _wicketTester.destroy(); + } + + /** + * Tests that MarkupContainer.ChildList is serialized/deserialized correctly. + * It needs ReflectionFactory support, ReferenceFieldSerializer as default + * serializer and the FieldSerializer for MarkupContainer.ChildList (instead of + * default CollectionSerializer). + * + * @throws Exception + */ + @Test(enabled = true) + public void testMarkupContainerChildList() throws Exception { + final MarkupContainer markupContainer = new WebMarkupContainer("foo"); + markupContainer.add(new Label("label1", "foo")); + markupContainer.add(new Label("label", "hello")); + final byte[] serialized = serialize(_kryo, markupContainer); + final MarkupContainer deserialized = deserialize(_kryo, serialized, markupContainer.getClass()); + KryoTest.assertDeepEquals(deserialized, markupContainer); + } + + @Test(enabled = true) + public void testFeedbackPanel() throws Exception { + final FeedbackPanel markupContainer = new FeedbackPanel("foo"); + //markupContainer.info( "foo" ); + final Component child = markupContainer.get("feedbackul"); + child.isVisible(); + final byte[] serialized = serialize(_kryo, markupContainer); + final MarkupContainer deserialized = deserialize(_kryo, serialized, markupContainer.getClass()); + + final Component deserializedChild = deserialized.get("feedbackul"); + deserializedChild.isVisible(); + + KryoTest.assertDeepEquals(deserialized, markupContainer); + } } diff --git a/src/test/resources/SampleProtoA.proto b/src/test/proto/SampleProtoA.proto similarity index 65% rename from src/test/resources/SampleProtoA.proto rename to src/test/proto/SampleProtoA.proto index fbdfb538..6779ca82 100644 --- a/src/test/resources/SampleProtoA.proto +++ b/src/test/proto/SampleProtoA.proto @@ -1,4 +1,6 @@ -package ProtocolBuffers; // the namespace for the compiled classes +syntax = "proto2"; + +package de.javakaffee.kryoserializers.protobuf; // the namespace for the compiled classes option java_package = "de.javakaffee.kryoserializers.protobuf"; option java_outer_classname = "SampleProtoAOuterClass"; diff --git a/src/test/resources/SampleProtoB.proto b/src/test/proto/SampleProtoB.proto similarity index 68% rename from src/test/resources/SampleProtoB.proto rename to src/test/proto/SampleProtoB.proto index a5612ba0..537823ab 100644 --- a/src/test/resources/SampleProtoB.proto +++ b/src/test/proto/SampleProtoB.proto @@ -1,4 +1,6 @@ -package ProtocolBuffers; // the namespace for the compiled classes +syntax = "proto2"; + +package de.javakaffee.kryoserializers.protobuf; // the namespace for the compiled classes option java_package = "de.javakaffee.kryoserializers.protobuf"; option java_outer_classname = "SampleProtoBOuterClass";