Project

General

Profile

1
package eu.dnetlib.clients.index.model.util;
2

    
3
import java.util.*;
4
import java.util.Map.Entry;
5

    
6
import eu.dnetlib.clients.index.model.*;
7
import eu.dnetlib.clients.index.model.impl.DefaultDataFactoryImpl;
8

    
9
/**
10
 * utility class for handling / conversion of Any objects.
11
 * <p>
12
 * Hint: The Any-to-JSON conversion for Date(Time)s is not symmetric. If the Any object contains Date(Time) values, they will be serialized
13
 * to String values in simple timestamp format. But when parsing JSON to an Any object, Date(Time) strings will not be recognized anymore,
14
 * but just read as String values.
15
 */
16
public class AnyUtil {
17

    
18
	/**
19
	 * Immutable empty AnyMap instance.
20
	 */
21
	public static final AnyMap EMPTY_MAP = DefaultDataFactoryImpl.IMMUTABLE_EMPTY_MAP;
22

    
23
	/**
24
	 * prevent instance creation.
25
	 */
26
	protected AnyUtil() {
27
		// prevent instance creation
28
	}
29

    
30
	/**
31
	 * Converts an Any object into a native java object.
32
	 *
33
	 * @param any the Any object
34
	 * @return a Pojo
35
	 */
36
	public static Object anyToNative(final Any any) {
37
		if (any.isMap()) {
38
			final LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
39
			for (final Iterator<String> kIt = ((AnyMap) any).keySet().iterator(); kIt.hasNext(); ) {
40
				final String key = kIt.next();
41
				map.put(key, anyToNative(((AnyMap) any).get(key)));
42
			}
43
			return map;
44
		} else if (any.isSeq()) {
45
			final ArrayList<Object> list = new ArrayList<Object>();
46
			for (final Iterator<Any> aIt = any.iterator(); aIt.hasNext(); ) {
47
				final Any a = aIt.next();
48
				list.add(anyToNative(a));
49
			}
50
			return list;
51
		} else if (any.isString()) return ((Value) any).asString();
52
		else if (any.isLong()) return ((Value) any).asLong();
53
		else if (any.isDouble()) return ((Value) any).asDouble();
54
		else if (any.isBoolean()) return ((Value) any).asBoolean();
55
		else if (any.isDate()) return ((Value) any).asDate();
56
		else if (any.isDateTime()) return ((Value) any).asDateTime();
57
		else return ((Value) any).getObject();
58
	}
59

    
60
	/**
61
	 * Converts an object to an Any (recursively). The leaf object(s) must be convertable by {@link DataFactory#autoConvertValue(Object)}.
62
	 *
63
	 * @param object The object to be converted. Supported (and tested in this order) are
64
	 *               <ul>
65
	 *               <li>{@code Map<String, Object>}
66
	 *               <li>{@code Collections<Object>}
67
	 *               <li>{@code Object[]}
68
	 *               <li>Any other object that can be {@link DataFactory#autoConvertValue(Object)}</li>
69
	 *               </ul>
70
	 * @return The converted Any
71
	 */
72
	@SuppressWarnings("unchecked")
73
	public static Any objectToAny(final Object object) {
74
		Any value = null;
75
		if (object instanceof Any) return (Any) object;
76
		else if (object instanceof Map<?, ?>) {
77
			value = mapToAny((Map<String, Object>) object);
78
		} else if (object instanceof Collection<?>) {
79
			value = collectionToAny((Collection<Object>) object);
80
		} else if (object.getClass().isArray()) {
81
			Object[] array = (Object[]) object;
82
			value = collectionToAny(Arrays.asList(array));
83
		} else {
84
			value = scalarObjectToAny(object);
85
		}
86
		return value;
87
	}
88

    
89
	/**
90
	 * Converts a collection to an AnySeq object.
91
	 *
92
	 * @param objects The list of objects to convert.
93
	 * @return An AnySeq containing the objects as Any objects.
94
	 */
95
	private static AnySeq collectionToAny(final Collection<Object> objects) {
96
		AnySeq anySeq = null;
97
		if (objects != null) {
98
			anySeq = DataFactory.DEFAULT.createAnySeq();
99
			for (final Object obj : objects) {
100
				anySeq.add(objectToAny(obj));
101
			}
102
		}
103
		return anySeq;
104
	}
105

    
106
	/**
107
	 * Converts a scalar object to a Value object.
108
	 *
109
	 * @param obj The object to convert.
110
	 * @return A Value representing the object.
111
	 */
112
	private static Any scalarObjectToAny(final Object obj) {
113
		return DataFactory.DEFAULT.autoConvertValue(obj);
114
	}
115

    
116
	/**
117
	 * Converts a map to an AnyMap object.
118
	 *
119
	 * @param map The map (String to Object) to convert.
120
	 * @return An AnyMap representing the map with all Objects converted to Any.
121
	 */
122
	private static AnyMap mapToAny(final Map<String, Object> map) {
123
		AnyMap anyMap = null;
124
		if (map != null) {
125
			anyMap = DataFactory.DEFAULT.createAnyMap();
126
			for (final Entry<String, Object> entry : map.entrySet()) {
127
				anyMap.put(entry.getKey(), objectToAny(entry.getValue()));
128
			}
129
		}
130
		return anyMap;
131
	}
132

    
133
	/**
134
	 * get value for given path(list of keys) from AnyMap object. This methods throws no exception, if the path not exists an empty Any is
135
	 * the result.
136
	 *
137
	 * @param any  the Any object.
138
	 * @param path path to the entry.
139
	 * @return value associated to the path.
140
	 */
141
	public static Any saveGet(final Any any, final String[] path) {
142
		if (path.length == 0) return DataFactory.DEFAULT.createAnyMap();
143
		try {
144
			Any current = any;
145
			for (final String key : path) {
146
				if (current.isMap()) {
147
					current = ((AnyMap) current).get(key);
148
				} else {
149
					current = null;
150
				}
151
			}
152
			if (current == null) return DataFactory.DEFAULT.createStringValue("undef");
153
			else return current;
154
		} catch (final Exception e) {
155
			return DataFactory.DEFAULT.createStringValue("undef");
156
		}
157
	}
158

    
159
	/**
160
	 * convert an exception to an any object.
161
	 *
162
	 * @param e exception to convert
163
	 * @return any representation of exception
164
	 */
165
	public static AnyMap exceptionToAny(final Throwable e) {
166
		return exceptionToAny(e, new HashSet<String>());
167
	}
168

    
169
	/**
170
	 * convert an exception to an any object. stop in stacktrace printing when hitting known lines again.
171
	 *
172
	 * @param e            exception to convert
173
	 * @param visitedLines lines that have been added to stacktraces before.
174
	 * @return any representation of exception
175
	 */
176
	private static AnyMap exceptionToAny(final Throwable e, final Collection<String> visitedLines) {
177
		final AnyMap any = DataFactory.DEFAULT.createAnyMap();
178
		any.put("type", e.getClass().getName());
179
		if (e.getMessage() != null) {
180
			any.put("message", e.getMessage());
181
		}
182
		final AnySeq st = DataFactory.DEFAULT.createAnySeq();
183
		for (final StackTraceElement stElement : e.getStackTrace()) {
184
			final String line = stElement.toString();
185
			st.add(line);
186
			if (!visitedLines.add(line)) {
187
				st.add("...");
188
				break;
189
			}
190
		}
191
		any.put("at", st);
192
		if ((e.getCause() != null) && (e.getCause() != e)) {
193
			any.put("causedBy", exceptionToAny(e.getCause(), visitedLines));
194
		}
195
		return any;
196
	}
197

    
198
	/**
199
	 * null save version.
200
	 */
201
	public static Double asDouble(final Any any) {
202
		return any == null ? null : any.asValue().asDouble();
203
	}
204

    
205
	;
206

    
207
	/**
208
	 * null save version.
209
	 */
210
	public static Boolean asBoolean(final Any any) {
211
		return any == null ? null : any.asValue().asBoolean();
212
	}
213

    
214
	;
215

    
216
	/**
217
	 * null save version.
218
	 */
219
	public static Date asDateTime(final Any any) {
220
		return any == null ? null : any.asValue().asDateTime();
221
	}
222

    
223
	;
224

    
225
	/**
226
	 * null save version.
227
	 */
228
	public static Date asDate(final Any any) {
229
		return any == null ? null : any.asValue().asDate();
230
	}
231

    
232
	;
233

    
234
	/**
235
	 * null save version.
236
	 */
237
	public static Long asLong(final Any any) {
238
		return any == null ? null : any.asValue().asLong();
239
	}
240

    
241
	;
242

    
243
	/**
244
	 * null save version.
245
	 */
246
	public static String asString(final Any any) {
247
		return any == null ? null : any.asValue().asString();
248
	}
249

    
250
	;
251

    
252
	/**
253
	 * null save version.
254
	 */
255
	public static AnyMap asMap(final Any any) {
256
		return any == null ? null : any.asMap();
257
	}
258

    
259
	;
260

    
261
	/**
262
	 * null save version.
263
	 */
264
	public static AnySeq asSeq(final Any any) {
265
		return any == null ? null : any.asSeq();
266
	}
267

    
268
	;
269

    
270
	/**
271
	 * convert AnyMap to java.util.Properties.
272
	 */
273
	public static Properties anyToProperties(final AnyMap anyMap) {
274
		Properties props = new Properties();
275
		final Set<String> keySet = anyMap.keySet();
276
		for (final String key : keySet) {
277
			props.put(key, anyMap.get(key).toString());
278
		}
279
		return props;
280
	}
281

    
282
	/**
283
	 * convert java.util.Properties to AnyMap.
284
	 */
285
	public static AnyMap propertiesToAny(final Properties props) {
286
		final AnyMap any = DataFactory.DEFAULT.createAnyMap();
287
		final Set<String> propNames = props.stringPropertyNames();
288
		for (final String prop : propNames) {
289
			any.put(prop, props.getProperty(prop));
290
		}
291
		return any;
292
	}
293

    
294
	/**
295
	 * returns the 1st map in the give SEQ that contains a value with the given name value, or null if not found.
296
	 * <p>
297
	 * This is often useful for configs that are contained in a seq such as search filters.
298
	 *
299
	 * @since 1.1
300
	 */
301
	public static AnyMap findMapInSeq(final AnySeq seq, final String keyName, final String keyValue) {
302
		for (Any any : seq) {
303
			final String stringValue = any.asMap().getStringValue(keyName);
304
			if (keyValue.equals(stringValue)) return any.asMap();
305
		}
306
		return null;
307
	}
308
}
    (1-1/1)