blob: 85b98a9ce641c48f815716eb0937fe5cc8e626c1 [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 HIGUCHI533ec322014-09-30 13:29:52 -070016package org.onlab.onos.store.serializers;
17
18import java.util.Collections;
19import java.util.HashMap;
20import java.util.Map;
21
Yuta HIGUCHI533ec322014-09-30 13:29:52 -070022import com.esotericsoftware.kryo.Kryo;
Yuta HIGUCHI91768e32014-11-22 05:06:35 -080023import com.esotericsoftware.kryo.Serializer;
Yuta HIGUCHI533ec322014-09-30 13:29:52 -070024import com.esotericsoftware.kryo.io.Input;
25import com.esotericsoftware.kryo.io.Output;
26import com.esotericsoftware.kryo.serializers.MapSerializer;
27import com.google.common.collect.ImmutableMap;
28
29/**
30* Kryo Serializer for {@link ImmutableMap}.
31*/
Yuta HIGUCHI91768e32014-11-22 05:06:35 -080032public class ImmutableMapSerializer extends Serializer<ImmutableMap<?, ?>> {
Yuta HIGUCHI533ec322014-09-30 13:29:52 -070033
34 private final MapSerializer mapSerializer = new MapSerializer();
35
Yuta HIGUCHI03fec1f2014-10-03 09:13:50 -070036 /**
37 * Creates {@link ImmutableMap} serializer instance.
38 */
Yuta HIGUCHI533ec322014-09-30 13:29:52 -070039 public ImmutableMapSerializer() {
40 // non-null, immutable
41 super(false, true);
42 }
43
44 @Override
45 public void write(Kryo kryo, Output output, ImmutableMap<?, ?> object) {
46 // wrapping with unmodifiableMap proxy
47 // to avoid Kryo from writing only the reference marker of this instance,
48 // which will be embedded right before this method call.
49 kryo.writeObject(output, Collections.unmodifiableMap(object), mapSerializer);
50 }
51
52 @Override
53 public ImmutableMap<?, ?> read(Kryo kryo, Input input,
54 Class<ImmutableMap<?, ?>> type) {
55 Map<?, ?> map = kryo.readObject(input, HashMap.class, mapSerializer);
56 return ImmutableMap.copyOf(map);
57 }
Yuta HIGUCHI533ec322014-09-30 13:29:52 -070058}