blob: 03c392707562b122a768fbabd45b2482246d4fac [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
2 * Copyright 2014 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -070016package org.onlab.onos.store.serializers;
17
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -070018import org.onlab.util.KryoNamespace;
tomf5d85d42014-10-02 05:27:56 -070019import java.nio.ByteBuffer;
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -070020
21/**
Yuta HIGUCHI971addc2014-10-07 23:23:17 -070022 * StoreSerializer implementation using Kryo.
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -070023 */
Yuta HIGUCHI971addc2014-10-07 23:23:17 -070024public class KryoSerializer implements StoreSerializer {
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -070025
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -070026 protected KryoNamespace serializerPool;
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -070027
Yuta HIGUCHI672488d2014-10-07 09:23:43 -070028 public KryoSerializer() {
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -070029 setupKryoPool();
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -070030 }
31
32 /**
33 * Sets up the common serialzers pool.
34 */
35 protected void setupKryoPool() {
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -070036 serializerPool = KryoNamespace.newBuilder()
37 .register(KryoNamespaces.API)
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -070038 .build()
39 .populate(1);
40 }
41
42 @Override
Yuta HIGUCHI53a285d2014-10-06 23:58:01 -070043 public byte[] encode(final Object obj) {
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -070044 return serializerPool.serialize(obj);
45 }
46
47 @Override
Yuta HIGUCHI53a285d2014-10-06 23:58:01 -070048 public <T> T decode(final byte[] bytes) {
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -070049 if (bytes == null) {
50 return null;
51 }
52 return serializerPool.deserialize(bytes);
53 }
54
Yuta HIGUCHIf6d11702014-09-30 19:18:59 -070055 @Override
Yuta HIGUCHI53a285d2014-10-06 23:58:01 -070056 public void encode(Object obj, ByteBuffer buffer) {
Yuta HIGUCHIf6d11702014-09-30 19:18:59 -070057 serializerPool.serialize(obj, buffer);
58 }
59
60 @Override
Yuta HIGUCHI53a285d2014-10-06 23:58:01 -070061 public <T> T decode(ByteBuffer buffer) {
Yuta HIGUCHIf6d11702014-09-30 19:18:59 -070062 return serializerPool.deserialize(buffer);
63 }
64
Yuta HIGUCHIad4c2182014-09-29 11:16:23 -070065}