Madan Jampani | 068a438 | 2016-02-01 09:54:47 -0800 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright 2016 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 | */ |
| 16 | package org.onosproject.store.primitives.impl; |
| 17 | |
| 18 | import org.onosproject.store.service.Serializer; |
| 19 | |
| 20 | import io.atomix.catalyst.buffer.BufferInput; |
| 21 | import io.atomix.catalyst.buffer.BufferOutput; |
| 22 | import io.atomix.catalyst.serializer.TypeSerializer; |
| 23 | import io.atomix.catalyst.serializer.TypeSerializerFactory; |
| 24 | |
| 25 | /** |
| 26 | * {@link TypeSerializerFactory} for providing {@link TypeSerializer}s based on |
| 27 | * {@code org.onosproject.store.service.Serializer}. |
| 28 | */ |
| 29 | public class DefaultCatalystTypeSerializerFactory implements TypeSerializerFactory { |
| 30 | |
| 31 | private final TypeSerializer<?> typeSerializer; |
| 32 | |
| 33 | public DefaultCatalystTypeSerializerFactory(Serializer serializer) { |
| 34 | typeSerializer = new InternalSerializer<>(serializer); |
| 35 | } |
| 36 | |
| 37 | @Override |
| 38 | public TypeSerializer<?> createSerializer(Class<?> clazz) { |
| 39 | return typeSerializer; |
| 40 | } |
| 41 | |
| 42 | private class InternalSerializer<T> implements TypeSerializer<T> { |
| 43 | |
| 44 | private final Serializer serializer; |
| 45 | |
| 46 | InternalSerializer(Serializer serializer) { |
| 47 | this.serializer = serializer; |
| 48 | } |
| 49 | |
| 50 | @Override |
| 51 | public T read(Class<T> clazz, BufferInput<?> input, |
| 52 | io.atomix.catalyst.serializer.Serializer serializer) { |
| 53 | int size = input.readInt(); |
| 54 | byte[] payload = new byte[size]; |
| 55 | input.read(payload); |
| 56 | return this.serializer.decode(payload); |
| 57 | } |
| 58 | |
| 59 | @Override |
| 60 | public void write(T object, BufferOutput<?> output, |
| 61 | io.atomix.catalyst.serializer.Serializer serializer) { |
| 62 | byte[] payload = this.serializer.encode(object); |
| 63 | output.writeInt(payload.length); |
| 64 | output.write(payload); |
| 65 | } |
| 66 | } |
| 67 | } |