├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── build.gradle ├── resources ├── size.png └── tps.png └── src ├── main └── java │ └── com │ └── creative │ └── commons │ └── utils │ ├── HessianCodec.java │ ├── JsonCodec.java │ ├── KryoCodec.java │ ├── MsgPackCodec.java │ └── ObjectTemplate.java └── test └── java └── com └── creative ├── commons └── utils │ ├── CodecTest.java │ ├── benchmark │ ├── BenchmarkBootstrap.java │ ├── FastJsonBenchmark.java │ ├── HessianBenchmark.java │ ├── JdkCodecBencmark.java │ ├── KryoBenchmark.java │ └── MsgPackBenchmark.java │ └── unittest │ ├── FastJsonCodecTest.java │ ├── HessianCodecTest.java │ ├── JdkCodecTest.java │ ├── KryoCodecTest.java │ └── MsgPackCodecTest.java └── model ├── Certificates.java ├── Father.java ├── Message.java └── Son.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | .gradle/ 3 | build/ 4 | .idea/ 5 | *.iml 6 | 7 | # Mobile Tools for Java (J2ME) 8 | .mtj.tmp/ 9 | 10 | # Package Files # 11 | *.jar 12 | *.war 13 | *.ear 14 | 15 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 16 | hs_err_pid* 17 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk8 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | jvm-serializer[![Build Status](https://travis-ci.org/vongosling/jvm-serializer.svg?branch=master)](https://travis-ci.org/vongosling/jvm-serializer) 2 | ============== 3 | ### Description 4 | #### This project is a function and performance benchmark test for kyro4,fastjson,hessian and messagePack codec (Serialize and Deserialize).which are most popular non-schema Serialize and Deserialize tools nowadays. 5 | ### Environment 6 | #### Hardware: 7 | ##### Intel(R) Core(TM) i7 CPU @ 2.2GHz,8 core 16G memory 8 | #### Software: 9 | ##### Darwin Kernel Version 15.4.0: Fri Feb 26 22:08:05 PST 2016; root:xnu-3248.40.184~3/RELEASE_X86_64 x86_64 10 | ##### Java HotSpot(TM) 64-Bit Server VM (build 25.77-b03, mixed mode) 11 | 12 | ### Test case 13 | #### 1.Using JMH,After 10 seconds warmup iterations, do 10 times measurement iterations, each iteration costs 5 seconds. 14 | #### 2.Consider some special java type,such as BitEnum,EnumSet etc... 15 | #### Report 16 | 17 | ![Codec TPS comparison](./resources/tps.png) 18 | ![Codec size comparison](./resources/size.png) 19 | 20 | ##### If you have any good advice,please contact fengjia10@gmail.com or zhou@xinyu.im 21 | 22 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'eclipse' 3 | apply plugin: 'maven' 4 | apply plugin: 'idea' 5 | 6 | ext.projectIds = ['group': 'com.creative.commons', 'version': '0.1'] 7 | group = projectIds.group 8 | version = projectIds.version 9 | 10 | configurations { 11 | serializer { 12 | description = 'One jvm seriazlier benchmark platform.' 13 | visible = false 14 | } 15 | } 16 | configurations.serializer { 17 | resolutionStrategy { 18 | failOnVersionConflict() 19 | force('junit:junit:4.11') 20 | cacheDynamicVersionsFor(0, 'seconds') 21 | } 22 | } 23 | 24 | configurations.compile.resolutionStrategy { 25 | cacheChangingModulesFor(0, 'seconds') 26 | } 27 | 28 | ext { 29 | linkHomepage = 'https://github.com/vongosling/jvm-serializer' 30 | linkCi = 'https://github.com/vongosling/jvm-serializer/issues' 31 | linkIssue = 'https://github.com/vongosling/jvm-serializer/issues' 32 | linkScmUrl = 'https://github.com/vongosling/jvm-serializer' 33 | linkScmConnection = 'scm:git:git://github.com/vongosling/jvm-serializer.git' 34 | linkScmDevConnection = 'scm:git:ssh://git@github.com:vongosling/jvm-serializer.git' 35 | } 36 | 37 | compileJava.options*.compilerArgs = [ 38 | "-Xlint:serial", "-Xlint:varargs", "-Xlint:cast", "-Xlint:classfile", 39 | "-Xlint:dep-ann", "-Xlint:divzero", "-Xlint:empty", "-Xlint:finally", 40 | "-Xlint:overrides", "-Xlint:path", "-Xlint:processing", "-Xlint:static", 41 | "-Xlint:try", "-Xlint:fallthrough", "-Xlint:rawtypes", "-Xlint:deprecation", 42 | "-Xlint:unchecked", "-Xlint:-options", "-Werror" 43 | ] 44 | 45 | compileTestJava.options*.compilerArgs = [ 46 | "-Xlint:serial", "-Xlint:varargs", "-Xlint:cast", "-Xlint:classfile", 47 | "-Xlint:dep-ann", "-Xlint:divzero", "-Xlint:empty", "-Xlint:finally", 48 | "-Xlint:overrides", "-Xlint:path", "-Xlint:processing", "-Xlint:static", 49 | "-Xlint:try", "-Xlint:-fallthrough", "-Xlint:-rawtypes", "-Xlint:-deprecation", 50 | "-Xlint:-unchecked", "-Xlint:-options" 51 | ] 52 | 53 | compileJava { 54 | sourceCompatibility = 1.8 55 | targetCompatibility = 1.8 56 | } 57 | 58 | compileTestJava { 59 | sourceCompatibility = 1.8 60 | targetCompatibility = 1.8 61 | } 62 | 63 | jar { 64 | baseName = 'Jvm-serializer' 65 | version = '1.0' 66 | manifest { 67 | attributes 'Implementation-Title': 'Jvm serializer', 'Implementation-Version': version 68 | } 69 | } 70 | 71 | repositories { 72 | mavenCentral() 73 | } 74 | 75 | dependencies { 76 | compile group: 'com.caucho', name: 'hessian', version: '4.0.38' 77 | compile group: 'com.alibaba', name: 'fastjson', version: '1.2.15' 78 | compile group: 'com.esotericsoftware', name: 'kryo-shaded', version: '4.0.0' 79 | compile group: 'org.msgpack', name: 'msgpack', version: '0.6.12' 80 | compile group: 'org.openjdk.jmh', name: 'jmh-core', version: '1.13' 81 | compile group: 'org.openjdk.jmh', name: 'jmh-generator-annprocess', version: '1.13' 82 | //compile group: 'com.esotericsoftware.kryo', name: 'kryo', version: '2.24.0' 83 | testCompile group: 'junit', name: 'junit', version: '4.+' 84 | compile('com.google.guava:guava:18.0') 85 | //testCompile 'org.codehaus.groovy:groovy:2.3.9' 86 | } 87 | 88 | test { 89 | //systemProperties 'property': 'value' 90 | testLogging { 91 | showStandardStreams = true 92 | exceptionFormat 'full' 93 | events 'started', 'passed', 'skipped', 'failed' 94 | } 95 | minHeapSize = '128m' 96 | maxHeapSize = '256m' 97 | jvmArgs '-XX:MaxPermSize=128m' 98 | } 99 | -------------------------------------------------------------------------------- /resources/size.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vongosling/jvm-serializer/86ece6ecca0a475c13dfded5a2fe01cc9e19e124/resources/size.png -------------------------------------------------------------------------------- /resources/tps.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vongosling/jvm-serializer/86ece6ecca0a475c13dfded5a2fe01cc9e19e124/resources/tps.png -------------------------------------------------------------------------------- /src/main/java/com/creative/commons/utils/HessianCodec.java: -------------------------------------------------------------------------------- 1 | package com.creative.commons.utils; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import java.io.ByteArrayOutputStream; 5 | import java.io.IOException; 6 | import java.io.Serializable; 7 | import java.math.BigDecimal; 8 | import java.util.Locale; 9 | 10 | import com.caucho.hessian.io.*; 11 | 12 | /** 13 | * @author von gosling 14 | */ 15 | public abstract class HessianCodec { 16 | 17 | private static final SerializerFactory serializerFactory = SerializerFactory.createDefault(); 18 | 19 | static { 20 | ExtSerializerFactory extFactory = new ExtSerializerFactory(); 21 | extFactory.addSerializer(Locale.class, LocaleSerializer.create()); 22 | extFactory.addSerializer(BigDecimal.class, new StringValueSerializer()); 23 | extFactory.addDeserializer(BigDecimal.class,new BigDecimalDeserializer()); 24 | serializerFactory.addFactory(extFactory); 25 | } 26 | 27 | public static Serializable decode(byte[] array) throws IOException { 28 | Object obj; 29 | ByteArrayInputStream bais = new ByteArrayInputStream(array); 30 | Hessian2Input hi = new Hessian2Input(bais); 31 | hi.setSerializerFactory(serializerFactory); 32 | hi.setCloseStreamOnClose(true); 33 | hi.startMessage(); 34 | obj = hi.readObject(); 35 | hi.completeMessage(); 36 | 37 | hi.close(); 38 | return (Serializable) obj; 39 | } 40 | 41 | public static byte[] encode(Object data) throws IOException { 42 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 43 | Hessian2Output ho = new Hessian2Output(baos); 44 | ho.setSerializerFactory(serializerFactory); 45 | ho.setCloseStreamOnClose(true); 46 | ho.startMessage(); 47 | ho.writeObject(data); 48 | ho.completeMessage(); 49 | 50 | ho.close(); 51 | return baos.toByteArray(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/creative/commons/utils/JsonCodec.java: -------------------------------------------------------------------------------- 1 | package com.creative.commons.utils; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.alibaba.fastjson.JSONObject; 5 | import com.alibaba.fastjson.parser.Feature; 6 | import com.alibaba.fastjson.serializer.SerializeConfig; 7 | import com.alibaba.fastjson.serializer.SerializerFeature; 8 | import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer; 9 | 10 | /** 11 | * @author von gosling 12 | */ 13 | public abstract class JsonCodec { 14 | private static SerializeConfig config = new SerializeConfig(); 15 | private static SerializerFeature[] sfeatures = {SerializerFeature.WriteEnumUsingToString,SerializerFeature.UseISO8601DateFormat, SerializerFeature.DisableCircularReferenceDetect}; 16 | private static Feature[] features = {Feature.AllowISO8601DateFormat, Feature.DisableCircularReferenceDetect}; 17 | 18 | static { 19 | config.put(java.util.Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss")); 20 | config.put(java.sql.Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss")); 21 | config.put(java.sql.Timestamp.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss")); 22 | } 23 | 24 | public static byte[] encode(Object content) { 25 | return JSONObject.toJSONString(content, config, sfeatures).getBytes(); 26 | } 27 | 28 | public static T decode(byte[] content, Class clazz) { 29 | return JSON.parseObject(content, clazz, features); 30 | } 31 | } -------------------------------------------------------------------------------- /src/main/java/com/creative/commons/utils/KryoCodec.java: -------------------------------------------------------------------------------- 1 | package com.creative.commons.utils; 2 | 3 | import com.esotericsoftware.kryo.Kryo; 4 | import com.esotericsoftware.kryo.KryoSerializable; 5 | import com.esotericsoftware.kryo.Serializer; 6 | import com.esotericsoftware.kryo.io.Input; 7 | import com.esotericsoftware.kryo.io.Output; 8 | import com.google.common.collect.Lists; 9 | import org.objenesis.strategy.StdInstantiatorStrategy; 10 | 11 | import java.math.BigDecimal; 12 | import java.math.BigInteger; 13 | import java.sql.Timestamp; 14 | import java.util.*; 15 | 16 | /** 17 | * @author von gosling 18 | */ 19 | public abstract class KryoCodec { 20 | private static final List> classList = Lists.newArrayList(); 21 | private static final List> serializerList = Lists.newArrayList(); 22 | private static final List idList = Lists.newArrayList(); 23 | private static final ThreadLocal kryos = new ThreadLocal() { 24 | protected Kryo initialValue() { 25 | Kryo kryo = new Kryo(); 26 | 27 | kryo.register(byte[].class); 28 | kryo.register(char[].class); 29 | kryo.register(short[].class); 30 | kryo.register(int[].class); 31 | kryo.register(long[].class); 32 | kryo.register(float[].class); 33 | kryo.register(double[].class); 34 | kryo.register(boolean[].class); 35 | kryo.register(String[].class); 36 | kryo.register(Object[].class); 37 | kryo.register(KryoSerializable.class); 38 | kryo.register(BigInteger.class); 39 | kryo.register(BigDecimal.class); 40 | kryo.register(Class.class); 41 | kryo.register(Date.class); 42 | //kryo.register(Enum.class); 43 | kryo.register(EnumSet.class); 44 | kryo.register(Currency.class); 45 | kryo.register(StringBuffer.class); 46 | kryo.register(StringBuilder.class); 47 | kryo.register(Collections.EMPTY_LIST.getClass()); 48 | kryo.register(Collections.EMPTY_MAP.getClass()); 49 | kryo.register(Collections.EMPTY_SET.getClass()); 50 | kryo.register(Collections.singletonList(null).getClass()); 51 | kryo.register(Collections.singletonMap(null, null).getClass()); 52 | kryo.register(Collections.singleton(null).getClass()); 53 | kryo.register(TreeSet.class); 54 | kryo.register(Collection.class); 55 | kryo.register(TreeMap.class); 56 | kryo.register(Map.class); 57 | try { 58 | kryo.register(Class.forName("sun.util.calendar.ZoneInfo")); 59 | } catch (ClassNotFoundException e) { 60 | //Noop 61 | } 62 | kryo.register(Calendar.class); 63 | kryo.register(Locale.class); 64 | 65 | kryo.register(BitSet.class); 66 | kryo.register(HashMap.class); 67 | kryo.register(Timestamp.class); 68 | kryo.register(ArrayList.class); 69 | 70 | int size = idList.size(); 71 | for (int i = 0; i < size; i++) { 72 | kryo.register(classList 73 | .get(i), 74 | serializerList 75 | .get(i), 76 | idList.get(i)); 77 | } 78 | kryo.setRegistrationRequired(true); 79 | kryo.setReferences(false); 80 | kryo.setInstantiatorStrategy(new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy())); 81 | return kryo; 82 | } 83 | }; 84 | 85 | public static synchronized void registerClass(Class className, Serializer serializer, 86 | int id) { 87 | classList.add(className); 88 | serializerList.add(serializer); 89 | idList.add(id); 90 | } 91 | 92 | public static synchronized void register(Class className) { 93 | getKryo().register(className); 94 | } 95 | 96 | public static Kryo getKryo() { 97 | return kryos.get(); 98 | } 99 | 100 | public static Object decode(byte[] bytes) throws Exception { 101 | Input input = new Input(bytes); 102 | return getKryo().readClassAndObject(input); 103 | } 104 | 105 | public static byte[] encode(Object object) throws Exception { 106 | //4K 107 | Output output = new Output(4096); 108 | getKryo().writeClassAndObject(output, object); 109 | return output.toBytes(); 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/main/java/com/creative/commons/utils/MsgPackCodec.java: -------------------------------------------------------------------------------- 1 | package com.creative.commons.utils; 2 | 3 | import org.msgpack.MessagePack; 4 | 5 | import java.io.IOException; 6 | 7 | /** 8 | * @author xinyuzhou.zxy 9 | */ 10 | public class MsgPackCodec { 11 | private static MessagePack messagePack = new MessagePack(); 12 | 13 | static { 14 | messagePack.register(Object.class, ObjectTemplate.getInstance()); 15 | } 16 | public static byte[] encode(T content) { 17 | 18 | try { 19 | return messagePack.write(content); 20 | } catch (IOException e) { 21 | e.printStackTrace(); 22 | } 23 | return null; 24 | } 25 | 26 | public static T decode(byte[] content, Class clazz) { 27 | 28 | try { 29 | return messagePack.read(content, clazz); 30 | } catch (IOException e) { 31 | e.printStackTrace(); 32 | } 33 | return null; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/creative/commons/utils/ObjectTemplate.java: -------------------------------------------------------------------------------- 1 | package com.creative.commons.utils; 2 | 3 | import org.msgpack.MessageTypeException; 4 | import org.msgpack.packer.Packer; 5 | import org.msgpack.template.AbstractTemplate; 6 | import org.msgpack.template.Templates; 7 | import org.msgpack.type.*; 8 | import org.msgpack.unpacker.Converter; 9 | import org.msgpack.unpacker.Unpacker; 10 | 11 | import java.io.IOException; 12 | import java.util.ArrayList; 13 | import java.util.HashMap; 14 | import java.util.List; 15 | import java.util.Map; 16 | 17 | /** 18 | * @author xinyuzhou.zxy 19 | */ 20 | public class ObjectTemplate extends AbstractTemplate{ 21 | static final ObjectTemplate instance = new ObjectTemplate(); 22 | 23 | private ObjectTemplate() { 24 | } 25 | 26 | static public ObjectTemplate getInstance() { 27 | return instance; 28 | } 29 | 30 | 31 | @Override 32 | public void write(Packer pk, Object v, boolean required) throws IOException { 33 | if (v == null) { 34 | if (required) { 35 | throw new MessageTypeException("Attempted to write null"); 36 | } 37 | pk.writeNil(); 38 | return; 39 | } 40 | pk.write(v); 41 | } 42 | 43 | @Override 44 | public Object read(Unpacker u, Object to, boolean required) throws IOException { 45 | if (!required && u.trySkipNil()) { 46 | return null; 47 | } 48 | 49 | return toObject(u.readValue()); 50 | } 51 | 52 | private static Object toObject(Value value) throws IOException { 53 | Converter conv = new Converter(value); 54 | if (value.isNilValue()) { // null 55 | return null; 56 | } else if (value.isRawValue()) { // byte[] or String or maybe Date? 57 | // deserialize value to String object 58 | RawValue v = value.asRawValue(); 59 | return conv.read(Templates.TString); 60 | } else if (value.isBooleanValue()) { // boolean 61 | return conv.read(Templates.TBoolean); 62 | } else if (value.isIntegerValue()) { // int or long or BigInteger 63 | // deserialize value to int 64 | IntegerValue v = value.asIntegerValue(); 65 | return conv.read(Templates.TLong); 66 | } else if (value.isFloatValue()) { // float or double 67 | // deserialize value to double 68 | FloatValue v = value.asFloatValue(); 69 | return conv.read(Templates.TDouble); 70 | } else if (value.isArrayValue()) { // List or Set 71 | // deserialize value to List object 72 | ArrayValue v = value.asArrayValue(); 73 | List ret = new ArrayList<>(v.size()); 74 | for (Value elementValue : v) { 75 | ret.add(toObject(elementValue)); 76 | } 77 | return ret; 78 | } else if (value.isMapValue()) { // Map 79 | MapValue v = value.asMapValue(); 80 | 81 | Map map = new HashMap<>(v.size()); 82 | for (Map.Entry entry : v.entrySet()) { 83 | Value key = entry.getKey(); 84 | Value val = entry.getValue(); 85 | 86 | map.put(toObject(key), toObject(val)); 87 | } 88 | 89 | return map; 90 | } else { 91 | throw new RuntimeException("fatal error"); 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/test/java/com/creative/commons/utils/CodecTest.java: -------------------------------------------------------------------------------- 1 | package com.creative.commons.utils; 2 | 3 | import com.creative.model.Father; 4 | import com.creative.model.Message; 5 | import com.creative.model.Son; 6 | import com.google.common.collect.Lists; 7 | import com.google.common.collect.Maps; 8 | import org.junit.After; 9 | import org.junit.Before; 10 | import org.openjdk.jmh.annotations.Scope; 11 | import org.openjdk.jmh.annotations.State; 12 | 13 | import java.math.BigDecimal; 14 | import java.sql.Timestamp; 15 | import java.util.*; 16 | 17 | /** 18 | * @author Von Gosling 19 | */ 20 | @State(Scope.Benchmark) 21 | public class CodecTest { 22 | protected Message msg1 = new Message( 23 | "Most message-oriented middleware (MOM) products treat messages as lightweight entities that consist of a header and a body. The header contains fields used for message routing and identification; the body contains the application data being sent."); 24 | protected Message msg2 = new Message(new Father()); 25 | protected Message msg3 = new Message(new Son()); 26 | 27 | protected Map props = Maps.newHashMap(); 28 | 29 | protected Date now = Calendar.getInstance().getTime(); 30 | protected BigDecimal money = BigDecimal.valueOf(110.13); 31 | protected TimeZone tz = Calendar.getInstance().getTimeZone(); 32 | protected Timestamp tt = new java.sql.Timestamp(Calendar.getInstance().getTimeInMillis()); 33 | 34 | //intx CompileThreshold=10000 35 | protected final int warmupIter = 12000; 36 | protected final int testIter = 5000; 37 | 38 | @Before 39 | public void init() { 40 | props.put("boolean", Boolean.TRUE); 41 | props.put("byte", Byte.MAX_VALUE); 42 | props.put("short", Short.MAX_VALUE); 43 | props.put("int", Integer.MAX_VALUE); 44 | props.put("long", Long.MAX_VALUE); 45 | props.put("float", Float.MAX_EXPONENT); 46 | props.put("double", Double.MAX_EXPONENT); 47 | props.put("char", Character.MAX_VALUE); 48 | props.put("String", String.valueOf("VonGosling")); 49 | props.put("trait", Lists.newArrayListWithCapacity(1000)); 50 | props.put("case", Objects.toString(msg1)); 51 | 52 | //Some particular types 53 | props.put("bigDecimal", money); 54 | props.put("date", now); 55 | //props.put("timesZone", tz); 56 | props.put("timestamp", tt); 57 | 58 | msg1.setProperties(props); 59 | } 60 | 61 | 62 | @After 63 | public void destroy() { 64 | props.clear(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/test/java/com/creative/commons/utils/benchmark/BenchmarkBootstrap.java: -------------------------------------------------------------------------------- 1 | package com.creative.commons.utils.benchmark; 2 | 3 | import com.creative.commons.utils.unittest.*; 4 | import org.openjdk.jmh.runner.Runner; 5 | import org.openjdk.jmh.runner.RunnerException; 6 | import org.openjdk.jmh.runner.options.Options; 7 | import org.openjdk.jmh.runner.options.OptionsBuilder; 8 | import org.openjdk.jmh.runner.options.TimeValue; 9 | 10 | import java.util.concurrent.TimeUnit; 11 | 12 | /** 13 | * @author xinyuzhou.zxy 14 | */ 15 | public class BenchmarkBootstrap { 16 | public static void main(String[] args) throws RunnerException { 17 | Options opt = new OptionsBuilder() 18 | .include(MsgPackCodecTest.class.getSimpleName()) 19 | .include(KryoCodecTest.class.getSimpleName()) 20 | .include(FastJsonCodecTest.class.getSimpleName()) 21 | .include(JdkCodecTest.class.getSimpleName()) 22 | .include(HessianCodecTest.class.getSimpleName()) 23 | .forks(1) 24 | .measurementIterations(10).measurementTime(new TimeValue(5, TimeUnit.SECONDS)) 25 | .warmupIterations(10).warmupTime(new TimeValue(5, TimeUnit.SECONDS)) 26 | .build(); 27 | 28 | new Runner(opt).run(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/com/creative/commons/utils/benchmark/FastJsonBenchmark.java: -------------------------------------------------------------------------------- 1 | package com.creative.commons.utils.benchmark; 2 | 3 | import com.creative.commons.utils.unittest.FastJsonCodecTest; 4 | import org.openjdk.jmh.annotations.Benchmark; 5 | 6 | import java.io.IOException; 7 | 8 | /** 9 | * @author xinyuzhou.zxy 10 | */ 11 | public class FastJsonBenchmark extends FastJsonCodecTest{ 12 | @Benchmark 13 | public void jsonCodecMultiTest() throws IOException { 14 | jsonEncodeAndDecode(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/creative/commons/utils/benchmark/HessianBenchmark.java: -------------------------------------------------------------------------------- 1 | package com.creative.commons.utils.benchmark; 2 | 3 | import com.creative.commons.utils.unittest.HessianCodecTest; 4 | import org.openjdk.jmh.annotations.Benchmark; 5 | 6 | /** 7 | * @author xinyuzhou.zxy 8 | */ 9 | public class HessianBenchmark extends HessianCodecTest{ 10 | @Benchmark 11 | public void hessianCodecMultiTest() throws Throwable { 12 | hessianEncodeAndDecode(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/com/creative/commons/utils/benchmark/JdkCodecBencmark.java: -------------------------------------------------------------------------------- 1 | package com.creative.commons.utils.benchmark; 2 | 3 | import com.creative.commons.utils.unittest.JdkCodecTest; 4 | import org.openjdk.jmh.annotations.Benchmark; 5 | 6 | /** 7 | * @author xinyuzhou.zxy 8 | */ 9 | public class JdkCodecBencmark extends JdkCodecTest{ 10 | @Benchmark 11 | public void javaCodecMultiTest() throws Exception { 12 | javaEncodeAndDecode(msg1); 13 | javaEncodeAndDecode(msg2); 14 | javaEncodeAndDecode(msg3); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/creative/commons/utils/benchmark/KryoBenchmark.java: -------------------------------------------------------------------------------- 1 | package com.creative.commons.utils.benchmark; 2 | 3 | import com.creative.commons.utils.unittest.KryoCodecTest; 4 | import org.openjdk.jmh.annotations.Benchmark; 5 | 6 | /** 7 | * @author xinyuzhou.zxy 8 | */ 9 | public class KryoBenchmark extends KryoCodecTest{ 10 | 11 | @Benchmark 12 | public void kryoCodecMultiTest() throws Exception { 13 | kryoEncodeAndDecode(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/test/java/com/creative/commons/utils/benchmark/MsgPackBenchmark.java: -------------------------------------------------------------------------------- 1 | package com.creative.commons.utils.benchmark; 2 | 3 | import com.creative.commons.utils.unittest.MsgPackCodecTest; 4 | import org.openjdk.jmh.annotations.Benchmark; 5 | 6 | import java.io.IOException; 7 | 8 | /** 9 | * @author xinyuzhou.zxy 10 | */ 11 | public class MsgPackBenchmark extends MsgPackCodecTest { 12 | @Benchmark 13 | public void msgPackCodecMultiTest() throws IOException { 14 | msgPackEncodeAndDecode(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/creative/commons/utils/unittest/FastJsonCodecTest.java: -------------------------------------------------------------------------------- 1 | package com.creative.commons.utils.unittest; 2 | 3 | import com.creative.commons.utils.CodecTest; 4 | import com.creative.commons.utils.JsonCodec; 5 | import com.creative.model.Message; 6 | import com.creative.model.Son; 7 | import org.junit.Test; 8 | 9 | import java.io.IOException; 10 | 11 | public class FastJsonCodecTest extends CodecTest { 12 | 13 | @Test 14 | public void jsonCodecSizeTest() throws Throwable { 15 | byte[] obj1 = JsonCodec.encode(msg1); 16 | System.out.println(obj1.length); 17 | } 18 | 19 | @Test 20 | public void jsonCodecTest() { 21 | //Father father = new Father(); 22 | //byte[] obj1 = JsonCodec.encode(father); 23 | //Father fatherCopy = JsonCodec.decode(obj1, Father.class); 24 | 25 | //Timestamp type 26 | //System.out.println(fatherCopy.getLocation_time()); 27 | //System.out.println(father.getLocation_time()); 28 | 29 | //Locale 30 | //System.out.println(fatherCopy.getLocale()); 31 | //System.out.println(father.getLocale()); 32 | 33 | //EnumSet 34 | //bug 35 | //System.out.println(fatherCopy.getCertificates()); 36 | //System.out.println(father.getCertificates()); 37 | 38 | //BitSet 39 | //bug 40 | //System.out.println(fatherCopy.getqRCode()); 41 | //System.out.println(father.getqRCode()); 42 | 43 | Son son = new Son(); 44 | byte[] obj2 = JsonCodec.encode(son); 45 | Son sonCopy = JsonCodec.decode(obj2, Son.class); 46 | 47 | //Enum 48 | //System.out.println(sonCopy.getCf()); 49 | //System.out.println(son.getCf()); 50 | 51 | //same name filed,parent first 52 | System.out.println(son.getAge()); 53 | System.out.println(sonCopy.getAge()); 54 | System.out.println(son.isCCP()); 55 | System.out.println(sonCopy.isCCP()); 56 | System.out.println(son.getSalary()); 57 | System.out.println(sonCopy.getSalary()); 58 | } 59 | 60 | protected void jsonEncodeAndDecode() throws IOException { 61 | byte[] obj1 = JsonCodec.encode(msg1); 62 | msg1 = JsonCodec.decode(obj1, Message.class); 63 | 64 | byte[] obj2 = JsonCodec.encode(msg2); 65 | msg2 = JsonCodec.decode(obj2, Message.class); 66 | 67 | byte[] obj3 = JsonCodec.encode(msg3); 68 | msg3 = JsonCodec.decode(obj3, Message.class); 69 | } 70 | } -------------------------------------------------------------------------------- /src/test/java/com/creative/commons/utils/unittest/HessianCodecTest.java: -------------------------------------------------------------------------------- 1 | package com.creative.commons.utils.unittest; 2 | 3 | import com.caucho.hessian.io.ExtSerializerFactory; 4 | import com.caucho.hessian.io.LocaleSerializer; 5 | import com.caucho.hessian.io.SerializerFactory; 6 | import com.creative.commons.utils.CodecTest; 7 | import com.creative.commons.utils.HessianCodec; 8 | import com.creative.model.Father; 9 | import com.creative.model.Message; 10 | import com.creative.model.Son; 11 | import org.junit.Assert; 12 | import org.junit.Test; 13 | 14 | import java.io.IOException; 15 | import java.math.BigDecimal; 16 | import java.util.BitSet; 17 | import java.util.EnumSet; 18 | import java.util.Locale; 19 | 20 | public class HessianCodecTest extends CodecTest { 21 | 22 | @Test 23 | public void hessianCodecSizeTest() throws Throwable { 24 | byte[] obj1 = HessianCodec.encode(msg1); 25 | System.out.println(obj1.length); 26 | } 27 | 28 | @Test 29 | public void hessianCodecTest() throws Throwable { 30 | Father father = new Father(); 31 | byte[] obj1 = HessianCodec.encode(father); 32 | Father fatherCopy = (Father) HessianCodec.decode(obj1); 33 | 34 | //Timestamp type is null 35 | //System.out.println(fatherCopy.getLocation_time()); 36 | //System.out.println(father.getLocation_time()); 37 | 38 | //Float type field is null 39 | //System.out.println(fatherCopy.getCet4Score()); 40 | 41 | //Locale,if not set ext ExtSerializerFactory 42 | //bugs,http://bugs.caucho.com/view.php?id=5046 43 | //System.out.println(fatherCopy.getLocale()); 44 | //System.out.println(father.getLocale()); 45 | 46 | //EnumSet 47 | //Warning:WARNING: Hessian/Burlap: 'java.lang.Enum' is an unknown class in sun.misc.Launcher$AppClassLoader@9cc3baa: 48 | //java.lang.RuntimeException: Class java.lang.Enum is not an enum 49 | //System.out.println(fatherCopy.getCertificates()); 50 | //System.out.println(father.getCertificates()); 51 | 52 | //BitSet 53 | //bug 54 | //System.out.println(fatherCopy.getqRCode()); 55 | //System.out.println(father.getqRCode()); 56 | 57 | SerializerFactory serializerFactory = SerializerFactory.createDefault(); 58 | ExtSerializerFactory extFactory = new ExtSerializerFactory(); 59 | extFactory.addSerializer(Locale.class, LocaleSerializer.create()); 60 | //extFactory.addSerializer(Enum.class,new EnumSerializer(Enum.class)); 61 | //extFactory.addDeserializer(Enum.class,new EnumDeserializer(Enum.class)); 62 | serializerFactory.addFactory(extFactory); 63 | System.out.println(serializerFactory.getSerializer(Locale.class)); 64 | System.out.println(serializerFactory.getSerializer(BigDecimal.class)); 65 | System.out.println(serializerFactory.getSerializer(EnumSet.class)); 66 | System.out.println(serializerFactory.getSerializer(BitSet.class)); 67 | //System.out.println(serializerFactory.getDeserializer(Enum.class)); 68 | 69 | Assert.assertEquals(father.getSalary(), fatherCopy.getSalary()); 70 | 71 | Son son = new Son(); 72 | byte[] obj2 = HessianCodec.encode(son); 73 | Son sonCopy = (Son) HessianCodec.decode(obj2); 74 | 75 | //Enum 76 | System.out.println(sonCopy.getCf()); 77 | System.out.println(son.getCf()); 78 | 79 | //same name filed 80 | System.out.println(son.getAge()); 81 | System.out.println(sonCopy.getAge()); 82 | System.out.println(son.isCCP()); 83 | System.out.println(sonCopy.isCCP()); 84 | } 85 | 86 | protected void hessianEncodeAndDecode() throws IOException { 87 | byte[] obj1 = HessianCodec.encode(msg1); 88 | msg1 = (Message) HessianCodec.decode(obj1); 89 | 90 | byte[] obj2 = HessianCodec.encode(msg2); 91 | msg2 = (Message) HessianCodec.decode(obj2); 92 | 93 | byte[] obj3 = HessianCodec.encode(msg3); 94 | msg3 = (Message) HessianCodec.decode(obj3); 95 | } 96 | } -------------------------------------------------------------------------------- /src/test/java/com/creative/commons/utils/unittest/JdkCodecTest.java: -------------------------------------------------------------------------------- 1 | package com.creative.commons.utils.unittest; 2 | 3 | import com.creative.commons.utils.CodecTest; 4 | import com.creative.model.Father; 5 | import org.junit.Assert; 6 | import org.junit.Test; 7 | 8 | import java.io.*; 9 | 10 | /** 11 | * @author xinyuzhou.zxy 12 | */ 13 | public class JdkCodecTest extends CodecTest { 14 | protected Object javaEncodeAndDecode(Object msg) throws IOException, ClassNotFoundException { 15 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 16 | ObjectOutputStream oos = new ObjectOutputStream(baos); 17 | oos.writeObject(msg); 18 | oos.close(); 19 | baos.close(); 20 | 21 | ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); 22 | ObjectInputStream ois = new ObjectInputStream(bais); 23 | Object obj = ois.readObject(); 24 | ois.close(); 25 | bais.close(); 26 | 27 | return obj; 28 | } 29 | 30 | @Test 31 | public void javaCodecTest() throws Throwable { 32 | Father father = new Father(); 33 | Father fatherCopy = (Father) javaEncodeAndDecode(father); 34 | 35 | Assert.assertEquals(father, fatherCopy); 36 | } 37 | 38 | @Test 39 | public void javaCodecSizeTest() throws Throwable { 40 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 41 | ObjectOutputStream oos = new ObjectOutputStream(baos); 42 | oos.writeObject(msg1); 43 | System.out.println(baos.toByteArray().length); 44 | oos.close(); 45 | baos.close(); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/test/java/com/creative/commons/utils/unittest/KryoCodecTest.java: -------------------------------------------------------------------------------- 1 | package com.creative.commons.utils.unittest; 2 | 3 | import com.creative.commons.utils.CodecTest; 4 | import com.creative.commons.utils.KryoCodec; 5 | import com.creative.model.Certificates; 6 | import com.creative.model.Father; 7 | import com.creative.model.Message; 8 | import com.creative.model.Son; 9 | import org.junit.Assert; 10 | import org.junit.Test; 11 | 12 | import java.util.concurrent.TimeUnit; 13 | 14 | public class KryoCodecTest extends CodecTest { 15 | 16 | @Test 17 | public void kryoCodecSizeTest() throws Throwable { 18 | KryoCodec.register(Message.class); 19 | byte[] obj1 = KryoCodec.encode(msg1); 20 | System.out.println(obj1.length); 21 | } 22 | 23 | @Test 24 | public void testThrpt() throws InterruptedException { 25 | final int[] count = {0}; 26 | Thread t = new Thread(() -> { 27 | while (!Thread.interrupted()) { 28 | try { 29 | kryoEncodeAndDecode(); 30 | count[0]++; 31 | } catch (Exception e) { 32 | e.printStackTrace(); 33 | } 34 | } 35 | }); 36 | t.start(); 37 | TimeUnit.SECONDS.sleep(10); 38 | t.interrupt(); 39 | System.out.println(count[0] / 10); 40 | } 41 | 42 | protected void kryoEncodeAndDecode() throws Exception { 43 | KryoCodec.register(Message.class); 44 | KryoCodec.register(Father.class); 45 | KryoCodec.register(Son.class); 46 | KryoCodec.register(Certificates.class); 47 | 48 | byte[] obj1 = KryoCodec.encode(msg1); 49 | msg1 = (Message) KryoCodec.decode(obj1); 50 | 51 | byte[] obj2 = KryoCodec.encode(msg2); 52 | msg2 = (Message) KryoCodec.decode(obj2); 53 | 54 | byte[] obj3 = KryoCodec.encode(msg3); 55 | msg3 = (Message) KryoCodec.decode(obj3); 56 | } 57 | 58 | @Test 59 | public void kyroCodecTest() throws Exception { 60 | KryoCodec.register(Father.class); 61 | KryoCodec.register(Son.class); 62 | KryoCodec.register(Certificates.class); 63 | 64 | Father father = new Father(); 65 | byte[] obj1 = KryoCodec.encode(father); 66 | Father fatherCopy = (Father) KryoCodec.decode(obj1); 67 | 68 | Assert.assertEquals(father, fatherCopy); 69 | 70 | //Timestamp type 71 | //System.out.println(fatherCopy.getLocation_time()); 72 | //System.out.println(father.getLocation_time()); 73 | 74 | //Locale 75 | //System.out.println(fatherCopy.getLocale()); 76 | //System.out.println(father.getLocale()); 77 | 78 | //EnumSet 79 | //bug 80 | //System.out.println(fatherCopy.getCertificates()); 81 | //System.out.println(father.getCertificates()); 82 | 83 | //BitSet 84 | //bug 85 | //System.out.println(fatherCopy.getqRCode()); 86 | //System.out.println(father.getqRCode()); 87 | 88 | Son son = new Son(); 89 | byte[] obj2 = KryoCodec.encode(son); 90 | Son sonCopy = (Son) KryoCodec.decode(obj2); 91 | 92 | //Enum 93 | System.out.println(sonCopy.getCf()); 94 | System.out.println(son.getCf()); 95 | 96 | //same name filed,parent first 97 | System.out.println(son.getAge()); 98 | System.out.println(sonCopy.getAge()); 99 | System.out.println(son.isCCP()); 100 | System.out.println(sonCopy.isCCP()); 101 | System.out.println(son.getSalary()); 102 | System.out.println(sonCopy.getSalary()); 103 | } 104 | } -------------------------------------------------------------------------------- /src/test/java/com/creative/commons/utils/unittest/MsgPackCodecTest.java: -------------------------------------------------------------------------------- 1 | package com.creative.commons.utils.unittest; 2 | 3 | import com.creative.commons.utils.CodecTest; 4 | import com.creative.commons.utils.MsgPackCodec; 5 | import com.creative.model.Message; 6 | import org.junit.Test; 7 | 8 | import java.io.IOException; 9 | 10 | /** 11 | * @author xinyuzhou.zxy 12 | */ 13 | public class MsgPackCodecTest extends CodecTest { 14 | 15 | @Test 16 | public void msgPackCodecSizeTest() { 17 | byte[] obj1 = MsgPackCodec.encode(msg1); 18 | System.out.println(obj1.length); 19 | } 20 | 21 | 22 | protected void msgPackEncodeAndDecode() throws IOException { 23 | byte[] obj1 = MsgPackCodec.encode(msg1); 24 | msg1 = MsgPackCodec.decode(obj1, Message.class); 25 | 26 | byte[] obj2 = MsgPackCodec.encode(msg2); 27 | msg2 = MsgPackCodec.decode(obj2, Message.class); 28 | 29 | byte[] obj3 = MsgPackCodec.encode(msg3); 30 | msg3 = MsgPackCodec.decode(obj3, Message.class); 31 | } 32 | } 33 | 34 | -------------------------------------------------------------------------------- /src/test/java/com/creative/model/Certificates.java: -------------------------------------------------------------------------------- 1 | package com.creative.model; 2 | 3 | import com.google.common.collect.Maps; 4 | 5 | import java.util.Map; 6 | 7 | /** 8 | * @author Von Gosling 9 | */ 10 | public enum Certificates { 11 | CET4("cet4"), 12 | CET6("cet6"), 13 | MCSE("mcse"), 14 | CCNP("ccnp"), 15 | OCP("ocp"), 16 | SCJP("scjp"); 17 | 18 | private String value; 19 | 20 | Certificates() { 21 | } 22 | 23 | Certificates(String value) { 24 | this.value = value; 25 | } 26 | 27 | public String getValue() { 28 | return this.value; 29 | } 30 | 31 | private static Map stringToEnum = Maps.newHashMap(); 32 | 33 | static { 34 | for (Certificates fileFormat : values()) { 35 | stringToEnum.put(fileFormat.getValue(), fileFormat); 36 | } 37 | } 38 | 39 | public static Certificates fromString(String value) { 40 | return stringToEnum.get(value.toLowerCase()); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/test/java/com/creative/model/Father.java: -------------------------------------------------------------------------------- 1 | package com.creative.model; 2 | 3 | import com.google.common.collect.Maps; 4 | 5 | import java.io.Serializable; 6 | import java.math.BigDecimal; 7 | import java.sql.Timestamp; 8 | import java.util.*; 9 | 10 | /** 11 | * @author Von Gosling 12 | */ 13 | public class Father implements Serializable { 14 | private static final long serialVersionUID = 893890389701153928L; 15 | protected boolean isCCP = Boolean.TRUE; 16 | protected byte multilingualer = Byte.MAX_VALUE; 17 | protected short age = Short.MAX_VALUE; 18 | protected char education = Character.MAX_VALUE; 19 | protected int phoneNumber = Integer.MAX_VALUE; 20 | protected long anniversary = Long.MAX_VALUE; 21 | protected float cet4Score = Float.MAX_VALUE; 22 | protected double cet6Score = Double.MAX_VALUE; 23 | 24 | protected Date birthday = Calendar.getInstance().getTime(); 25 | protected BigDecimal salary = BigDecimal.valueOf(11000.13); 26 | 27 | protected TimeZone location = Calendar.getInstance().getTimeZone(); 28 | protected Timestamp location_time = new java.sql.Timestamp(Calendar.getInstance().getTimeInMillis()); 29 | 30 | protected Locale locale = Locale.getDefault(); 31 | //protected EnumSet certificates = EnumSet.allOf(Certificates.class); 32 | protected BitSet qRCode = BitSet.valueOf(new long[]{123, 345}); 33 | 34 | public BitSet getqRCode() { 35 | return qRCode; 36 | } 37 | 38 | public void setqRCode(BitSet qRCode) { 39 | this.qRCode = qRCode; 40 | } 41 | 42 | // public EnumSet getCertificates() { 43 | // return certificates; 44 | // } 45 | 46 | // public void setCertificates(EnumSet certificates) { 47 | // this.certificates = certificates; 48 | // } 49 | 50 | public Locale getLocale() { 51 | return locale; 52 | } 53 | 54 | public void setLocale(Locale locale) { 55 | this.locale = locale; 56 | } 57 | 58 | public boolean isCCP() { 59 | return isCCP; 60 | } 61 | 62 | public void setCCP(boolean isCCP) { 63 | this.isCCP = isCCP; 64 | } 65 | 66 | public byte getMultilingualer() { 67 | return multilingualer; 68 | } 69 | 70 | public void setMultilingualer(byte multilingualer) { 71 | this.multilingualer = multilingualer; 72 | } 73 | 74 | public short getAge() { 75 | return age; 76 | } 77 | 78 | public void setAge(short age) { 79 | this.age = age; 80 | } 81 | 82 | public char getEducation() { 83 | return education; 84 | } 85 | 86 | public void setEducation(char education) { 87 | this.education = education; 88 | } 89 | 90 | public int getPhoneNumber() { 91 | return phoneNumber; 92 | } 93 | 94 | public void setPhoneNumber(int phoneNumber) { 95 | this.phoneNumber = phoneNumber; 96 | } 97 | 98 | public long getAnniversary() { 99 | return anniversary; 100 | } 101 | 102 | public void setAnniversary(long anniversary) { 103 | this.anniversary = anniversary; 104 | } 105 | 106 | public float getCet4Score() { 107 | return cet4Score; 108 | } 109 | 110 | public void setCet4Score(float cet4Score) { 111 | this.cet4Score = cet4Score; 112 | } 113 | 114 | public double getCet6Score() { 115 | return cet6Score; 116 | } 117 | 118 | public void setCet6Score(double cet6Score) { 119 | this.cet6Score = cet6Score; 120 | } 121 | 122 | public Date getBirthday() { 123 | return birthday; 124 | } 125 | 126 | public void setBirthday(Date birthday) { 127 | this.birthday = birthday; 128 | } 129 | 130 | public BigDecimal getSalary() { 131 | return salary; 132 | } 133 | 134 | public void setSalary(BigDecimal salary) { 135 | this.salary = salary; 136 | } 137 | 138 | public TimeZone getLocation() { 139 | return location; 140 | } 141 | 142 | public void setLocation(TimeZone location) { 143 | this.location = location; 144 | } 145 | 146 | public Timestamp getLocation_time() { 147 | return location_time; 148 | } 149 | 150 | public void setLocation_time(Timestamp location_time) { 151 | this.location_time = location_time; 152 | } 153 | 154 | @Override 155 | public boolean equals(Object o) { 156 | if (this == o) return true; 157 | if (o == null || getClass() != o.getClass()) return false; 158 | 159 | Father father = (Father) o; 160 | 161 | if (age != father.age) return false; 162 | if (anniversary != father.anniversary) return false; 163 | if (Float.compare(father.cet4Score, cet4Score) != 0) return false; 164 | if (Double.compare(father.cet6Score, cet6Score) != 0) return false; 165 | if (education != father.education) return false; 166 | if (isCCP != father.isCCP) return false; 167 | if (multilingualer != father.multilingualer) return false; 168 | if (phoneNumber != father.phoneNumber) return false; 169 | if (birthday != null ? !birthday.equals(father.birthday) : father.birthday != null) return false; 170 | if (location != null ? !location.equals(father.location) : father.location != null) return false; 171 | if (location_time != null ? !location_time.equals(father.location_time) : father.location_time != null) 172 | return false; 173 | if (salary != null ? !salary.equals(father.salary) : father.salary != null) return false; 174 | 175 | return true; 176 | } 177 | 178 | @Override 179 | public int hashCode() { 180 | int result; 181 | long temp; 182 | result = (isCCP ? 1 : 0); 183 | result = 31 * result + (int) multilingualer; 184 | result = 31 * result + (int) age; 185 | result = 31 * result + (int) education; 186 | result = 31 * result + phoneNumber; 187 | result = 31 * result + (int) (anniversary ^ (anniversary >>> 32)); 188 | result = 31 * result + (cet4Score != +0.0f ? Float.floatToIntBits(cet4Score) : 0); 189 | temp = Double.doubleToLongBits(cet6Score); 190 | result = 31 * result + (int) (temp ^ (temp >>> 32)); 191 | result = 31 * result + (birthday != null ? birthday.hashCode() : 0); 192 | result = 31 * result + (salary != null ? salary.hashCode() : 0); 193 | result = 31 * result + (location != null ? location.hashCode() : 0); 194 | result = 31 * result + (location_time != null ? location_time.hashCode() : 0); 195 | return result; 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /src/test/java/com/creative/model/Message.java: -------------------------------------------------------------------------------- 1 | package com.creative.model; 2 | 3 | import com.google.common.collect.Maps; 4 | 5 | import java.io.Serializable; 6 | import java.util.Map; 7 | 8 | /** 9 | * @author Von Gosling 10 | */ 11 | @org.msgpack.annotation.Message 12 | public class Message implements Serializable { 13 | private static final long serialVersionUID = 1892011038502772782L; 14 | /** 15 | * message properties 16 | */ 17 | protected Map properties = Maps.newHashMap(); 18 | /** 19 | * message headers 20 | */ 21 | protected Map headers = Maps.newHashMap(); 22 | /** 23 | * message body 24 | */ 25 | protected transient Serializable body; 26 | 27 | public Message(Serializable body) { 28 | this.body = body; 29 | } 30 | 31 | public Message() { 32 | } 33 | 34 | /** 35 | * @return the properties 36 | */ 37 | public Map getProperties() { 38 | return properties; 39 | } 40 | 41 | /** 42 | * @param properties the properties to set 43 | */ 44 | public void setProperties(Map properties) { 45 | this.properties = properties; 46 | } 47 | 48 | /** 49 | * @return the headers 50 | */ 51 | public Map getHeaders() { 52 | return headers; 53 | } 54 | 55 | /** 56 | * @param headers the headers to set 57 | */ 58 | public void setHeaders(Map headers) { 59 | this.headers = headers; 60 | } 61 | 62 | /** 63 | * @return the body 64 | */ 65 | public Serializable getBody() { 66 | return body; 67 | } 68 | 69 | /** 70 | * @param body the body to set 71 | */ 72 | public void setBody(Serializable body) { 73 | this.body = body; 74 | } 75 | 76 | @Override 77 | public boolean equals(Object o) { 78 | if (this == o) return true; 79 | if (o == null || getClass() != o.getClass()) return false; 80 | 81 | Message message = (Message) o; 82 | 83 | if (body != null ? !body.equals(message.body) : message.body != null) return false; 84 | if (headers != null ? !headers.equals(message.headers) : message.headers != null) return false; 85 | if (properties != null ? !properties.equals(message.properties) : message.properties != null) return false; 86 | 87 | return true; 88 | } 89 | 90 | @Override 91 | public int hashCode() { 92 | int result = properties != null ? properties.hashCode() : 0; 93 | result = 31 * result + (headers != null ? headers.hashCode() : 0); 94 | result = 31 * result + (body != null ? body.hashCode() : 0); 95 | return result; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/test/java/com/creative/model/Son.java: -------------------------------------------------------------------------------- 1 | package com.creative.model; 2 | 3 | /** 4 | * @author Von Gosling 5 | */ 6 | public class Son extends Father{ 7 | private static final long serialVersionUID = 6952023538649252068L; 8 | private byte multilingualer = Byte.MIN_VALUE; 9 | private short age = Short.MIN_VALUE; 10 | private char education = Character.MIN_VALUE; 11 | private int phoneNumber = Integer.MIN_VALUE; 12 | private long anniversary= Long.MIN_VALUE; 13 | private float cet4Score=Float.MIN_VALUE; 14 | private double cet6Score=Double.MIN_VALUE; 15 | private boolean isCCP = Boolean.FALSE; 16 | 17 | private Certificates cf = Certificates.CET4; 18 | 19 | public Certificates getCf() { 20 | return cf; 21 | } 22 | 23 | public void setCf(Certificates cf) { 24 | this.cf = cf; 25 | } 26 | } 27 | --------------------------------------------------------------------------------