1/*2 * Licensed to the Apache Software Foundation (ASF) under one3 * or more contributor license agreements. See the NOTICE file4 * distributed with this work for additional information5 * regarding copyright ownership. The ASF licenses this file6 * to you under the Apache License, Version 2.0 (the7 * "License"); you may not use this file except in compliance8 * with the License. You may obtain a copy of the License at9 *10 * http://www.apache.org/licenses/LICENSE-2.011 *12 * Unless required by applicable law or agreed to in writing, software13 * distributed under the License is distributed on an "AS IS" BASIS,14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15 * See the License for the specific language governing permissions and16 * limitations under the License.17 */18package org.apache.giraph.writable.kryo.serializers;
1920import java.io.DataInputStream;
21import java.io.DataOutputStream;
22import java.io.IOException;
2324import org.apache.giraph.utils.ReflectionUtils;
25import org.apache.giraph.utils.WritableUtils;
26import org.apache.hadoop.io.Writable;
2728import com.esotericsoftware.kryo.Kryo;
29import com.esotericsoftware.kryo.Serializer;
30import com.esotericsoftware.kryo.io.Input;
31import com.esotericsoftware.kryo.io.Output;
3233/**34 * A custom Serializer that will call the Writable methods defined by the35 * object itself to serialize the object, instead of Kryo auto-magically36 * serializing37 *38 * @param <T> Object type, should implement Writable39 */4041publicclass DirectWritableSerializer<T extends Writable>
42extends Serializer<T> {
4344 @Override
45publicvoid write(Kryo kryo, Output output, T object) {
46try {
47 object.write(new DataOutputStream(output));
48 } catch (IOException e) {
49thrownew RuntimeException(
50"DirectWritableSerializer.write calling Writable method of class: " +
51 object.getClass().getName() + " encountered issues", e);
52 }
53 }
5455 @Override
56public T read(Kryo kryo, Input input, Class<T> type) {
57try {
58 T object = create(kryo, input, type);
59 kryo.reference(object);
60 object.readFields(new DataInputStream(input));
6162return object;
63 } catch (IOException e) {
64thrownew RuntimeException(
65"DirectWritableSerializer.read calling Writable method of class: " +
66 type.getName() + " encountered issues", e);
67 }
68 }
6970 @Override
71public T copy(Kryo kryo, T original) {
72return WritableUtils.createCopy(original);
73 }
7475/**76 * Used by {@link #read(Kryo, Input, Class)} to create the new object.77 * This can be overridden to customize object creation, eg to call a78 * constructor with arguments. The default implementation79 * uses {@link Kryo#newInstance(Class)}.80 *81 * @param kryo Kryo object instance82 * @param input Input83 * @param type Type of the class to create84 * @return New instance of wanted type85 */86protected T create(Kryo kryo, Input input, Class<T> type) {
87return ReflectionUtils.newInstance(type);
88 }
89 }