1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.giraph.conf;
19
20 import org.apache.hadoop.conf.Configuration;
21 import org.apache.log4j.Logger;
22 import org.codehaus.jackson.map.ObjectMapper;
23 import org.codehaus.jackson.type.TypeReference;
24
25 import java.io.IOException;
26
27
28
29
30 public class JsonStringConfOption extends AbstractConfOption {
31
32 private static final Logger LOG =
33 Logger.getLogger(JsonStringConfOption.class);
34
35
36
37
38
39
40
41 public JsonStringConfOption(String key, String description) {
42 super(key, description);
43 }
44
45
46
47
48
49
50
51 public void set(Configuration conf, Object value) {
52 ObjectMapper mapper = new ObjectMapper();
53 String jsonStr;
54 try {
55 jsonStr = mapper.writeValueAsString(value);
56 conf.set(getKey(), jsonStr);
57 } catch (IOException e) {
58 throw new IllegalStateException("Failed to set " + getKey() +
59 " with json value from " + value);
60 }
61 }
62
63
64
65
66
67
68
69 public String getRaw(Configuration conf) {
70 return conf.get(getKey());
71 }
72
73
74
75
76
77
78
79
80
81 public <T> T get(Configuration conf, Class<T> klass) {
82 String jsonStr = getRaw(conf);
83 T value = null;
84 if (jsonStr != null) {
85 ObjectMapper mapper = new ObjectMapper();
86 try {
87 value = mapper.readValue(jsonStr, klass);
88 } catch (IOException e) {
89 throw new IllegalStateException("Failed to read json from key " +
90 getKey() + " with class " + klass);
91 }
92 }
93 return value;
94 }
95
96
97
98
99
100
101
102
103
104 public <T> T get(Configuration conf, TypeReference<T> typeReference) {
105 String jsonStr = getRaw(conf);
106 T value = null;
107 if (jsonStr != null) {
108 ObjectMapper mapper = new ObjectMapper();
109 try {
110 value = mapper.<T>readValue(jsonStr, typeReference);
111 } catch (IOException e) {
112 throw new IllegalStateException("Failed to read json from key " +
113 getKey() + " with class " + typeReference);
114 }
115 }
116 return value;
117 }
118
119
120
121
122
123
124
125
126
127
128 public <T> T getWithDefault(Configuration conf, Class<T> klass,
129 T defaultValue) {
130 if (contains(conf)) {
131 return get(conf, klass);
132 } else {
133 return defaultValue;
134 }
135 }
136
137 @Override
138 public String getDefaultValueStr() {
139 return "null";
140 }
141
142 @Override
143 public boolean isDefaultValue(Configuration conf) {
144 return !contains(conf);
145 }
146
147 @Override
148 public ConfOptionType getType() {
149 return ConfOptionType.STRING;
150 }
151 }