Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: ea5fb6b3087a65734f0566ee66f1e793ac669525 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/*******************************************************************************
 * Copyright (c) 2012 Wind River Systems, Inc. and others. All rights reserved.
 * This program and the accompanying materials are made available under the terms
 * of the Eclipse Public License v1.0 which accompanies this distribution, and is
 * available at http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Wind River Systems - initial API and implementation
 *******************************************************************************/

package org.eclipse.tcf.te.runtime.persistence.delegates;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.tcf.te.runtime.extensions.ExecutableExtension;
import org.eclipse.tcf.te.runtime.interfaces.properties.IPropertiesContainer;
import org.eclipse.tcf.te.runtime.persistence.PersistenceManager;
import org.eclipse.tcf.te.runtime.persistence.interfaces.IPersistenceDelegate;
import org.eclipse.tcf.te.runtime.persistence.interfaces.IVariableDelegate;
import org.eclipse.tcf.te.runtime.properties.PropertiesContainer;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * GsonMapPersistenceDelegate
 */
public class GsonMapPersistenceDelegate extends ExecutableExtension implements IPersistenceDelegate {

	private final String defaultFileExtension;

	protected static final String VARIABLES = "__VariablesMap__"; //$NON-NLS-1$

	/**
	 * Constructor.
	 */
	public GsonMapPersistenceDelegate() {
		this("json"); //$NON-NLS-1$
	}

