0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018 package org.apache.spark.util.kvstore;
0019
0020 import java.io.ByteArrayInputStream;
0021 import java.io.ByteArrayOutputStream;
0022 import java.util.zip.GZIPInputStream;
0023 import java.util.zip.GZIPOutputStream;
0024 import static java.nio.charset.StandardCharsets.UTF_8;
0025
0026 import com.fasterxml.jackson.databind.ObjectMapper;
0027
0028 import org.apache.spark.annotation.Private;
0029
0030
0031
0032
0033
0034
0035
0036
0037
0038 @Private
0039 public class KVStoreSerializer {
0040
0041
0042
0043
0044
0045
0046 protected final ObjectMapper mapper;
0047
0048 public KVStoreSerializer() {
0049 this.mapper = new ObjectMapper();
0050 }
0051
0052 public final byte[] serialize(Object o) throws Exception {
0053 if (o instanceof String) {
0054 return ((String) o).getBytes(UTF_8);
0055 } else {
0056 ByteArrayOutputStream bytes = new ByteArrayOutputStream();
0057 try (GZIPOutputStream out = new GZIPOutputStream(bytes)) {
0058 mapper.writeValue(out, o);
0059 }
0060 return bytes.toByteArray();
0061 }
0062 }
0063
0064 @SuppressWarnings("unchecked")
0065 public final <T> T deserialize(byte[] data, Class<T> klass) throws Exception {
0066 if (klass.equals(String.class)) {
0067 return (T) new String(data, UTF_8);
0068 } else {
0069 try (GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(data))) {
0070 return mapper.readValue(in, klass);
0071 }
0072 }
0073 }
0074
0075 final byte[] serialize(long value) {
0076 return String.valueOf(value).getBytes(UTF_8);
0077 }
0078
0079 final long deserializeLong(byte[] data) {
0080 return Long.parseLong(new String(data, UTF_8));
0081 }
0082
0083 }