1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.data;
|
---|
3 |
|
---|
4 | import java.io.StringReader;
|
---|
5 | import java.io.StringWriter;
|
---|
6 | import java.lang.annotation.Retention;
|
---|
7 | import java.lang.annotation.RetentionPolicy;
|
---|
8 | import java.lang.reflect.Field;
|
---|
9 | import java.util.ArrayList;
|
---|
10 | import java.util.Collection;
|
---|
11 | import java.util.Collections;
|
---|
12 | import java.util.HashMap;
|
---|
13 | import java.util.LinkedHashMap;
|
---|
14 | import java.util.List;
|
---|
15 | import java.util.Map;
|
---|
16 | import java.util.Objects;
|
---|
17 | import java.util.Optional;
|
---|
18 | import java.util.Set;
|
---|
19 | import java.util.stream.Collectors;
|
---|
20 |
|
---|
21 | import javax.json.Json;
|
---|
22 | import javax.json.JsonArray;
|
---|
23 | import javax.json.JsonArrayBuilder;
|
---|
24 | import javax.json.JsonObject;
|
---|
25 | import javax.json.JsonObjectBuilder;
|
---|
26 | import javax.json.JsonReader;
|
---|
27 | import javax.json.JsonString;
|
---|
28 | import javax.json.JsonValue;
|
---|
29 | import javax.json.JsonWriter;
|
---|
30 |
|
---|
31 | import org.openstreetmap.josm.spi.preferences.IPreferences;
|
---|
32 | import org.openstreetmap.josm.tools.JosmRuntimeException;
|
---|
33 | import org.openstreetmap.josm.tools.Logging;
|
---|
34 | import org.openstreetmap.josm.tools.MultiMap;
|
---|
35 | import org.openstreetmap.josm.tools.Utils;
|
---|
36 |
|
---|
37 | /**
|
---|
38 | * Utility methods to convert struct-like classes to a string map and back.
|
---|
39 | *
|
---|
40 | * A "struct" is a class that has some fields annotated with {@link StructEntry}.
|
---|
41 | * Those fields will be respected when converting an object to a {@link Map} and
|
---|
42 | * back.
|
---|
43 | * @since 12851
|
---|
44 | */
|
---|
45 | public final class StructUtils {
|
---|
46 |
|
---|
47 | private StructUtils() {
|
---|
48 | // hide constructor
|
---|
49 | }
|
---|
50 |
|
---|
51 | /**
|
---|
52 | * Annotation used for converting objects to String Maps and vice versa.
|
---|
53 | * Indicates that a certain field should be considered in the conversion process. Otherwise it is ignored.
|
---|
54 | *
|
---|
55 | * @see #serializeStruct(java.lang.Object, java.lang.Class)
|
---|
56 | * @see #deserializeStruct(java.util.Map, java.lang.Class)
|
---|
57 | */
|
---|
58 | @Retention(RetentionPolicy.RUNTIME) // keep annotation at runtime
|
---|
59 | public @interface StructEntry { }
|
---|
60 |
|
---|
61 | /**
|
---|
62 | * Annotation used for converting objects to String Maps.
|
---|
63 | * Indicates that a certain field should be written to the map, even if the value is the same as the default value.
|
---|
64 | *
|
---|
65 | * @see #serializeStruct(java.lang.Object, java.lang.Class)
|
---|
66 | */
|
---|
67 | @Retention(RetentionPolicy.RUNTIME) // keep annotation at runtime
|
---|
68 | public @interface WriteExplicitly { }
|
---|
69 |
|
---|
70 | /**
|
---|
71 | * Get a list of hashes which are represented by a struct-like class.
|
---|
72 | * Possible properties are given by fields of the class klass that have the @pref annotation.
|
---|
73 | * Default constructor is used to initialize the struct objects, properties then override some of these default values.
|
---|
74 | * @param <T> klass type
|
---|
75 | * @param preferences preferences to look up the value
|
---|
76 | * @param key main preference key
|
---|
77 | * @param klass The struct class
|
---|
78 | * @return a list of objects of type T or an empty list if nothing was found
|
---|
79 | */
|
---|
80 | public static <T> List<T> getListOfStructs(IPreferences preferences, String key, Class<T> klass) {
|
---|
81 | return Optional.ofNullable(getListOfStructs(preferences, key, null, klass)).orElseGet(Collections::emptyList);
|
---|
82 | }
|
---|
83 |
|
---|
84 | /**
|
---|
85 | * same as above, but returns def if nothing was found
|
---|
86 | * @param <T> klass type
|
---|
87 | * @param preferences preferences to look up the value
|
---|
88 | * @param key main preference key
|
---|
89 | * @param def default value
|
---|
90 | * @param klass The struct class
|
---|
91 | * @return a list of objects of type T or {@code def} if nothing was found
|
---|
92 | */
|
---|
93 | public static <T> List<T> getListOfStructs(IPreferences preferences, String key, Collection<T> def, Class<T> klass) {
|
---|
94 | List<Map<String, String>> prop =
|
---|
95 | preferences.getListOfMaps(key, def == null ? null : serializeListOfStructs(def, klass));
|
---|
96 | if (prop == null)
|
---|
97 | return def == null ? null : new ArrayList<>(def);
|
---|
98 | return prop.stream().map(p -> deserializeStruct(p, klass)).collect(Collectors.toList());
|
---|
99 | }
|
---|
100 |
|
---|
101 | /**
|
---|
102 | * Convenience method that saves a MapListSetting which is provided as a collection of objects.
|
---|
103 | *
|
---|
104 | * Each object is converted to a <code>Map<String, String></code> using the fields with {@link StructEntry} annotation.
|
---|
105 | * The field name is the key and the value will be converted to a string.
|
---|
106 | *
|
---|
107 | * Considers only fields that have the {@code @StructEntry} annotation.
|
---|
108 | * In addition it does not write fields with null values. (Thus they are cleared)
|
---|
109 | * Default values are given by the field values after default constructor has been called.
|
---|
110 | * Fields equal to the default value are not written unless the field has the {@link WriteExplicitly} annotation.
|
---|
111 | * @param <T> the class,
|
---|
112 | * @param preferences the preferences to save to
|
---|
113 | * @param key main preference key
|
---|
114 | * @param val the list that is supposed to be saved
|
---|
115 | * @param klass The struct class
|
---|
116 | * @return true if something has changed
|
---|
117 | */
|
---|
118 | public static <T> boolean putListOfStructs(IPreferences preferences, String key, Collection<T> val, Class<T> klass) {
|
---|
119 | return preferences.putListOfMaps(key, serializeListOfStructs(val, klass));
|
---|
120 | }
|
---|
121 |
|
---|
122 | private static <T> List<Map<String, String>> serializeListOfStructs(Collection<T> l, Class<T> klass) {
|
---|
123 | if (l == null)
|
---|
124 | return null;
|
---|
125 | List<Map<String, String>> vals = new ArrayList<>();
|
---|
126 | for (T struct : l) {
|
---|
127 | if (struct != null) {
|
---|
128 | vals.add(serializeStruct(struct, klass));
|
---|
129 | }
|
---|
130 | }
|
---|
131 | return vals;
|
---|
132 | }
|
---|
133 |
|
---|
134 | /**
|
---|
135 | * Convert an object to a String Map, by using field names and values as map key and value.
|
---|
136 | *
|
---|
137 | * The field value is converted to a String.
|
---|
138 | *
|
---|
139 | * Only fields with annotation {@link StructEntry} are taken into account.
|
---|
140 | *
|
---|
141 | * Fields will not be written to the map if the value is null or unchanged
|
---|
142 | * (compared to an object created with the no-arg-constructor).
|
---|
143 | * The {@link WriteExplicitly} annotation overrides this behavior, i.e. the default value will also be written.
|
---|
144 | *
|
---|
145 | * @param <T> the class of the object <code>struct</code>
|
---|
146 | * @param struct the object to be converted
|
---|
147 | * @param klass the class T
|
---|
148 | * @return the resulting map (same data content as <code>struct</code>)
|
---|
149 | */
|
---|
150 | @SuppressWarnings("deprecation")
|
---|
151 | public static <T> Map<String, String> serializeStruct(T struct, Class<T> klass) {
|
---|
152 | T structPrototype;
|
---|
153 | try {
|
---|
154 | structPrototype = klass.getConstructor().newInstance();
|
---|
155 | } catch (ReflectiveOperationException ex) {
|
---|
156 | throw new IllegalArgumentException(ex);
|
---|
157 | }
|
---|
158 |
|
---|
159 | Map<String, String> hash = new LinkedHashMap<>();
|
---|
160 | for (Field f : klass.getDeclaredFields()) {
|
---|
161 | if (f.getAnnotation(Preferences.pref.class) == null && f.getAnnotation(StructEntry.class) == null) {
|
---|
162 | continue;
|
---|
163 | }
|
---|
164 | Utils.setObjectsAccessible(f);
|
---|
165 | try {
|
---|
166 | Object fieldValue = f.get(struct);
|
---|
167 | Object defaultFieldValue = f.get(structPrototype);
|
---|
168 | if (fieldValue != null && (
|
---|
169 | f.getAnnotation(Preferences.writeExplicitly.class) != null ||
|
---|
170 | f.getAnnotation(WriteExplicitly.class) != null ||
|
---|
171 | !Objects.equals(fieldValue, defaultFieldValue))) {
|
---|
172 | String key = f.getName().replace('_', '-');
|
---|
173 | if (fieldValue instanceof Map) {
|
---|
174 | hash.put(key, mapToJson((Map<?, ?>) fieldValue));
|
---|
175 | } else if (fieldValue instanceof MultiMap) {
|
---|
176 | hash.put(key, multiMapToJson((MultiMap<?, ?>) fieldValue));
|
---|
177 | } else {
|
---|
178 | hash.put(key, fieldValue.toString());
|
---|
179 | }
|
---|
180 | }
|
---|
181 | } catch (IllegalAccessException ex) {
|
---|
182 | throw new JosmRuntimeException(ex);
|
---|
183 | }
|
---|
184 | }
|
---|
185 | return hash;
|
---|
186 | }
|
---|
187 |
|
---|
188 | /**
|
---|
189 | * Converts a String-Map to an object of a certain class, by comparing map keys to field names of the class and assigning
|
---|
190 | * map values to the corresponding fields.
|
---|
191 | *
|
---|
192 | * The map value (a String) is converted to the field type. Supported types are: boolean, Boolean, int, Integer, double,
|
---|
193 | * Double, String, Map<String, String> and Map<String, List<String>>.
|
---|
194 | *
|
---|
195 | * Only fields with annotation {@link StructEntry} are taken into account.
|
---|
196 | * @param <T> the class
|
---|
197 | * @param hash the string map with initial values
|
---|
198 | * @param klass the class T
|
---|
199 | * @return an object of class T, initialized as described above
|
---|
200 | */
|
---|
201 | @SuppressWarnings("deprecation")
|
---|
202 | public static <T> T deserializeStruct(Map<String, String> hash, Class<T> klass) {
|
---|
203 | T struct = null;
|
---|
204 | try {
|
---|
205 | struct = klass.getConstructor().newInstance();
|
---|
206 | } catch (ReflectiveOperationException ex) {
|
---|
207 | throw new IllegalArgumentException(ex);
|
---|
208 | }
|
---|
209 | for (Map.Entry<String, String> keyValue : hash.entrySet()) {
|
---|
210 | Object value;
|
---|
211 | Field f;
|
---|
212 | try {
|
---|
213 | f = klass.getDeclaredField(keyValue.getKey().replace('-', '_'));
|
---|
214 | } catch (NoSuchFieldException ex) {
|
---|
215 | Logging.trace(ex);
|
---|
216 | continue;
|
---|
217 | }
|
---|
218 | if (f.getAnnotation(Preferences.pref.class) == null && f.getAnnotation(StructEntry.class) == null) {
|
---|
219 | continue;
|
---|
220 | }
|
---|
221 | Utils.setObjectsAccessible(f);
|
---|
222 | if (f.getType() == Boolean.class || f.getType() == boolean.class) {
|
---|
223 | value = Boolean.valueOf(keyValue.getValue());
|
---|
224 | } else if (f.getType() == Integer.class || f.getType() == int.class) {
|
---|
225 | try {
|
---|
226 | value = Integer.valueOf(keyValue.getValue());
|
---|
227 | } catch (NumberFormatException nfe) {
|
---|
228 | continue;
|
---|
229 | }
|
---|
230 | } else if (f.getType() == Double.class || f.getType() == double.class) {
|
---|
231 | try {
|
---|
232 | value = Double.valueOf(keyValue.getValue());
|
---|
233 | } catch (NumberFormatException nfe) {
|
---|
234 | continue;
|
---|
235 | }
|
---|
236 | } else if (f.getType() == String.class) {
|
---|
237 | value = keyValue.getValue();
|
---|
238 | } else if (f.getType().isAssignableFrom(Map.class)) {
|
---|
239 | value = mapFromJson(keyValue.getValue());
|
---|
240 | } else if (f.getType().isAssignableFrom(MultiMap.class)) {
|
---|
241 | value = multiMapFromJson(keyValue.getValue());
|
---|
242 | } else
|
---|
243 | throw new JosmRuntimeException("unsupported preference primitive type");
|
---|
244 |
|
---|
245 | try {
|
---|
246 | f.set(struct, value);
|
---|
247 | } catch (IllegalArgumentException ex) {
|
---|
248 | throw new AssertionError(ex);
|
---|
249 | } catch (IllegalAccessException ex) {
|
---|
250 | throw new JosmRuntimeException(ex);
|
---|
251 | }
|
---|
252 | }
|
---|
253 | return struct;
|
---|
254 | }
|
---|
255 |
|
---|
256 | @SuppressWarnings("rawtypes")
|
---|
257 | private static String mapToJson(Map map) {
|
---|
258 | StringWriter stringWriter = new StringWriter();
|
---|
259 | try (JsonWriter writer = Json.createWriter(stringWriter)) {
|
---|
260 | JsonObjectBuilder object = Json.createObjectBuilder();
|
---|
261 | for (Object o: map.entrySet()) {
|
---|
262 | Map.Entry e = (Map.Entry) o;
|
---|
263 | Object evalue = e.getValue();
|
---|
264 | object.add(e.getKey().toString(), evalue.toString());
|
---|
265 | }
|
---|
266 | writer.writeObject(object.build());
|
---|
267 | }
|
---|
268 | return stringWriter.toString();
|
---|
269 | }
|
---|
270 |
|
---|
271 | @SuppressWarnings({ "rawtypes", "unchecked" })
|
---|
272 | private static Map mapFromJson(String s) {
|
---|
273 | Map ret = null;
|
---|
274 | try (JsonReader reader = Json.createReader(new StringReader(s))) {
|
---|
275 | JsonObject object = reader.readObject();
|
---|
276 | ret = new HashMap(object.size());
|
---|
277 | for (Map.Entry<String, JsonValue> e: object.entrySet()) {
|
---|
278 | JsonValue value = e.getValue();
|
---|
279 | if (value instanceof JsonString) {
|
---|
280 | // in some cases, when JsonValue.toString() is called, then additional quotation marks are left in value
|
---|
281 | ret.put(e.getKey(), ((JsonString) value).getString());
|
---|
282 | } else {
|
---|
283 | ret.put(e.getKey(), e.getValue().toString());
|
---|
284 | }
|
---|
285 | }
|
---|
286 | }
|
---|
287 | return ret;
|
---|
288 | }
|
---|
289 |
|
---|
290 | @SuppressWarnings("rawtypes")
|
---|
291 | private static String multiMapToJson(MultiMap map) {
|
---|
292 | StringWriter stringWriter = new StringWriter();
|
---|
293 | try (JsonWriter writer = Json.createWriter(stringWriter)) {
|
---|
294 | JsonObjectBuilder object = Json.createObjectBuilder();
|
---|
295 | for (Object o: map.entrySet()) {
|
---|
296 | Map.Entry e = (Map.Entry) o;
|
---|
297 | Set evalue = (Set) e.getValue();
|
---|
298 | JsonArrayBuilder a = Json.createArrayBuilder();
|
---|
299 | for (Object evo: evalue) {
|
---|
300 | a.add(evo.toString());
|
---|
301 | }
|
---|
302 | object.add(e.getKey().toString(), a.build());
|
---|
303 | }
|
---|
304 | writer.writeObject(object.build());
|
---|
305 | }
|
---|
306 | return stringWriter.toString();
|
---|
307 | }
|
---|
308 |
|
---|
309 | @SuppressWarnings({ "rawtypes", "unchecked" })
|
---|
310 | private static MultiMap multiMapFromJson(String s) {
|
---|
311 | MultiMap ret = null;
|
---|
312 | try (JsonReader reader = Json.createReader(new StringReader(s))) {
|
---|
313 | JsonObject object = reader.readObject();
|
---|
314 | ret = new MultiMap(object.size());
|
---|
315 | for (Map.Entry<String, JsonValue> e: object.entrySet()) {
|
---|
316 | JsonValue value = e.getValue();
|
---|
317 | if (value instanceof JsonArray) {
|
---|
318 | for (JsonString js: ((JsonArray) value).getValuesAs(JsonString.class)) {
|
---|
319 | ret.put(e.getKey(), js.getString());
|
---|
320 | }
|
---|
321 | } else if (value instanceof JsonString) {
|
---|
322 | // in some cases, when JsonValue.toString() is called, then additional quotation marks are left in value
|
---|
323 | ret.put(e.getKey(), ((JsonString) value).getString());
|
---|
324 | } else {
|
---|
325 | ret.put(e.getKey(), e.getValue().toString());
|
---|
326 | }
|
---|
327 | }
|
---|
328 | }
|
---|
329 | return ret;
|
---|
330 | }
|
---|
331 | }
|
---|