	/**
	 * Constructor.
	 */
	public GsonMapPersistenceDelegate(String defaultFileExtension) {
		super();
		Assert.isNotNull(defaultFileExtension);
		this.defaultFileExtension = defaultFileExtension;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.runtime.persistence.interfaces.IPersistenceDelegate#getPersistedClass(java.lang.Object)
	 */
	@Override
	public Class<?> getPersistedClass(Object context) {
		return Map.class;
	}

	/**
	 * Return the default file extension if container is an URI.
	 */
	protected String getDefaultFileExtension() {
		return defaultFileExtension;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.runtime.persistence.interfaces.IPersistenceDelegate#writeList(java.lang.Object[], java.lang.Object)
	 */
	@Override
	public Object writeList(Object[] context, Object container) throws IOException {
		Assert.isNotNull(context);
		Assert.isNotNull(container);

		return write(context, container, true);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.runtime.persistence.interfaces.IPersistenceDelegate#write(java.lang.Object, java.lang.Object)
	 */
	@Override
	public final Object write(Object context, Object container) throws IOException {
		Assert.isNotNull(context);
		Assert.isNotNull(container);

		return write(context, container, false);
	}

	private Object write(Object context, Object container, boolean isList) throws IOException {
		Assert.isNotNull(context);
		Assert.isNotNull(container);

		if (container instanceof URI) {
			URI uri = (URI) container;

			// Only "file:" URIs are supported
			if (!"file".equalsIgnoreCase(uri.getScheme())) { //$NON-NLS-1$
				throw new IOException("Unsupported URI schema '" + uri.getScheme() + "'"); //$NON-NLS-1$ //$NON-NLS-2$
			}

			// Create the file object from the given URI
			File file = new File(uri.normalize());

			// The file must be absolute
			if (!file.isAbsolute()) {
				throw new IOException("URI must denote an absolute file path."); //$NON-NLS-1$
			}

			// If the file defaultFileExtension is no set, default to "properties"
			IPath path = new Path(file.getCanonicalPath());
			if (path.getFileExtension() == null) {
				file = path.addFileExtension(getDefaultFileExtension()).toFile();
			}

			Gson gson = new GsonBuilder().setPrettyPrinting().create();
			Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); //$NON-NLS-1$
			if (!isList) {
				try {
					gson.toJson(internalToMap(context), Map.class, writer);
				}
				finally {
					writer.close();
				}
			}
			else {
				List<String> encoded = new ArrayList<String>();
				for (Object entry : (Object[]) context) {
					encoded.add(gson.toJson(internalToMap(entry)));
				}
				try {
					gson.toJson(encoded, List.class, writer);
				}
				finally {
					writer.close();
				}
			}
		}
		else if (String.class.equals(container)) {
			Gson gson = new GsonBuilder().create();

			if (!isList) {
				container = gson.toJson(internalToMap(context));
			}
			else {
				List<String> encoded = new ArrayList<String>();
				for (Object entry : (Object[]) context) {
					encoded.add(gson.toJson(internalToMap(entry)));
				}
				container = gson.toJson(encoded);
			}
		}

		return container;
	}

	/*
	 * Convert the context to a Map, extract and use variables and add them to the map as key
	 * VARIABLE.
	 */
	private Map<String, Object> internalToMap(Object context) {
		try {
			Map<String, Object> data = toMap(context);

			if (data != null) {
				Map<String, String> variables = null;
				IVariableDelegate[] delegates = PersistenceManager.getInstance()
				                .getVariableDelegates(this);
				for (IVariableDelegate delegate : delegates) {
					variables = delegate.getVariables(data);
				}
				if (variables != null && !variables.isEmpty()) {
					data.put(VARIABLES, variables);
				}
			}
			return data;
		}
		catch (Exception e) {

		}

		return null;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.runtime.persistence.interfaces.IPersistenceDelegate#readList(java.lang.Class, java.lang.Object)
	 */
	@Override
	public Object[] readList(Class<?> contextClass, Object container) throws IOException {
		Assert.isNotNull(container);
		return (Object[])read(contextClass, container, true);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.runtime.persistence.interfaces.IPersistenceDelegate#read(java.lang.Object, java.lang.Object)
	 */
	@Override
	public final Object read(Object context, Object container) throws IOException {
		Assert.isNotNull(container);
		return read(context, container, false);
	}

	private Object read(Object context, Object container, boolean isList) throws IOException {
		Assert.isNotNull(container);

		Gson gson = new GsonBuilder().create();
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();

		if (container instanceof URI) {
			URI uri = (URI) container;

			// Only "file:" URIs are supported
			if (!"file".equalsIgnoreCase(uri.getScheme())) { //$NON-NLS-1$
				throw new IOException("Unsupported URI schema '" + uri.getScheme() + "'"); //$NON-NLS-1$ //$NON-NLS-2$
			}

			// Create the file object from the given URI
			File file = new File(uri.normalize());

			// The file must be absolute
			if (!file.isAbsolute()) {
				throw new IOException("URI must denote an absolute file path."); //$NON-NLS-1$
			}

			if (!file.exists()) {
				IPath path = new Path(file.getCanonicalPath());
				if (path.getFileExtension() == null) {
					file = path.addFileExtension(getDefaultFileExtension()).toFile();
				}
			}

			Reader reader = new InputStreamReader(new FileInputStream(file), "UTF-8"); //$NON-NLS-1$
			if (!isList) {
				try {
					data.add(gson.fromJson(reader, Map.class));
				}
				finally {
					reader.close();
				}
			}
			else {
				try {
					List<String> strings = gson.fromJson(reader, List.class);
					for (String string : strings) {
						data.add(gson.fromJson(string, Map.class));
					}
				}
				finally {
					reader.close();
				}
			}
		}
		else if (container instanceof String) {
			if (!isList) {
				data.add(gson.fromJson((String) container, Map.class));
			}
			else {
				List<String> strings = gson.fromJson((String) container, List.class);
				for (String string : strings) {
					data.add(gson.fromJson(string, Map.class));
				}
			}
		}

		for (Map<String, Object> entry : data) {
			Map<String, String> variables = new HashMap<String, String>();
			if (entry.containsKey(VARIABLES)) {
				variables = (Map<String, String>) entry.remove(VARIABLES);
			}
			IVariableDelegate[] delegates = PersistenceManager.getInstance()
			                .getVariableDelegates(this);
			for (IVariableDelegate delegate : delegates) {
				entry = delegate.putVariables(entry, variables);
			}
		}

		if (!isList) {
			return !data.isEmpty() ? fromMap(data.get(0), context) : context;
		}

		List<Object> list = new ArrayList<Object>();
		for (Map<String, Object> entry : data) {
			list.add(fromMap(entry, context));
		}
		return list.toArray();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.runtime.persistence.interfaces.IPersistenceDelegate#delete(java.lang.Object, java.lang.Object)
	 */
	@Override
	public boolean delete(Object context, Object container) throws IOException {
		Assert.isNotNull(container);

		if (container instanceof URI) {
			URI uri = (URI) container;

			// Only "file:" URIs are supported
			if (!"file".equalsIgnoreCase(uri.getScheme())) { //$NON-NLS-1$
				throw new IOException("Unsupported URI schema '" + uri.getScheme() + "'"); //$NON-NLS-1$ //$NON-NLS-2$
			}

			// Create the file object from the given URI
			File file = new File(uri.normalize());

			// The file must be absolute
			if (!file.isAbsolute()) {
				throw new IOException("URI must denote an absolute file path."); //$NON-NLS-1$
			}

			if (!file.exists()) {
				IPath path = new Path(file.getCanonicalPath());
				if (path.getFileExtension() == null) {
					file = path.addFileExtension(getDefaultFileExtension()).toFile();
				}
			}

			// If the file defaultFileExtension is no set, default to "properties"
			IPath path = new Path(file.getCanonicalPath());
			if (path.getFileExtension() == null) {
				file = path.addFileExtension(getDefaultFileExtension()).toFile();
			}

			return file.delete();
		}

		return false;
	}

	/**
	 * Convert the given context to map.
	 *
	 * @param context The context. Must not be <code>null</code>.
	 * @return Map representing the context.
	 *
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	protected Map<String, Object> toMap(final Object context) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();

		Map<String, Object> attrs = null;
		if (context instanceof Map) {
			attrs = (Map<String, Object>) context;
		}
		else if (context instanceof IPropertiesContainer) {
			IPropertiesContainer container = (IPropertiesContainer) context;
			attrs = new HashMap<String, Object>(container.getProperties());
		}

		if (attrs != null) {
			for (Entry<String, Object> entry : attrs.entrySet()) {
				if (!entry.getKey().endsWith(".transient")) { //$NON-NLS-1$
					result.put(entry.getKey(), entry.getValue());
				}
			}
		}

		return result;
	}

	/**
	 * Convert a map into the needed context object.
	 *
	 * @param map The map representing the context. Must not be <code>null</code>.
	 * @param context The context to put the map values in or <code>null</code>.
	 * @return The context object.
	 *
	 * @throws IOException
	 */
	protected Object fromMap(Map<String, Object> map, Object context) throws IOException {
		if (context == null || Map.class.equals(context)) {
			return map;
		}
		else if (context instanceof Map) {
			@SuppressWarnings({ "rawtypes", "unchecked" })
			Map<String, Object> newMap = new HashMap<String, Object>((Map) context);
			newMap.putAll(map);
			return newMap;
		}
		else if (IPropertiesContainer.class.equals(context.getClass())) {
			IPropertiesContainer container = new PropertiesContainer();
			container.setProperties(map);

			return container;
		}
		else if (context instanceof IPropertiesContainer) {
			IPropertiesContainer container = (IPropertiesContainer) context;
			container.setProperties(map);

			return container;
		}

		return null;
	}
}

Back to the top