Skip to main content
summaryrefslogtreecommitdiffstats
blob: fb6d276b4f0d49c789b89978eb118c81effde4eb (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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/*******************************************************************************
 * Copyright (c) 2012, 2014 Obeo.
 * 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:
 *     Obeo - initial API and implementation
 *******************************************************************************/
package org.eclipse.emf.compare.ide.utils;

import com.google.common.io.Closeables;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Map;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IStorage;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.core.runtime.content.IContentTypeManager;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.common.util.WrappedException;
import org.eclipse.emf.compare.ide.EMFCompareIDEPlugin;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;

/**
 * This class will be used to provide various utilities aimed at IResource manipulation.
 * 
 * @author <a href="mailto:laurent.goubet@obeo.fr">Laurent Goubet</a>
 */
public final class ResourceUtil {
	/**
	 * This does not need to be instantiated.
	 */
	private ResourceUtil() {
		// hides default constructor
	}

	/**
	 * This will try and load the given file as an EMF model, and return the corresponding {@link Resource} if
	 * at all possible.
	 * 
	 * @param storage
	 *            The file we need to try and load as a model.
	 * @param resourceSet
	 *            The resource set in which to load this Resource.
	 * @param options
	 *            The options to pass to {@link Resource#load(java.util.Map)}.
	 * @return The loaded EMF Resource if {@code file} was a model, {@code null} otherwise.
	 */
	public static Resource loadResource(IStorage storage, ResourceSet resourceSet, Map<?, ?> options) {
		final String resourceName = storage.getName();
		String path = storage.getFullPath().toString();
		if (!path.endsWith(resourceName)) {
			final int endIndex = path.indexOf(resourceName) + resourceName.length();
			path = path.substring(0, endIndex);
		}

		final URI uri = createURIFor(storage);

		InputStream stream = null;
		Resource resource = null;
		try {
			resource = resourceSet.createResource(uri);
			stream = storage.getContents();
			resource.load(stream, options);
		} catch (IOException e) {
			// return null
		} catch (CoreException e) {
			// return null
		} catch (WrappedException e) {
			// return null
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e) {
					// Should have been caught by the outer try
				}
			}
		}

		return resource;
	}

	/**
	 * Checks whether the two given storages point to binary identical data.
	 * 
	 * @param left
	 *            First of the two storages which content we are testing.
	 * @param right
	 *            Second of the two storages which content we are testing.
	 * @return <code>true</code> if {@code left} and {@code right} are binary identical.
	 */
	public static boolean binaryIdentical(IStorage left, IStorage right) {
		Reader leftReader = null;
		Reader rightReader = null;
		try {
			leftReader = new BufferedReader(new InputStreamReader(left.getContents()));
			rightReader = new BufferedReader(new InputStreamReader(right.getContents()));

			final int bufferSize = 16384;
			final char[] leftBuff = new char[bufferSize];
			final char[] rightBuff = new char[bufferSize];
			int readLeft = leftReader.read(leftBuff);
			int readRight = rightReader.read(rightBuff);
			while (readLeft > 0 && readRight > 0 && equalArrays(readLeft, readRight, leftBuff, rightBuff)) {
				readLeft = leftReader.read(leftBuff);
				readRight = rightReader.read(rightBuff);
			}
			// One last check in case we've reached the end of one side but not of the other
			return equalArrays(readLeft, readRight, leftBuff, rightBuff);
		} catch (CoreException e) {
			logError(e);
		} catch (IOException e) {
			logError(e);
		} finally {
			if (leftReader != null) {
				Closeables.closeQuietly(leftReader);
			}
			if (rightReader != null) {
				Closeables.closeQuietly(rightReader);
			}
		}
		return false;
	}

	/**
	 * Checks whether the three given storages point to binary identical data. This could be done by calling
	 * {@link #binaryIdentical(IStorage, IStorage)} twice, though this implementation allows us to shortcut
	 * whenever one byte differs... and will read one less file from its input stream.
	 * 
	 * @param left
	 *            First of the three storages which content we are testing.
	 * @param right
	 *            Second of the three storages which content we are testing.
	 * @param origin
	 *            Third of the three storages which content we are testing.
	 * @return <code>true</code> if {@code left}, {@code right} and {@code origin} are binary identical.
	 */
	public static boolean binaryIdentical(IStorage left, IStorage right, IStorage origin) {
		Reader leftReader = null;
		Reader rightReader = null;
		Reader originReader = null;
		try {
			leftReader = new BufferedReader(new InputStreamReader(left.getContents()));
			rightReader = new BufferedReader(new InputStreamReader(right.getContents()));
			originReader = new BufferedReader(new InputStreamReader(origin.getContents()));

			final int bufferSize = 16384;
			final char[] leftBuff = new char[bufferSize];
			final char[] rightBuff = new char[bufferSize];
			final char[] originBuff = new char[bufferSize];
			int readLeft = leftReader.read(leftBuff);
			int readRight = rightReader.read(rightBuff);
			int readOrigin = originReader.read(originBuff);
			while (readLeft > 0 && readRight > 0 && readOrigin > 0
					&& equalArrays(readLeft, readRight, readOrigin, leftBuff, rightBuff, originBuff)) {
				readLeft = leftReader.read(leftBuff);
				readRight = rightReader.read(rightBuff);
				readOrigin = originReader.read(originBuff);
			}
			// One last check in case we've reached the end of one side but not of the other
			return equalArrays(readLeft, readRight, readOrigin, leftBuff, rightBuff, originBuff);
		} catch (CoreException e) {
			logError(e);
		} catch (IOException e) {
			logError(e);
		} finally {
			if (leftReader != null) {
				Closeables.closeQuietly(leftReader);
			}
			if (rightReader != null) {
				Closeables.closeQuietly(rightReader);
			}
			if (originReader != null) {
				Closeables.closeQuietly(originReader);
			}
		}
		return false;
	}

	/**
	 * Create the URI with which we'll load the given IFile as an EMF resource.
	 * 
	 * @param file
	 *            The file for which we need an EMF URI.
	 * @return The created URI.
	 * @since 4.0
	 */
	public static URI createURIFor(IFile file) {
		// whether it exists or not (no longer), use platform:/resource
		return URI.createPlatformResourceURI(file.getFullPath().toString(), true);
	}

	/**
	 * Create the URI with which we'll load the given IStorage as an EMF resource.
	 * 
	 * @param storage
	 *            The storage for which we need an EMF URI.
	 * @return The created URI.
	 */
	public static URI createURIFor(IStorage storage) {
		if (storage instanceof IFile) {
			return createURIFor((IFile)storage);
		}

		final String resourceName = storage.getName();
		String path = storage.getFullPath().toString();
		if (!path.endsWith(resourceName)) {
			final int endIndex = path.indexOf(resourceName) + resourceName.length();
			path = path.substring(0, endIndex);
		}

		// Given the two paths
		// "g:/ws/project/test.ecore"
		// "/project/test.ecore"
		// We have no way to determine which is absolute and which should be platform:/resource
		// Furthermore, "ws" could be a git repository, in which case we would be here with
		// ws/project/test.ecore
		URI uri;
		if (path.startsWith("file:/")) { //$NON-NLS-1$
			uri = URI.createURI(path);
		} else {
			uri = URI.createFileURI(path);
		}

		final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
		if (root != null) {
			if (root.getFile(new Path(path)).exists()) {
				uri = URI.createPlatformResourceURI(path, true);
			} else {
				// is it a file coming from a Git repository?
				final int indexOfSeparator = path.indexOf('/');
				if (indexOfSeparator > 0 && root.getFile(new Path(path.substring(indexOfSeparator))).exists()) {
					uri = URI.createPlatformResourceURI(path.substring(indexOfSeparator), true);
				}
			}
		}

		return uri;
	}

	/**
	 * This can be called to save all resources contained by the resource set. This will not try and save
	 * resources that do not support output.
	 * 
	 * @param resourceSet
	 *            The resource set to save.
	 * @param options
	 *            The options we are to pass on to {@link Resource#save(Map)}.
	 */
	public static void saveAllResources(ResourceSet resourceSet, Map<?, ?> options) {
		EList<Resource> resources = resourceSet.getResources();
		for (Resource resource : resources) {
			if (supportsOutput(resource)) {
				try {
					resource.save(options);
				} catch (IOException e) {
					logError(e);
				}
			}
		}
	}

	/**
	 * This will return <code>true</code> if the given <em>contentTypeId</em> represents a content-type
	 * contained in the given array.
	 * 
	 * @param contentTypeId
	 *            Fully qualified identifier of the content type we seek.
	 * @param contentTypes
	 *            The array of content-types to compare against.
	 * @return <code>true</code> if the given array contains a content-type with this id.
	 * @since 4.0
	 */
	public static boolean hasContentType(String contentTypeId, IContentType[] contentTypes) {
		IContentTypeManager ctManager = Platform.getContentTypeManager();
		IContentType expected = ctManager.getContentType(contentTypeId);
		if (expected == null) {
			return false;
		}

		boolean hasContentType = false;
		for (int i = 0; i < contentTypes.length && !hasContentType; i++) {
			if (contentTypes[i].isKindOf(expected)) {
				hasContentType = true;
			}
		}
		return hasContentType;
	}

	/**
	 * Returns the whole list of content types of the given IFile, or an empty array if none.
	 * 
	 * @param file
	 *            The file we need the content types of.
	 * @return All content types associated with the given file, an empty array if none.
	 * @since 4.0
	 */
	public static IContentType[] getContentTypes(IFile file) {
		IContentTypeManager ctManager = Platform.getContentTypeManager();

		InputStream resourceContent = null;
		IContentType[] contentTypes = new IContentType[0];
		try {
			resourceContent = file.getContents();
			contentTypes = ctManager.findContentTypesFor(resourceContent, file.getName());
		} catch (CoreException e) {
			ctManager.findContentTypesFor(file.getName());
		} catch (IOException e) {
			ctManager.findContentTypesFor(file.getName());
		} finally {
			Closeables.closeQuietly(resourceContent);
		}
		return contentTypes;
	}

	/**
	 * Disable saving for resources that cannot support it.
	 * 
	 * @param resource
	 *            The resource we are to check.
	 * @return <code>true</code> if we can save this <code>resource</code>, <code>false</code> otherwise.
	 */
	private static boolean supportsOutput(Resource resource) {
		final URI uri = resource.getURI();
		if (uri.isPlatformResource() || uri.isRelative() || uri.isFile()) {
			return true;
		}
		return false;
	}

	/**
	 * Checks whether the two arrays contain identical data in the {@code [0:length]} range. Note that we
	 * won't even check the arrays' contents if {@code length1} is not equal to {@code length2}.
	 * 
	 * @param length1
	 *            Length of the data range to check within {@code array1}.
	 * @param length2
	 *            Length of the data range to check within {@code array2}.
	 * @param array1
	 *            First of the two arrays which content we need to check.
	 * @param array2
	 *            Second of the two arrays which content we need to check.
	 * @return <code>true</code> if the two given arrays contain identical data in the {@code [0:length]}
	 *         range.
	 */
	private static boolean equalArrays(int length1, int length2, char[] array1, char[] array2) {
		if (length1 == length2) {
			boolean result = true;
			if (array1 == array2) {
				result = true;
			} else if (array1 == null || array2 == null) {
				result = false;
			} else {
				for (int i = 0; i < length1 && result; i++) {
					result = array1[i] == array2[i];
				}
			}
			return result;
		}
		return false;
	}

	/**
	 * Checks whether the three arrays contain identical data in the {@code [0:length]} range. Note that we
	 * will only check the arrays' contents if {@code length1} is equal to {@code length2} and {@code length3}
	 * .
	 * 
	 * @param length1
	 *            Length of the data range to check within {@code array1}.
	 * @param length2
	 *            Length of the data range to check within {@code array2}.
	 * @param length3
	 *            Length of the data range to check within {@code array3}.
	 * @param array1
	 *            First of the three arrays which content we need to check.
	 * @param array2
	 *            Second of the three arrays which content we need to check.
	 * @param array3
	 *            Third of the three arrays which content we need to check.
	 * @return <code>true</code> if the three given arrays contain identical data in the {@code [0:length]}
	 *         range.
	 */
	private static boolean equalArrays(int length1, int length2, int length3, char[] array1, char[] array2,
			char[] array3) {
		if (length1 == length2 && length1 == length3) {
			boolean result = true;
			if (array1 == array2 && array1 == array3) {
				result = true;
			} else if (array1 == null || array2 == null || array3 == null) {
				result = false;
			} else {
				for (int i = 0; i < length1 && result; i++) {
					result = array1[i] == array2[i] && array1[1] == array3[i];
				}
			}
			return result;
		}
		return false;
	}

	/**
	 * Logs the given exception as an error.
	 * 
	 * @param e
	 *            The exception we need to log.
	 */
	private static void logError(Exception e) {
		final IStatus status = new Status(IStatus.ERROR, EMFCompareIDEPlugin.PLUGIN_ID, e.getMessage(), e);
		EMFCompareIDEPlugin.getDefault().getLog().log(status);
	}
}

Back to the top