View Javadoc
1   /*
2    * Copyright 2014 Luca Burgazzoli
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  
17  package net.anyflow.lannister.serialization;
18  
19  import java.io.IOException;
20  
21  import com.fasterxml.jackson.core.JsonFactory;
22  import com.fasterxml.jackson.databind.ObjectMapper;
23  import com.fasterxml.jackson.dataformat.smile.SmileFactory;
24  import com.hazelcast.nio.ObjectDataInput;
25  import com.hazelcast.nio.ObjectDataOutput;
26  import com.hazelcast.nio.serialization.Serializer;
27  import com.hazelcast.nio.serialization.StreamSerializer;
28  
29  public final class JsonSerializer<T> extends HazelcastSerializer<T, ObjectMapper> implements StreamSerializer<T> {
30  	public static final int TYPEID_JSON_PLAIN = 100;
31  	public static final int TYPEID_JSON_BINARY = 101;
32  
33  	private JsonSerializer(Class<T> type, int typeId) {
34  		this(type, typeId, null);
35  	}
36  
37  	private JsonSerializer(Class<T> type, int typeId, final JsonFactory factory) {
38  		super(type, typeId, () -> new ObjectMapper(factory));
39  	}
40  
41  	@Override
42  	public void write(ObjectDataOutput out, T object) throws IOException {
43  		out.writeByteArray(get().writeValueAsBytes(object));
44  	}
45  
46  	@Override
47  	public T read(ObjectDataInput in) throws IOException {
48  		return get().readValue(in.readByteArray(), getType());
49  	}
50  
51  	public static <V> Serializer makeBinary(final Class<V> type) {
52  		return new JsonSerializer<>(type, TYPEID_JSON_BINARY, new SmileFactory());
53  	}
54  
55  	public static <V> Serializer makePlain(final Class<V> type) {
56  		return new JsonSerializer<>(type, TYPEID_JSON_PLAIN);
57  	}
58  }