-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPersistenceHelper.java
458 lines (396 loc) · 15 KB
/
PersistenceHelper.java
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/**
* (c) 2009 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
* Heinrich Heine Universitaet Duesseldorf
* This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
* */
package org.eventb.texttools;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.EMap;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.compare.Comparison;
import org.eclipse.emf.compare.Diff;
import org.eclipse.emf.compare.DifferenceKind;
import org.eclipse.emf.compare.EMFCompare;
import org.eclipse.emf.compare.diff.DefaultDiffEngine;
import org.eclipse.emf.compare.diff.IDiffEngine;
import org.eclipse.emf.compare.match.DefaultComparisonFactory;
import org.eclipse.emf.compare.match.DefaultEqualityHelperFactory;
import org.eclipse.emf.compare.match.IComparisonFactory;
import org.eclipse.emf.compare.match.IMatchEngine;
import org.eclipse.emf.compare.match.eobject.IEObjectMatcher;
import org.eclipse.emf.compare.match.impl.MatchEngineFactoryImpl;
import org.eclipse.emf.compare.match.impl.MatchEngineFactoryRegistryImpl;
import org.eclipse.emf.compare.merge.BatchMerger;
import org.eclipse.emf.compare.merge.IMerger;
import org.eclipse.emf.compare.merge.IMerger.Registry;
import org.eclipse.emf.compare.merge.IMerger.RegistryImpl;
import org.eclipse.emf.compare.scope.DefaultComparisonScope;
import org.eclipse.emf.compare.scope.IComparisonScope;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eventb.emf.core.Attribute;
import org.eventb.emf.core.AttributeType;
import org.eventb.emf.core.CoreFactory;
import org.eventb.emf.core.EventBElement;
import org.eventb.emf.core.EventBNamedCommentedComponentElement;
import org.eventb.texttools.diffmerge.EventBDiffProcessor;
import org.eventb.texttools.diffmerge.EventBEObjectMatcher;
import org.eventb.texttools.diffmerge.EventBMerger;
import org.eventb.texttools.prettyprint.PrettyPrinter;
import de.be4.eventb.core.parser.BException;
import de.be4.eventb.core.parser.EventBParser;
import de.be4.eventb.core.parser.node.AContextParseUnit;
import de.be4.eventb.core.parser.node.AMachineParseUnit;
import de.be4.eventb.core.parser.node.PParseUnit;
import de.be4.eventb.core.parser.node.Start;
//import org.eventb.texttools.merge.ModelMerge;
public class PersistenceHelper {
public static final Boolean DEBUG = false;
public static IResource getIResource(final Resource resource) {
final URI uri = resource.getURI();
if (uri.isPlatformResource()) {
return ResourcesPlugin.getWorkspace().getRoot()
.findMember(uri.toPlatformString(true));
}
return null;
}
public static void saveText(final Resource resource,
final boolean overwrite, final IProgressMonitor monitor)
throws CoreException {
try {
resource.save(Collections.EMPTY_MAP);
/*
* Try to set timestamp to the same as in the annotation. Setting on
* both Resource and IResource to be save.
*/
// final long textTimestamp = getTextTimestamp(resource);
// REMOVED WORKAROUND BELOW: a better fix is to not ignore
// attributes in EventBReferencesCheck
// --- TODO: Workaround for save bug. The method getTextTimestamp
// --- returns in some cases -1 (no time annotation exists). I
// noticed
// --- that many different instances of the same resource exist.
// Some
// --- are annotated, the others not.
long textTimestamp = getTextTimestamp(resource);
// if(textTimestamp == -1)
// textTimestamp = System.currentTimeMillis();
resource.setTimeStamp(textTimestamp);
getIResource(resource).setLocalTimeStamp(textTimestamp);
} catch (final IOException e) {
throw new CoreException(new Status(IStatus.ERROR,
TextToolsPlugin.PLUGIN_ID, "Saving to RodinDB failed", e));
}
}
public static void addTextAnnotation(final Resource resource,
final String textRepresentation, final long timeStamp)
throws CoreException {
final EventBNamedCommentedComponentElement component = getComponent(resource);
if (component != null) {
addTextAnnotation(component, textRepresentation, timeStamp);
} else {
throw new CoreException(new Status(IStatus.ERROR,
TextToolsPlugin.PLUGIN_ID,
"Resource has no EventBComponent"));
}
}
public static void addTextAnnotation(final EventBElement element,
final String textRepresentation, final long timeStamp) {
final EMap<String, Attribute> attributes = element.getAttributes();
// update text representation
Attribute textAttribute = attributes
.get(TextToolsPlugin.TYPE_TEXTREPRESENTATION.getId());
if (textAttribute == null) {
textAttribute = CoreFactory.eINSTANCE.createAttribute();
textAttribute.setType(AttributeType.STRING);
attributes.put(TextToolsPlugin.TYPE_TEXTREPRESENTATION.getId(),
textAttribute);
}
textAttribute.setValue(textRepresentation);
// update timestamp
Attribute timeAttribute = attributes
.get(TextToolsPlugin.TYPE_LASTMODIFIED.getId());
if (timeAttribute == null) {
timeAttribute = CoreFactory.eINSTANCE.createAttribute();
timeAttribute.setType(AttributeType.LONG);
attributes.put(TextToolsPlugin.TYPE_LASTMODIFIED.getId(),
timeAttribute);
}
timeAttribute.setValue(timeStamp);
}
public static void addUsesAnnotation(final EventBElement element,
final String usesStatements) {
final EMap<String, Attribute> attributes = element.getAttributes();
Attribute usesAttribute = attributes
.get(TextToolsPlugin.TYPE_USESEXTENSION.getId());
if (usesAttribute == null) {
usesAttribute = CoreFactory.eINSTANCE.createAttribute();
usesAttribute.setType(AttributeType.STRING);
attributes.put(TextToolsPlugin.TYPE_USESEXTENSION.getId(),
usesAttribute);
}
usesAttribute.setValue(usesStatements);
}
private static void mergeComponents(
final EventBNamedCommentedComponentElement oldVersion,
final EventBNamedCommentedComponentElement newVersion,
final IProgressMonitor monitor) {
long time0 = System.currentTimeMillis();
IComparisonFactory comparisonFactory = new DefaultComparisonFactory(
new DefaultEqualityHelperFactory());
IEObjectMatcher matcher = new EventBEObjectMatcher();
// IMatchEngine matchEngine = new DefaultMatchEngine(matcher,
// comparisonFactory);
// final IMatchEngine eventBMatchEngine = new EventBMatchEngine(matcher,
// comparisonFactory);
// IMatchEngine.Factory matchEngineFactory = new
// MatchEngineFactoryImpl() {
// @Override
// public IMatchEngine getMatchEngine() {
// return eventBMatchEngine;
// }
// };
IMatchEngine.Factory matchEngineFactory = new MatchEngineFactoryImpl(
matcher, comparisonFactory);
matchEngineFactory.setRanking(20);
IMatchEngine.Factory.Registry matchEngineRegistry = new MatchEngineFactoryRegistryImpl();
matchEngineRegistry.add(matchEngineFactory);
IDiffEngine diffEngine = new DefaultDiffEngine(
new EventBDiffProcessor());
EMFCompare comparator = EMFCompare.builder()
.setMatchEngineFactoryRegistry(matchEngineRegistry)
.setDiffEngine(diffEngine).build();
IComparisonScope scope = new DefaultComparisonScope(oldVersion,
newVersion, null);
Comparison comparison = comparator.compare(scope);
List<Diff> differences = comparison.getDifferences();
long time1 = System.currentTimeMillis();
Registry registry = RegistryImpl.createStandaloneInstance();
IMerger evbMerger = new EventBMerger();
evbMerger.setRanking(100);
registry.add(evbMerger);
BatchMerger bm = new BatchMerger(registry);
differences = filter(differences);
bm.copyAllRightToLeft(differences, null);
long time2 = System.currentTimeMillis();
if (DEBUG) {
System.out.println("new ModelMerge: " + (time1 - time0));
System.out.println("merge.applyChanges: " + (time2 - time1));
}
}
// for some reasons, there are still problematic diffs:
// usually, they can be identified as follows:
// 1. right = null, i.e. Camille does not hold this element
// 2. ADD, i.e. the "nothing" coming from Camille is added to the EMF model
// => we drop the diff before we screw up the database
// Obvoiusly it would be better not to generate the diff at all....
private static List<Diff> filter(List<Diff> differences) {
List<Diff> newList = new ArrayList<Diff>();
for (Diff d : differences) {
if (!(d.getKind() == DifferenceKind.ADD && d.getMatch().getRight() == null)) {
newList.add(d);
}
}
return newList;
}
public static void mergeRootElement(final Resource resource,
final EventBNamedCommentedComponentElement newVersion,
final IProgressMonitor monitor) {
final EventBNamedCommentedComponentElement component = getComponent(resource);
if (component != null) {
// FIXME Hier stimmt die Reihenfolge noch
long start = System.currentTimeMillis();
mergeComponents(component, newVersion, monitor);
long end = System.currentTimeMillis();
if (DEBUG) {
System.out
.println("Time to merge components: " + (end - start));
}
// Hier stimmt die Reihenfolge in component nicht mehr
} else {
resource.getContents().add(newVersion);
}
}
public static String loadText(final Resource resource,
final String linebreak) throws IOException {
// make sure resource is loaded
if (!resource.isLoaded()) {
resource.load(Collections.EMPTY_MAP);
}
// check if we have the most recent text representation
if (isTextUptodate(resource)) {
// we should find a text representation in the EMF
final String text = getTextAnnotation(resource);
/*
* workaround for Bug #3305107
*
* When a machine- or contextfile is renamed the lastmodified date
* does not change. Since isTextUptodate() compares timestamps only,
* it returns true for renamed files.
*/
boolean namesMatch = true;
final EventBNamedCommentedComponentElement rootElement = getComponent(resource);
if (rootElement != null) {
final EventBParser parser = new EventBParser();
try {
Start start = parser.parse(text, false);
// System.out.println(start);
PParseUnit pParseUnit = start.getPParseUnit();
String parsedName = null;
if (pParseUnit instanceof AMachineParseUnit) {
parsedName = ((AMachineParseUnit) start.getPParseUnit())
.getName().getText();
}
if (pParseUnit instanceof AContextParseUnit) {
parsedName = ((AContextParseUnit) start.getPParseUnit())
.getName().getText();
}
if (parsedName != null) {
if (!parsedName.equals(rootElement.getName())) {
namesMatch = false;
System.err
.println("Conflicting names of ParseUnit! Expected name: '"
+ rootElement.getName()
+ "' actual name: '"
+ parsedName
+ "'! Prettyprinting unit...");
}
}
} catch (BException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/* End of woraround */
if (text != null && namesMatch) {
return text;
}
}
/*
* Reload resource to get latest changes. This is necessary if the model
* was already loaded and external changes have occured meanwhile. Then
* unloading+loading makes sure the EMF persistence loads those changes.
*/
resource.unload();
resource.load(Collections.EMPTY_MAP);
// pretty-print the machine/context
final EventBNamedCommentedComponentElement rootElement = getComponent(resource);
if (rootElement != null) {
return getPrettyPrint(rootElement, linebreak);
} else {
throw new IOException(
"Cannot find load Event-B component: No machine/context found");
}
}
public static String getTextAnnotation(final Resource resource) {
final EMap<String, Attribute> attributes = getAttributesMap(resource);
if (attributes != null) {
final Attribute attr = attributes
.get(TextToolsPlugin.TYPE_TEXTREPRESENTATION.getId());
if (attr != null) {
return (String) attr.getValue();
}
}
return null;
}
public static EClass getComponentType(final Resource resource) {
final EventBNamedCommentedComponentElement component = getComponent(resource);
if (component != null) {
return component.eClass();
}
return null;
}
private static EventBNamedCommentedComponentElement getComponent(
final Resource resource) {
final EList<EObject> contents = resource.getContents();
if (contents.size() > 0
&& contents.get(0) instanceof EventBNamedCommentedComponentElement) {
return (EventBNamedCommentedComponentElement) contents.get(0);
}
return null;
}
/**
* Extracts the timestamp of the latest saved text representation from the
* EMF and returns it.
*
* @param resource
* @return timestamp or <code>System.currentTimeMillis();</code> if none is
* found
*/
private static long getTextTimestamp(final Resource resource) {
final EMap<String, Attribute> attributes = getAttributesMap(resource);
if (attributes != null) {
final Attribute attr = attributes
.get(TextToolsPlugin.TYPE_LASTMODIFIED.getId());
return attr != null ? (Long) attr.getValue() : -1;
}
return -1;
}
private static EMap<String, Attribute> getAttributesMap(
final Resource resource) {
final EList<EObject> contents = resource.getContents();
if (contents.size() > 0) {
final EObject object = contents.get(0);
if (object instanceof EventBNamedCommentedComponentElement) {
final EventBNamedCommentedComponentElement component = (EventBNamedCommentedComponentElement) object;
return component.getAttributes();
}
}
return null;
}
/**
* Checks if the text representation saved in the EMF is up-to-date. The
* timestamps in the EMF and of the underlying file are compared for this
* decision.
*
* @param resource
* @return <code>true</code> if there was no external change and the text
* representation is still up-to-date
*/
private static boolean isTextUptodate(final Resource resource) {
final long textTimestamp = getTextTimestamp(resource);
if (true) {
// return false;
}
try {
final IResource file = getIResource(resource);
// refresh to get latest timestamp
file.refreshLocal(IResource.DEPTH_ONE, null);
final long resourceTimestamp = file.getLocalTimeStamp();
// easy case: text is newer than resource
if (textTimestamp >= resourceTimestamp) {
return true;
}
final long diff = resourceTimestamp - textTimestamp;
// tolerate 50ms offset (time to save file)
// FIXME this is ugly!!!
if (diff < 50) {
return true;
}
} catch (final CoreException e) {
TextToolsPlugin
.getDefault()
.getLog()
.log(new Status(IStatus.ERROR, TextToolsPlugin.PLUGIN_ID,
"Error checking file timestamps", e));
}
return false;
}
private static String getPrettyPrint(final EventBElement rootElement,
final String linebreak) {
final StringBuilder buffer = new StringBuilder();
new PrettyPrinter(buffer, linebreak, null).prettyPrint(rootElement);
return buffer.toString();
}
}