1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.giraph.utils;
19
20 import org.apache.giraph.writable.kryo.KryoWritableWrapper;
21 import org.apache.hadoop.conf.Configuration;
22
23
24
25
26 public class ConfigurationObjectUtils {
27
28 private ConfigurationObjectUtils() {
29 }
30
31
32
33
34
35
36
37 public static String encodeBytes(byte[] bytes) {
38 StringBuilder strBuf = new StringBuilder();
39 for (int i = 0; i < bytes.length; i++) {
40 strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ('a')));
41 strBuf.append((char) (((bytes[i]) & 0xF) + ('a')));
42 }
43 return strBuf.toString();
44 }
45
46
47
48
49
50
51
52 public static byte[] decodeBytes(String str) {
53 byte[] bytes = new byte[str.length() / 2];
54 for (int i = 0; i < str.length(); i += 2) {
55 char c = str.charAt(i);
56 bytes[i / 2] = (byte) ((c - 'a') << 4);
57 c = str.charAt(i + 1);
58 bytes[i / 2] += c - 'a';
59 }
60 return bytes;
61 }
62
63
64
65
66
67
68
69
70 public static void setByteArray(byte[] data, String confOption,
71 Configuration conf) {
72 conf.set(confOption, encodeBytes(data));
73 }
74
75
76
77
78
79
80
81
82 public static byte[] getByteArray(String confOption,
83 Configuration conf) {
84 return decodeBytes(conf.get(confOption));
85 }
86
87
88
89
90
91
92
93
94
95 public static <T> void setObjectKryo(T object, String confOption,
96 Configuration conf) {
97 setByteArray(WritableUtils.toByteArrayUnsafe(
98 new KryoWritableWrapper<>(object)),
99 confOption, conf);
100 }
101
102
103
104
105
106
107
108
109
110 public static <T> T getObjectKryo(String confOption,
111 Configuration conf) {
112 KryoWritableWrapper<T> wrapper = new KryoWritableWrapper<>();
113 WritableUtils.fromByteArrayUnsafe(
114 getByteArray(confOption, conf), wrapper,
115 new UnsafeReusableByteArrayInput());
116 return wrapper.get();
117 }
118 }