]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.modeling/src/org/simantics/modeling/typicals/SyncTypicalTemplatesToInstances.java
Sync git svn branch with SVN repository r33319.
[simantics/platform.git] / bundles / org.simantics.modeling / src / org / simantics / modeling / typicals / SyncTypicalTemplatesToInstances.java
1 /*******************************************************************************\r
2  * Copyright (c) 2007, 2012 Association for Decentralized Information Management in\r
3  * Industry THTH ry.\r
4  * All rights reserved. This program and the accompanying materials\r
5  * are made available under the terms of the Eclipse Public License v1.0\r
6  * which accompanies this distribution, and is available at\r
7  * http://www.eclipse.org/legal/epl-v10.html\r
8  *\r
9  * Contributors:\r
10  *     VTT Technical Research Centre of Finland - initial API and implementation\r
11  *******************************************************************************/\r
12 package org.simantics.modeling.typicals;\r
13 \r
14 import java.awt.geom.Point2D;\r
15 import java.util.ArrayList;\r
16 import java.util.Collection;\r
17 import java.util.Collections;\r
18 import java.util.Date;\r
19 import java.util.HashMap;\r
20 import java.util.HashSet;\r
21 import java.util.Iterator;\r
22 import java.util.List;\r
23 import java.util.Map;\r
24 import java.util.Set;\r
25 \r
26 import org.eclipse.core.runtime.IProgressMonitor;\r
27 import org.simantics.Logger;\r
28 import org.simantics.Simantics;\r
29 import org.simantics.databoard.Bindings;\r
30 import org.simantics.db.ReadGraph;\r
31 import org.simantics.db.Resource;\r
32 import org.simantics.db.Statement;\r
33 import org.simantics.db.WriteGraph;\r
34 import org.simantics.db.common.CommentMetadata;\r
35 import org.simantics.db.common.NamedResource;\r
36 import org.simantics.db.common.primitiverequest.Adapter;\r
37 import org.simantics.db.common.procedure.adapter.TransientCacheListener;\r
38 import org.simantics.db.common.request.ObjectsWithType;\r
39 import org.simantics.db.common.request.PossibleIndexRoot;\r
40 import org.simantics.db.common.request.WriteRequest;\r
41 import org.simantics.db.common.uri.UnescapedChildMapOfResource;\r
42 import org.simantics.db.common.utils.CommonDBUtils;\r
43 import org.simantics.db.common.utils.NameUtils;\r
44 import org.simantics.db.exception.DatabaseException;\r
45 import org.simantics.db.layer0.adapter.Instances;\r
46 import org.simantics.db.layer0.request.ActiveModels;\r
47 import org.simantics.db.layer0.util.RemoverUtil;\r
48 import org.simantics.diagram.content.ConnectionUtil;\r
49 import org.simantics.diagram.handler.CopyPasteStrategy;\r
50 import org.simantics.diagram.handler.ElementObjectAssortment;\r
51 import org.simantics.diagram.handler.PasteOperation;\r
52 import org.simantics.diagram.handler.Paster;\r
53 import org.simantics.diagram.handler.Paster.RouteLine;\r
54 import org.simantics.diagram.stubs.DiagramResource;\r
55 import org.simantics.diagram.synchronization.CollectingModificationQueue;\r
56 import org.simantics.diagram.synchronization.CopyAdvisor;\r
57 import org.simantics.diagram.synchronization.SynchronizationHints;\r
58 import org.simantics.diagram.synchronization.graph.GraphSynchronizationContext;\r
59 import org.simantics.diagram.ui.DiagramModelHints;\r
60 import org.simantics.document.DocumentResource;\r
61 import org.simantics.g2d.canvas.ICanvasContext;\r
62 import org.simantics.g2d.diagram.DiagramClass;\r
63 import org.simantics.g2d.diagram.IDiagram;\r
64 import org.simantics.g2d.diagram.impl.Diagram;\r
65 import org.simantics.layer0.Layer0;\r
66 import org.simantics.modeling.ModelingResources;\r
67 import org.simantics.modeling.ModelingUtils;\r
68 import org.simantics.modeling.mapping.ModelingSynchronizationHints;\r
69 import org.simantics.modeling.typicals.rules.AuxKeys;\r
70 import org.simantics.modeling.typicals.rules.FlagRule;\r
71 import org.simantics.modeling.typicals.rules.InstanceOfRule;\r
72 import org.simantics.modeling.typicals.rules.LabelRule;\r
73 import org.simantics.modeling.typicals.rules.MonitorRule;\r
74 import org.simantics.modeling.typicals.rules.NameRule;\r
75 import org.simantics.modeling.typicals.rules.ProfileMonitorRule;\r
76 import org.simantics.modeling.typicals.rules.SVGElementRule;\r
77 import org.simantics.modeling.typicals.rules.TransformRule;\r
78 import org.simantics.scenegraph.g2d.events.command.Commands;\r
79 import org.simantics.scl.runtime.function.Function4;\r
80 import org.simantics.structural.stubs.StructuralResource2;\r
81 import org.simantics.utils.datastructures.MapSet;\r
82 import org.simantics.utils.strings.AlphanumComparator;\r
83 import org.simantics.utils.strings.EString;\r
84 import org.simantics.utils.ui.ErrorLogger;\r
85 \r
86 import gnu.trove.map.hash.THashMap;\r
87 import gnu.trove.set.hash.THashSet;\r
88 \r
89 /**\r
90  * A write request that synchronizes typical master templates and their\r
91  * instances as specified.\r
92  * \r
93  * <p>\r
94  * Use {@link #SyncTypicalTemplatesToInstances(Resource[], MapSet)} to\r
95  * synchronize all instances of specified templates. Use\r
96  * {@link #syncSingleInstance(Resource)} to synchronize a single typical\r
97  * instance with its master template.\r
98  * \r
99  * @author Tuukka Lehtonen\r
100  * \r
101  * @see ReadTypicalInfo\r
102  * @see TypicalInfo\r
103  * @see TypicalSynchronizationMetadata\r
104  */\r
105 public class SyncTypicalTemplatesToInstances extends WriteRequest {\r
106 \r
107     /**\r
108      * A constant used as the second argument to\r
109      * {@link #SyncTemplates(Resource[], MapSet)} for stating that all specified\r
110      * templates should be fully synchronized to their instances.\r
111      * \r
112      * This is useful for forcing complete synchronization and unit testing. \r
113      */\r
114     public static final EmptyMapSet ALL = EmptyMapSet.INSTANCE;\r
115 \r
116     public static class EmptyMapSet extends MapSet<Resource, Resource> {\r
117 \r
118         public static final EmptyMapSet INSTANCE = new EmptyMapSet();\r
119 \r
120         public EmptyMapSet() {\r
121             this.sets = Collections.emptyMap();\r
122         }\r
123 \r
124         @Override\r
125         protected Set<Resource> getOrCreateSet(Resource key) {\r
126             throw new UnsupportedOperationException("immutable constant instance");\r
127         }\r
128 \r
129     };\r
130 \r
131     protected static final boolean           DEBUG = false;\r
132 \r
133     // Input\r
134 \r
135     final private IProgressMonitor monitor;\r
136     /**\r
137      * Typical diagram rules to apply\r
138      */\r
139     protected Set<Resource>                                     selectedRules;\r
140     \r
141     /**\r
142      * Typical diagram templates to synchronize with their instances.\r
143      */\r
144     protected Resource[]                     templates;\r
145 \r
146     /**\r
147      * Typical diagram instances to synchronize with their templates.\r
148      */\r
149     protected Resource[]                     instances;\r
150 \r
151     /**\r
152      * For each template diagram in {@link #templates}, shall contain a set of\r
153      * elements that have changed and should be synchronized into the instance\r
154      * diagrams. Provided as an argument by the client. Allows optimizing\r
155      * real-time synchronization by not processing everything all the time.\r
156      * \r
157      * If the value is {@link #ALL}, all elements of the template shall be fully\r
158      * synchronized.\r
159      */\r
160     protected MapSet<Resource, Resource>     changedElementsByDiagram;\r
161 \r
162     // Temporary data\r
163 \r
164     protected Layer0                         L0;\r
165     protected StructuralResource2            STR;\r
166     protected DiagramResource                DIA;\r
167     protected ModelingResources              MOD;\r
168 \r
169     /**\r
170      * Needed for using {@link Paster} in\r
171      * {@link #addMissingElements(WriteGraph, TypicalInfo, Resource, Resource, Set)}\r
172      */\r
173     protected GraphSynchronizationContext    syncCtx;\r
174 \r
175     /**\r
176      * For collecting commit metadata during the processing of this request.\r
177      */\r
178     protected TypicalSynchronizationMetadata metadata;\r
179 \r
180     /**\r
181      * Necessary for using {@link CopyPasteStrategy} and {@link PasteOperation}\r
182      * for now. Will be removed in the future once IDiagram is removed from\r
183      * PasteOperation.\r
184      */\r
185     protected IDiagram                       temporaryDiagram;\r
186 \r
187     protected ConnectionUtil                 cu;\r
188 \r
189     /**\r
190      * Maps source -> target connection route nodes, i.e. connectors and\r
191      * interior route nodes (route lines). Inverse mapping of {@link #t2s}.\r
192      */\r
193     protected Map<Resource, Resource>        s2t;\r
194 \r
195     /**\r
196      * Maps target -> source connection route nodes, i.e. connectors and\r
197      * interior route nodes (route lines). Inverse mapping of {@link #s2t}.\r
198      */\r
199     protected Map<Resource, Resource>        t2s;\r
200 \r
201     /**\r
202      * An auxiliary resource map for extracting the correspondences between\r
203      * originals and copied resource when diagram contents are copied from\r
204      * template to instance.\r
205      */\r
206     protected Map<Object, Object>            copyMap;\r
207 \r
208     final private Map<Resource, List<String>> messageLogs = new HashMap<>();\r
209     \r
210     public List<Resource> logs = new ArrayList<>();\r
211 \r
212         private boolean writeLog;\r
213 \r
214     /**\r
215      * For SCL API.\r
216      * \r
217      * @param graph\r
218      * @param selectedRules\r
219      * @param templates\r
220      * @param instances\r
221      * @throws DatabaseException\r
222      */\r
223     public static void syncTypicals(WriteGraph graph, boolean log, List<Resource> templates, List<Resource> instances) throws DatabaseException {\r
224         graph.syncRequest(\r
225                 new SyncTypicalTemplatesToInstances(\r
226                         null,\r
227                         templates.toArray(Resource.NONE),\r
228                         instances.toArray(Resource.NONE),\r
229                         ALL,\r
230                         null)\r
231                 .logging(log));\r
232     }\r
233 \r
234     /**\r
235      * @param templates typical diagram templates to completely synchronize with\r
236      *        their instances\r
237      */\r
238     public SyncTypicalTemplatesToInstances(Set<Resource> selectedRules, Resource... templates) {\r
239         this(selectedRules, templates, null, ALL, null);\r
240     }\r
241 \r
242     /**\r
243      * @param templates typical diagram templates to partially synchronize with\r
244      *        their instances\r
245      * @param changedElementsByDiagram see {@link #changedElementsByDiagram}\r
246      */\r
247     public SyncTypicalTemplatesToInstances(Set<Resource> selectedRules, Resource[] templates, MapSet<Resource, Resource> changedElementsByDiagram) {\r
248         this(selectedRules, templates, null, changedElementsByDiagram, null);\r
249     }\r
250 \r
251     /**\r
252      * Return a write request that completely synchronizes the specified\r
253      * instance diagram with its template.\r
254      * \r
255      * @param instance\r
256      * @return\r
257      */\r
258     public static SyncTypicalTemplatesToInstances syncSingleInstance(Set<Resource> selectedRules, Resource instance) {\r
259         return new SyncTypicalTemplatesToInstances(selectedRules, null, new Resource[] { instance }, ALL, null);\r
260     }\r
261 \r
262     /**\r
263      * @param templates typical diagram templates to synchronize with their instances\r
264      * @param instances typical diagram instances to synchronize with their templates\r
265      * @param changedElementsByDiagram see {@link #changedElementsByDiagram}\r
266      */\r
267     private SyncTypicalTemplatesToInstances(Set<Resource> selectedRules, Resource[] templates, Resource[] instances, MapSet<Resource, Resource> changedElementsByDiagram, IProgressMonitor monitor) {\r
268         this.selectedRules = selectedRules;\r
269         this.templates = templates;\r
270         this.instances = instances;\r
271         this.changedElementsByDiagram = changedElementsByDiagram;\r
272         this.monitor = monitor;\r
273     }\r
274 \r
275     public SyncTypicalTemplatesToInstances logging(boolean writeLog) {\r
276         this.writeLog = writeLog;\r
277         return this;\r
278     }\r
279 \r
280     private Resource getDiagramNameResource(ReadGraph graph, Resource diagram) throws DatabaseException {\r
281         Resource composite = graph.getPossibleObject(diagram, MOD.DiagramToComposite);\r
282         if(composite != null) return composite;\r
283         else return diagram;\r
284     }\r
285     \r
286     private Resource getElementNameResource(ReadGraph graph, Resource element) throws DatabaseException {\r
287         Resource corr = ModelingUtils.getPossibleElementCorrespondendence(graph, element);\r
288         if(corr != null) return corr;\r
289         else return element;\r
290     }\r
291     \r
292     private List<String> getLog(ReadGraph graph, Resource diagram) throws DatabaseException {\r
293         Resource indexRoot = graph.syncRequest(new PossibleIndexRoot(diagram));\r
294         if(indexRoot == null) throw new DatabaseException("FATAL: Diagram is not under any index root.");\r
295         List<String> log = messageLogs.get(indexRoot);\r
296         if(log == null) {\r
297                 log = new ArrayList<>();\r
298                 messageLogs.put(indexRoot, log);\r
299         }\r
300         return log;\r
301     }\r
302     \r
303     private String elementName(ReadGraph graph, Resource element) throws DatabaseException {\r
304         \r
305         StringBuilder b = new StringBuilder();\r
306         b.append(safeNameAndType(graph, element));\r
307 \r
308         int spaces = 60-b.length();\r
309                 for(int i=0;i<spaces;i++) b.append(" ");\r
310 \r
311         Resource corr = ModelingUtils.getPossibleElementCorrespondendence(graph, element);\r
312         if(corr != null) {\r
313                 b.append(safeNameAndType(graph, corr));\r
314         } else {\r
315                 b.append("-");\r
316         }\r
317         \r
318         return b.toString();\r
319         \r
320     }\r
321 \r
322     @Override\r
323     public void perform(WriteGraph graph) throws DatabaseException {\r
324         this.L0 = Layer0.getInstance(graph);\r
325         this.STR = StructuralResource2.getInstance(graph);\r
326         this.DIA = DiagramResource.getInstance(graph);\r
327         this.MOD = ModelingResources.getInstance(graph);\r
328 \r
329         this.syncCtx = GraphSynchronizationContext.getWriteInstance( graph, new CollectingModificationQueue() );\r
330         this.syncCtx.set(ModelingSynchronizationHints.MODELING_RESOURCE, ModelingResources.getInstance(graph));\r
331 \r
332         this.metadata = new TypicalSynchronizationMetadata();\r
333         this.metadata.synchronizedTypicals = new ArrayList<>();\r
334 \r
335         this.temporaryDiagram = Diagram.spawnNew(DiagramClass.DEFAULT);\r
336         this.temporaryDiagram.setHint(SynchronizationHints.CONTEXT, syncCtx);\r
337 \r
338         this.cu = new ConnectionUtil(graph);\r
339 \r
340         if (templates != null) {\r
341             // Look for typical template instances from the currently active models only.\r
342             Collection<Resource> activeModels = graph.syncRequest(new ActiveModels(Simantics.getProjectResource()));\r
343             if (!activeModels.isEmpty()) {\r
344                 for (Resource template : templates) {\r
345                     syncTemplate(graph, template, activeModels);\r
346                 }\r
347             }\r
348         }\r
349         if (instances != null) {\r
350             for (Resource instance : instances) {\r
351                 syncInstance(graph, instance);\r
352             }\r
353         }\r
354 \r
355         if (writeLog) {\r
356             for(Map.Entry<Resource, List<String>> entry : messageLogs.entrySet()) {\r
357 \r
358                 Resource indexRoot = entry.getKey();\r
359                 List<String> messageLog = entry.getValue();\r
360 \r
361                 Layer0 L0 = Layer0.getInstance(graph);\r
362                 DocumentResource DOC = DocumentResource.getInstance(graph);\r
363 \r
364                 Collection<Resource> libs = graph.syncRequest(new ObjectsWithType(indexRoot, L0.ConsistsOf, DOC.DocumentLibrary));\r
365                 if(libs.isEmpty()) continue;\r
366 \r
367                 List<NamedResource> nrs = new ArrayList<>();\r
368                 for(Resource lib : libs) nrs.add(new NamedResource(NameUtils.getSafeName(graph, lib), lib));\r
369                 Collections.sort(nrs, AlphanumComparator.CASE_INSENSITIVE_COMPARATOR);\r
370                 Resource library = nrs.iterator().next().getResource();\r
371 \r
372                 CommonDBUtils.selectClusterSet(graph, library);\r
373 \r
374                 String text = "--- Created: " + new Date().toString() + " ---\n";\r
375                 text += EString.implode(messageLog);\r
376 \r
377                 Resource log = graph.newResource();\r
378                 graph.claim(log, L0.InstanceOf, null, DOC.PlainTextDocument);\r
379                 graph.claimLiteral(log, L0.HasName, L0.String, "Typical Sync " + new Date().toString());\r
380                 graph.claim(library, L0.ConsistsOf, L0.PartOf, log);\r
381                 graph.claimLiteral(log, DOC.PlainTextDocument_text, L0.String, text);\r
382                 logs.add(log);\r
383 \r
384             }\r
385         }\r
386 \r
387         if (!metadata.getTypicals().isEmpty()) {\r
388             graph.addMetadata(metadata);\r
389 \r
390             // Add comment to change set.\r
391             CommentMetadata cm = graph.getMetadata(CommentMetadata.class);\r
392             graph.addMetadata( cm.add("Synchronized " + metadata.getTypicals().size() + " typical diagram instances (" + metadata.getTypicals() + ") with their templates.") );\r
393         }\r
394 \r
395         temporaryDiagram = null;\r
396         syncCtx = null;\r
397     }\r
398 \r
399     private Collection<Resource> findInstances(ReadGraph graph, Resource ofType, Collection<Resource> indexRoots) throws DatabaseException {\r
400         Instances index = graph.adapt(ofType, Instances.class);\r
401         Set<Resource> instances = new HashSet<>();\r
402         for (Resource indexRoot : indexRoots)\r
403             instances.addAll( index.find(graph, indexRoot) );\r
404         return instances;\r
405     }\r
406 \r
407     private void syncTemplate(WriteGraph graph, Resource template, Collection<Resource> indexRoots) throws DatabaseException {\r
408         Resource templateType = graph.getPossibleType(template, DIA.Diagram);\r
409         if (templateType == null)\r
410             return;\r
411 \r
412         Collection<Resource> instances = findInstances(graph, templateType, indexRoots);\r
413         // Do not include the template itself as it is also an instance of templateType\r
414         instances.remove(template);\r
415         if (instances.isEmpty())\r
416             return;\r
417 \r
418         Set<Resource> templateElements = new THashSet<>( graph.syncRequest(\r
419                 new ObjectsWithType(template, L0.ConsistsOf, DIA.Element) ) );\r
420 \r
421         try {\r
422             for (Resource instance : instances) {\r
423                 this.temporaryDiagram.setHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE, instance);\r
424                 syncInstance(graph, template, instance, templateElements);\r
425             }\r
426         } catch (Exception e) {\r
427                 Logger.defaultLogError(e);\r
428                 e.printStackTrace();\r
429         } finally {\r
430             this.temporaryDiagram.removeHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE);\r
431         }\r
432     }\r
433 \r
434     private void syncInstance(WriteGraph graph, Resource instance) throws DatabaseException {\r
435         Resource template = graph.getPossibleObject(instance, MOD.HasDiagramSource);\r
436         if (template == null)\r
437             return;\r
438 \r
439         Set<Resource> templateElements = new THashSet<>( graph.syncRequest(\r
440                 new ObjectsWithType(template, L0.ConsistsOf, DIA.Element) ) );\r
441 \r
442         try {\r
443             this.temporaryDiagram.setHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE, instance);\r
444             syncInstance(graph, template, instance, templateElements);\r
445         } finally {\r
446             this.temporaryDiagram.removeHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE);\r
447         }\r
448     }\r
449     \r
450     private Resource findInstanceCounterpart(ReadGraph graph, Resource instanceDiagram, Resource templateElement) throws DatabaseException {\r
451         Map<String,Resource> children = graph.syncRequest(new UnescapedChildMapOfResource(instanceDiagram));\r
452         for(Resource child : children.values()) {\r
453                 if(graph.hasStatement(child, MOD.HasElementSource, templateElement)) return child;\r
454         }\r
455         return null;\r
456     }\r
457     \r
458     private boolean isSynchronizedConnector(ReadGraph graph, Resource templateConnection, Resource instanceConnector) throws DatabaseException {\r
459         DiagramResource DIA = DiagramResource.getInstance(graph);\r
460         Resource instanceConnection = graph.getPossibleObject(instanceConnector, DIA.IsConnectorOf);\r
461         return graph.hasStatement(instanceConnection, MOD.HasElementSource, templateConnection)\r
462                         // If the master connection has been removed, this is all that's left\r
463                         // to identify a connection that at least was originally synchronized\r
464                         // from the typical master to this instance.\r
465                         || graph.hasStatement(instanceConnection, MOD.IsTemplatized);\r
466     }\r
467 \r
468     /**\r
469      * Perform the following synchronization steps for the instance diagram:\r
470      * <ol>\r
471      * <li>remove such templatized elements from the instance diagram whose\r
472      * template counterpart no longer exists</li>\r
473      * <li>add elements to the instance diagram that are only in the template</li>\r
474      * <li>synchronize elements of the instance diagram that have been deemed\r
475      * changed</li>\r
476      * </ol>\r
477      * \r
478      * @param graph database write access\r
479      * @param template the synchronization source diagram\r
480      * @param instance the synchronization target diagram\r
481      * @param currentTemplateElements the set of all elements currently in the\r
482      *        template diagram\r
483      * @throws DatabaseException if anything goes wrong\r
484      */\r
485     private void syncInstance(WriteGraph graph, Resource template, Resource instance, Set<Resource> currentTemplateElements) throws DatabaseException {\r
486 \r
487         List<String> messageLog = getLog(graph, instance);\r
488         \r
489         messageLog.add("Synchronization of changed typical template: " + SyncTypicalTemplatesToInstances.safeNameAndType(graph, getDiagramNameResource(graph, template)));\r
490         messageLog.add("----\n\ttypical instance: " + safeNameAndType(graph, getDiagramNameResource(graph, instance)));\r
491 \r
492         CommonDBUtils.selectClusterSet(graph, instance);\r
493         \r
494         // Form instance element <-> template element bijection\r
495         TypicalInfoBean typicalInfoBean = graph.syncRequest(\r
496                 new ReadTypicalInfo(instance),\r
497                 TransientCacheListener.<TypicalInfoBean> instance());\r
498         // Must be able to modify the typicalInfo structure,\r
499         // therefore clone the query result.\r
500         typicalInfoBean = (TypicalInfoBean) typicalInfoBean.clone();\r
501         typicalInfoBean.templateElements = currentTemplateElements;\r
502         typicalInfoBean.auxiliary = new HashMap<>(1);\r
503 \r
504         TypicalInfo info = new TypicalInfo();\r
505         info.monitor = monitor;\r
506         info.messageLog = messageLog;\r
507         info.bean = typicalInfoBean;\r
508         \r
509         // Resolve naming function for this typical instance.\r
510         Resource compositeInstance = graph.getPossibleObject(instance, MOD.DiagramToComposite);\r
511         if (compositeInstance != null) {\r
512                 Function4<ReadGraph, Resource, Resource, String, String> namingFunction = TypicalUtil.getTypicalNamingFunction(graph, compositeInstance);\r
513             if (namingFunction != null)\r
514                 typicalInfoBean.auxiliary.put(AuxKeys.KEY_TYPICAL_NAMING_FUNCTION, namingFunction);\r
515         }\r
516 \r
517         int dSizeAbs = Math.abs(typicalInfoBean.instanceElements.size() - currentTemplateElements.size());\r
518 \r
519         if(DEBUG)\r
520                 System.out.println("typical <-> template mapping: " + typicalInfoBean.instanceToTemplate);\r
521 \r
522         // Find elements to be removed from instance by looking for all\r
523         // instance elements that do not have a MOD.HasElementSource\r
524         // relation but have a MOD.IsTemplatized tag.\r
525         Set<Resource> instanceElementsRemovedFromTemplate = findInstanceElementsRemovedFromTemplate(\r
526                 graph, info, new THashSet<>(dSizeAbs));\r
527 \r
528         // Find elements in template that do not yet exist in the instance\r
529         Set<Resource> templateElementsAddedToTemplate = findTemplateElementsMissingFromInstance(\r
530                 graph, currentTemplateElements, info,\r
531                 new THashSet<>(dSizeAbs));\r
532 \r
533         Set<Resource> changedTemplateElements = changedElementsByDiagram.removeValues(template);\r
534 \r
535         if(DEBUG)\r
536                 System.out.println("ADDED: " + templateElementsAddedToTemplate.size() + ", REMOVED: " + instanceElementsRemovedFromTemplate.size() + ", CHANGED: " + changedTemplateElements.size());\r
537         \r
538         // Validate\r
539         for(Resource templateElement : graph.getObjects(template, L0.ConsistsOf)) {\r
540                 if(graph.isInstanceOf(templateElement, DIA.RouteGraphConnection)) {\r
541                         for(Resource connector : graph.getObjects(templateElement, DIA.HasConnector)) {\r
542                                 for(Statement elementStm : graph.getStatements(connector, STR.Connects)) {\r
543                                         Resource otherElement = elementStm.getObject(); \r
544                                         if(!otherElement.equals(templateElement)) {\r
545                                 Resource counterPartElement = findInstanceCounterpart(graph, instance, otherElement);\r
546                                 if(counterPartElement != null) {\r
547                                                 Resource diagramConnectionPoint = graph.getInverse(elementStm.getPredicate());\r
548                                                 Resource connectionPoint = graph.getPossibleObject(diagramConnectionPoint, MOD.DiagramConnectionRelationToConnectionRelation);\r
549                                                 if(connectionPoint != null) {\r
550                                                         Statement stm = graph.getPossibleStatement(counterPartElement, diagramConnectionPoint);\r
551                                         if(stm != null) {\r
552                                                 if(graph.isInstanceOf(connectionPoint, L0.FunctionalRelation)) {\r
553                                                         if(!isSynchronizedConnector(graph, templateElement, stm.getObject())) {\r
554                                                                 messageLog.add("\t\tABORTED: tried to connect to an already connected terminal " + NameUtils.getSafeName(graph, counterPartElement) + " " + NameUtils.getSafeName(graph, connectionPoint));\r
555                                                                 return;\r
556                                                         }\r
557                                                 }\r
558                                                 }\r
559                                                 }\r
560                                 }\r
561                                         }\r
562                                 }\r
563                         }\r
564                 }\r
565         }\r
566         \r
567         // Perform changes\r
568         boolean changed = false;\r
569         changed |= synchronizeDiagramChanges(graph, info, template, instance);\r
570         changed |= removeElements(graph, info, instanceElementsRemovedFromTemplate);\r
571         changed |= addMissingElements(graph, info, template, instance, templateElementsAddedToTemplate);\r
572         changed |= synchronizeChangedElements(graph, info, template, instance, changedTemplateElements, templateElementsAddedToTemplate, changedElementsByDiagram == ALL);\r
573 \r
574         if (changed)\r
575             metadata.addTypical(instance);\r
576     }\r
577 \r
578     /**\r
579      * Synchronize any configurable aspects of the typical diagram instance itself.\r
580      * Every rule executed here comes from the ontology, nothing is fixed. \r
581      * \r
582      * @param graph\r
583      * @param typicalInfo\r
584      * @param template\r
585      * @param instance\r
586      * @return if any changes were made. \r
587      * @throws DatabaseException\r
588      */\r
589     private boolean synchronizeDiagramChanges(\r
590             WriteGraph graph,\r
591             TypicalInfo typicalInfo,\r
592             Resource template,\r
593             Resource instance)\r
594                     throws DatabaseException\r
595     {\r
596         boolean changed = false;\r
597         for (Resource rule : graph.getObjects(template, MOD.HasTypicalSynchronizationRule)) {\r
598             if (selectedRules != null && !selectedRules.contains(rule))\r
599                 continue;\r
600             ITypicalSynchronizationRule r = graph.getPossibleAdapter(rule, ITypicalSynchronizationRule.class);\r
601             if (r != null)\r
602                 changed |= r.synchronize(graph, template, instance, typicalInfo);\r
603         }\r
604         return changed;\r
605     }\r
606 \r
607     /**\r
608      * Add elements from template that do not yet exist in the instance.\r
609      * \r
610      * @param graph\r
611      * @param template\r
612      * @param instance\r
613      * @param elementsAddedToTemplate\r
614      * @return <code>true</code> if changes were made to the instance\r
615      * @throws DatabaseException\r
616      */\r
617     private boolean addMissingElements(WriteGraph graph, TypicalInfo typicalInfo, Resource template,\r
618             Resource instance, Set<Resource> elementsAddedToTemplate)\r
619                     throws DatabaseException {\r
620         if (elementsAddedToTemplate.isEmpty())\r
621             return false;\r
622 \r
623         CopyAdvisor copyAdvisor = graph.syncRequest(new Adapter<CopyAdvisor>(instance, CopyAdvisor.class));\r
624         this.temporaryDiagram.setHint(SynchronizationHints.COPY_ADVISOR, copyAdvisor);\r
625 \r
626         ElementObjectAssortment assortment = new ElementObjectAssortment(graph, elementsAddedToTemplate);\r
627         if (copyMap == null)\r
628             copyMap = new THashMap<>();\r
629         else\r
630             copyMap.clear();\r
631 \r
632         if (DEBUG)\r
633             System.out.println("ADD MISSING ELEMENTS: " + assortment);\r
634 \r
635         // initialCopyMap argument is needed for copying just connections\r
636         // when their end-points are not copied at the same time.\r
637 \r
638         PasteOperation pasteOp = new PasteOperation(Commands.COPY,\r
639                 (ICanvasContext) null, template, instance, temporaryDiagram,\r
640                 assortment, false, new Point2D.Double(0, 0),\r
641                 typicalInfo.bean.templateToInstance, copyMap)\r
642         .options(PasteOperation.ForceCopyReferences.INSTANCE);\r
643 \r
644         new Paster(graph.getSession(), pasteOp).perform(graph);\r
645 \r
646         boolean changed = false;\r
647 \r
648         if(!elementsAddedToTemplate.isEmpty())\r
649                 typicalInfo.messageLog.add("\tadded elements");\r
650         \r
651         for (Resource addedElement : elementsAddedToTemplate) {\r
652             Resource copyElement = (Resource) copyMap.get(addedElement);\r
653             if (copyElement != null) {\r
654                 graph.claim(copyElement, MOD.IsTemplatized, MOD.IsTemplatized, copyElement);\r
655                 graph.claim(copyElement, MOD.HasElementSource, MOD.ElementHasInstance, addedElement);\r
656 \r
657                 typicalInfo.bean.instanceElements.add(copyElement);\r
658                 typicalInfo.bean.instanceToTemplate.put(copyElement, addedElement);\r
659                 typicalInfo.bean.templateToInstance.put(addedElement, copyElement);\r
660 \r
661                 typicalInfo.messageLog.add("\t\t" + safeNameAndType(graph, copyElement));\r
662 \r
663                 changed = true;\r
664             }\r
665         }\r
666 \r
667         ModelingResources MOD = ModelingResources.getInstance(graph);\r
668         Resource instanceComposite = graph.getPossibleObject(instance, MOD.DiagramToComposite);\r
669         List<Resource> instanceComponents = new ArrayList<>(elementsAddedToTemplate.size());\r
670 \r
671         // Post-process added elements after typicalInfo has been updated and\r
672         // template mapping statements are in place.\r
673         for (Resource addedElement : elementsAddedToTemplate) {\r
674             Resource copyElement = (Resource) copyMap.get(addedElement);\r
675             if (copyElement != null) {\r
676                 postProcessAddedElement(graph, addedElement, copyElement, typicalInfo);\r
677 \r
678                 if (instanceComponents != null) {\r
679                     // Gather all instance typical components for applying naming\r
680                     // strategy on them.\r
681                     Resource component = graph.getPossibleObject(copyElement, MOD.ElementToComponent);\r
682                     if (component != null)\r
683                         instanceComponents.add(component);\r
684                 }\r
685             }\r
686         }\r
687 \r
688         if (instanceComposite != null)\r
689             TypicalUtil.applySelectedModuleNames(graph, instanceComposite, instanceComponents);\r
690 \r
691         return changed;\r
692     }\r
693 \r
694     private void postProcessAddedElement(WriteGraph graph,\r
695             Resource addedTemplateElement, Resource addedInstanceElement,\r
696             TypicalInfo typicalInfo) throws DatabaseException {\r
697         if (graph.isInstanceOf(addedInstanceElement, DIA.Monitor)) {\r
698             postProcessAddedMonitor(graph, addedTemplateElement, addedInstanceElement, typicalInfo);\r
699         }\r
700     }\r
701 \r
702     private void postProcessAddedMonitor(WriteGraph graph,\r
703             Resource addedTemplateMonitor, Resource addedInstanceMonitor,\r
704             TypicalInfo typicalInfo) throws DatabaseException {\r
705         Resource monitor = addedInstanceMonitor;\r
706         Resource monitoredComponent = graph.getPossibleObject(monitor, DIA.HasMonitorComponent);\r
707         if (monitoredComponent != null) {\r
708             Resource monitoredTemplateElement = graph.getPossibleObject(monitoredComponent, MOD.ComponentToElement);\r
709             if (monitoredTemplateElement != null) {\r
710                 Resource monitoredInstanceElement = typicalInfo.bean.templateToInstance.get(monitoredTemplateElement);\r
711                 if (monitoredInstanceElement != null) {\r
712                     Resource monitoredInstanceComponent = graph.getPossibleObject(monitoredInstanceElement, MOD.ElementToComponent);\r
713                     if (monitoredInstanceComponent != null) {\r
714                         // Ok, the monitor refers to a component within the\r
715                         // template composite. Change it to refer to the\r
716                         // instance composite.\r
717                         graph.deny(monitor, DIA.HasMonitorComponent);\r
718                         graph.claim(monitor, DIA.HasMonitorComponent, monitoredInstanceComponent);\r
719                     }\r
720                 }\r
721             }\r
722         }\r
723     }\r
724 \r
725     private boolean removeElements(WriteGraph graph, TypicalInfo typicalInfo, Set<Resource> elementsRemovedFromTemplate) throws DatabaseException {\r
726         if (elementsRemovedFromTemplate.isEmpty())\r
727             return false;\r
728 \r
729         // Remove mapped elements from instance that are removed from the template.\r
730         boolean changed = false;\r
731         \r
732         if(!elementsRemovedFromTemplate.isEmpty())\r
733                 typicalInfo.messageLog.add("\tremoved elements");\r
734         \r
735         for (Resource removedElement : elementsRemovedFromTemplate) {\r
736                 typicalInfo.messageLog.add("\t\t" + safeNameAndType(graph, removedElement));\r
737 \r
738             RemoverUtil.remove(graph, removedElement);\r
739 \r
740             typicalInfo.bean.instanceElements.remove(removedElement);\r
741             Resource template = typicalInfo.bean.instanceToTemplate.remove(removedElement);\r
742             if (template != null)\r
743                 typicalInfo.bean.templateToInstance.remove(template);\r
744 \r
745             changed = true;\r
746         }\r
747         return changed;\r
748     }\r
749 \r
750     private Set<Resource> findTemplateElementsMissingFromInstance(\r
751             WriteGraph graph, Collection<Resource> currentTemplateElements,\r
752             TypicalInfo typicalInfo, THashSet<Resource> result)\r
753                   throws DatabaseException {\r
754         for (Resource templateElement : currentTemplateElements) {\r
755             Resource instanceElement = typicalInfo.bean.templateToInstance.get(templateElement);\r
756             if (instanceElement == null) {\r
757                 if(DEBUG)\r
758                         System.out.println("No instance correspondence for template element " + NameUtils.getSafeName(graph, templateElement, true) + " => add");\r
759                 result.add(templateElement);\r
760             }\r
761         }\r
762         return result;\r
763     }\r
764 \r
765     public Set<Resource> findInstanceElementsRemovedFromTemplate(\r
766             ReadGraph graph, TypicalInfo typicalInfo,\r
767             THashSet<Resource> result) throws DatabaseException {\r
768         for (Resource instanceElement : typicalInfo.bean.instanceElements) {\r
769             if (!typicalInfo.bean.instanceToTemplate.containsKey(instanceElement)) {\r
770                 if (typicalInfo.bean.isTemplatized.contains(instanceElement)) {\r
771                         if(DEBUG)\r
772                                 System.out.println("Templatized typical instance element " + NameUtils.getSafeName(graph, instanceElement, true) + " has no correspondence in template => remove");\r
773                     result.add(instanceElement);\r
774                 }\r
775             }\r
776         }\r
777         return result;\r
778     }\r
779 \r
780     /**\r
781      * Synchronize basic visual aspects of changed elements. For all elements,\r
782      * transform and label are synchronized. Otherwise synchronization is\r
783      * type-specific for connections, flags, monitors and svg elements.\r
784      * \r
785      * @param graph\r
786      * @param typicalInfo\r
787      * @param template\r
788      * @param instance\r
789      * @param changedTemplateElements\r
790      * @param addedElements\r
791      *            elements that have been added and thus need not be\r
792      *            synchronized\r
793      * @param synchronizeAllElements\r
794      * @return\r
795      * @throws DatabaseException\r
796      */\r
797     private boolean synchronizeChangedElements(WriteGraph graph,\r
798             TypicalInfo typicalInfo, Resource template, Resource instance,\r
799             Collection<Resource> changedTemplateElements,\r
800             Set<Resource> addedElements,\r
801             boolean synchronizeAllElements) throws DatabaseException {\r
802 \r
803         if (synchronizeAllElements) {\r
804             // For unit testing purposes.\r
805             changedTemplateElements = graph.syncRequest(new ObjectsWithType(template, L0.ConsistsOf, DIA.Element));\r
806         }\r
807 \r
808         if (changedTemplateElements.isEmpty())\r
809             return false;\r
810 \r
811         boolean changed = false;\r
812 \r
813         typicalInfo.messageLog.add("\telement change analysis");\r
814         int analysisLogPosition = typicalInfo.messageLog.size();\r
815 \r
816         for (Resource changedTemplateElement : changedTemplateElements) {\r
817             // Skip synchronization of elements that were just added and are\r
818             // thus already synchronized.\r
819             if (addedElements.contains(changedTemplateElement))\r
820                 continue;\r
821 \r
822             Resource instanceElement = typicalInfo.bean.templateToInstance.get(changedTemplateElement);\r
823             if (instanceElement == null) {\r
824                 // There's an earlier problem in the sync process if this happens.\r
825                 typicalInfo.messageLog.add("SKIPPING SYNC OF CHANGED TEMPLATE ELEMENT DUE TO MISSING INSTANCE: " + safeNameAndType(graph, getElementNameResource(graph, changedTemplateElement)));\r
826                 continue;\r
827             }\r
828             \r
829             typicalInfo.messageLog.add("\t\t" + elementName(graph, changedTemplateElement));\r
830             int currentLogSize = typicalInfo.messageLog.size();\r
831 \r
832             changed |= InstanceOfRule.INSTANCE.synchronize(graph, changedTemplateElement, instanceElement, typicalInfo);\r
833             changed |= NameRule.INSTANCE.synchronize(graph, changedTemplateElement, instanceElement, typicalInfo);\r
834             changed |= TransformRule.INSTANCE.synchronize(graph, changedTemplateElement, instanceElement, typicalInfo);\r
835             changed |= LabelRule.INSTANCE.synchronize(graph, changedTemplateElement, instanceElement, typicalInfo);\r
836 \r
837             Collection<Resource> types = graph.getTypes(changedTemplateElement);\r
838             if (types.contains(DIA.RouteGraphConnection)) {\r
839                 changed |= synchronizeConnection(graph, changedTemplateElement, instanceElement, typicalInfo);\r
840             } else if (types.contains(DIA.Flag)) {\r
841                 changed |= FlagRule.INSTANCE.synchronize(graph, changedTemplateElement, instanceElement, typicalInfo);\r
842             } else if (types.contains(DIA.Monitor)) {\r
843                 changed |= MonitorRule.INSTANCE.synchronize(graph, changedTemplateElement, instanceElement, typicalInfo);\r
844             } else if (types.contains(DIA.SVGElement)) {\r
845                 changed |= SVGElementRule.INSTANCE.synchronize(graph, changedTemplateElement, instanceElement, typicalInfo);\r
846             }\r
847 \r
848             changed |= ProfileMonitorRule.INSTANCE.synchronize(graph, changedTemplateElement, instanceElement, typicalInfo);\r
849             \r
850             for (Resource rule : graph.getObjects(changedTemplateElement, MOD.HasTypicalSynchronizationRule)) {\r
851                 if(selectedRules != null && !selectedRules.contains(rule)) continue;\r
852                 ITypicalSynchronizationRule r = graph.getPossibleAdapter(rule, ITypicalSynchronizationRule.class);\r
853                 if (r != null)\r
854                     changed |= r.synchronize(graph, changedTemplateElement, instanceElement, typicalInfo);\r
855             }\r
856             \r
857             // Show element only if something has happened\r
858             if(currentLogSize == typicalInfo.messageLog.size())\r
859                 typicalInfo.messageLog.remove(typicalInfo.messageLog.size()-1);\r
860             \r
861         }\r
862 \r
863         if (s2t != null)\r
864             s2t.clear();\r
865         if (t2s != null)\r
866             t2s.clear();\r
867 \r
868         // Show analysis header only if something has happened\r
869         if(analysisLogPosition == typicalInfo.messageLog.size())\r
870                 typicalInfo.messageLog.remove(typicalInfo.messageLog.size()-1);\r
871 \r
872         return changed;\r
873     }\r
874 \r
875     private static class Connector {\r
876         public final Resource attachmentRelation;\r
877         public final Resource connector;\r
878         public RouteLine attachedTo;\r
879 \r
880         public Connector(Resource attachmentRelation, Resource connector) {\r
881             this.attachmentRelation = attachmentRelation;\r
882             this.connector = connector;\r
883         }\r
884     }\r
885 \r
886     /**\r
887      * Synchronizes two route graph connection topologies if and only if the\r
888      * destination connection is not attached to any node elements besides\r
889      * the ones that exist in the source. This means that connections that\r
890      * have instance-specific connections to non-template nodes are ignored\r
891      * here.\r
892      * \r
893      * @param graph\r
894      * @param sourceConnection\r
895      * @param targetConnection\r
896      * @param typicalInfo\r
897      * @return <code>true</code> if changes were made \r
898      * @throws DatabaseException\r
899      */\r
900     private boolean synchronizeConnection(WriteGraph graph, Resource sourceConnection, Resource targetConnection, TypicalInfo typicalInfo)\r
901             throws DatabaseException {\r
902 \r
903         if(DEBUG)\r
904                 System.out.println("connection " + NameUtils.getSafeName(graph, sourceConnection, true) + " to target connection " + NameUtils.getSafeName(graph, targetConnection, true));\r
905 \r
906         boolean changed = false;\r
907 \r
908         // Initialize utilities and data maps\r
909         s2t = newOrClear(s2t);\r
910         t2s = newOrClear(t2s);\r
911 \r
912         if (cu == null)\r
913             cu = new ConnectionUtil(graph);\r
914 \r
915         // 0.1. find mappings between source and target connection connectors\r
916         Collection<Statement> toTargetConnectors = graph.getStatements(targetConnection, DIA.HasConnector);\r
917         Map<Resource, Connector> targetConnectors = new THashMap<>(toTargetConnectors.size());\r
918         for (Statement toTargetConnector : toTargetConnectors) {\r
919             Resource targetConnector = toTargetConnector.getObject();\r
920             targetConnectors.put(targetConnector, new Connector(toTargetConnector.getPredicate(), targetConnector));\r
921             Statement toNode = cu.getConnectedComponentStatement(targetConnection, targetConnector);\r
922             if (toNode == null) {\r
923                 // Corrupted target connection!\r
924                 ErrorLogger.defaultLogError("Encountered corrupted typical template connection "\r
925                         + NameUtils.getSafeName(graph, targetConnection, true) + " with a stray DIA.Connector instance "\r
926                         + NameUtils.getSafeName(graph, targetConnector, true) + " that is not attached to any element.",\r
927                         new Exception("trace"));\r
928                 return false;\r
929             }\r
930             if (!graph.hasStatement(targetConnector, DIA.AreConnected)) {\r
931                 // Corrupted target connection!\r
932                 ErrorLogger.defaultLogError("Encountered corrupted typical template connection "\r
933                         + NameUtils.getSafeName(graph, targetConnection, true) + " with a stray DIA.Connector instance "\r
934                         + NameUtils.getSafeName(graph, targetConnector, true) + " that is not connected to any other route node.",\r
935                         new Exception("trace"));\r
936                 return false;\r
937             }\r
938 \r
939             //Resource templateNode = typicalInfo.instanceToTemplate.get(toNode.getObject());\r
940             Resource templateNode = graph.getPossibleObject(toNode.getObject(), MOD.HasElementSource);\r
941             if (templateNode != null) {\r
942                 Resource isConnectedTo = graph.getPossibleInverse(toNode.getPredicate());\r
943                 if (isConnectedTo != null) {\r
944                     Resource templateConnector = graph.getPossibleObject(templateNode, isConnectedTo);\r
945                     if (templateConnector != null) {\r
946                         Resource connectionOfTemplateConnector = ConnectionUtil.tryGetConnection(graph, templateConnector);\r
947                         if (sourceConnection.equals(connectionOfTemplateConnector)) {\r
948                             s2t.put(templateConnector, targetConnector);\r
949                             t2s.put(targetConnector, templateConnector);\r
950 \r
951                             if (DEBUG)\r
952                                 debug(typicalInfo, "Mapping connector "\r
953                                         + NameUtils.getSafeName(graph, templateConnector, true)\r
954                                         + " to " + NameUtils.getSafeName(graph, targetConnector, true));\r
955                         }\r
956                     }\r
957                 }\r
958             }\r
959         }\r
960 \r
961         // 0.2. find mapping between source and target route lines\r
962         Collection<Resource> sourceInteriorRouteNodes = graph.getObjects(sourceConnection, DIA.HasInteriorRouteNode);\r
963         Collection<Resource> targetInteriorRouteNodes = graph.getObjects(targetConnection, DIA.HasInteriorRouteNode);\r
964         Map<Resource, Paster.RouteLine> sourceToRouteLine = new THashMap<>();\r
965         Map<Resource, Paster.RouteLine> targetToRouteLine = new THashMap<>();\r
966 \r
967         for (Resource source : sourceInteriorRouteNodes)\r
968             sourceToRouteLine.put(source, Paster.readRouteLine(graph, source));\r
969         for (Resource target : targetInteriorRouteNodes)\r
970             targetToRouteLine.put(target, Paster.readRouteLine(graph, target));\r
971 \r
972         Map<Resource, Paster.RouteLine> originalSourceToRouteLine = new THashMap<>(sourceToRouteLine);\r
973         Map<Resource, Paster.RouteLine> originalTargetToRouteLine = new THashMap<>(targetToRouteLine);\r
974 \r
975         nextSourceLine:\r
976             for (Iterator<Map.Entry<Resource, Paster.RouteLine>> sourceIt = sourceToRouteLine.entrySet().iterator(); !targetToRouteLine.isEmpty() && sourceIt.hasNext();) {\r
977                 Map.Entry<Resource, Paster.RouteLine> sourceEntry = sourceIt.next();\r
978                 Paster.RouteLine sourceLine = sourceEntry.getValue();\r
979                 for (Iterator<Map.Entry<Resource, Paster.RouteLine>> targetIt = targetToRouteLine.entrySet().iterator(); targetIt.hasNext();) {\r
980                     Map.Entry<Resource, Paster.RouteLine> targetEntry = targetIt.next();\r
981                     if (sourceLine.equals(targetEntry.getValue())) {\r
982                         s2t.put(sourceEntry.getKey(), targetEntry.getKey());\r
983                         t2s.put(targetEntry.getKey(), sourceEntry.getKey());\r
984                         sourceIt.remove();\r
985                         targetIt.remove();\r
986 \r
987                         if (DEBUG)\r
988                             debug(typicalInfo, "Mapping routeline "\r
989                                     + NameUtils.getSafeName(graph, sourceEntry.getKey(), true)\r
990                                     + " - " + sourceEntry.getValue()\r
991                                     + " to " + NameUtils.getSafeName(graph, targetEntry.getKey(), true)\r
992                                     + " - " + targetEntry.getValue());\r
993 \r
994                         continue nextSourceLine;\r
995                     }\r
996                 }\r
997             }\r
998 \r
999         if (DEBUG) {\r
1000             debug(typicalInfo, "Take 1: Source to target route nodes map : " + s2t);\r
1001             debug(typicalInfo, "Take 1: Target to source route nodes map : " + t2s);\r
1002         }\r
1003 \r
1004         // 1.1. Temporarily disconnect instance-specific connectors from the the connection .\r
1005         //      They will be added back to the connection after the templatized parts of the\r
1006         //      connection have been synchronized.\r
1007 \r
1008         // Stores diagram connectors that are customizations in the synchronized instance.\r
1009         List<Connector> instanceOnlyConnectors = null;\r
1010 \r
1011         for (Connector connector : targetConnectors.values()) {\r
1012             if (!t2s.containsKey(connector.connector)) {\r
1013                 typicalInfo.messageLog.add("\t\tencountered instance-specific diagram connector in target connection: " + NameUtils.getSafeName(graph, connector.connector));\r
1014 \r
1015                 // Find the RouteLine this connectors is connected to.\r
1016                 for (Resource rl : graph.getObjects(connector.connector, DIA.AreConnected)) {\r
1017                     connector.attachedTo = originalTargetToRouteLine.get(rl);\r
1018                     if (connector.attachedTo != null)\r
1019                         break;\r
1020                 }\r
1021 \r
1022                 // Disconnect connector from connection\r
1023                 graph.deny(targetConnection, connector.attachmentRelation, connector.connector);\r
1024                 graph.deny(connector.connector, DIA.AreConnected);\r
1025 \r
1026                 // Keep track of the disconnected connector\r
1027                 if (instanceOnlyConnectors == null)\r
1028                     instanceOnlyConnectors = new ArrayList<>(targetConnectors.size());\r
1029                 instanceOnlyConnectors.add(connector);\r
1030             }\r
1031         }\r
1032 \r
1033         // 1.2. add missing connectors to target\r
1034         Collection<Resource> sourceConnectors = graph.getObjects(sourceConnection, DIA.HasConnector);\r
1035         for (Resource sourceConnector : sourceConnectors) {\r
1036             if (!s2t.containsKey(sourceConnector)) {\r
1037                 Statement sourceIsConnectorOf = graph.getSingleStatement(sourceConnector, DIA.IsConnectorOf);\r
1038                 Statement connects = cu.getConnectedComponentStatement(sourceConnection, sourceConnector);\r
1039                 if (connects == null) {\r
1040                     // TODO: serious error!\r
1041                     throw new DatabaseException("ERROR: connector is astray, i.e. not connected to a node element: " + safeNameAndType(graph, sourceConnector));\r
1042                 }\r
1043                 Resource connectsInstanceElement = typicalInfo.bean.templateToInstance.get(connects.getObject());\r
1044                 if (connectsInstanceElement == null) {\r
1045                     // TODO: serious error!\r
1046                     throw new DatabaseException("ERROR: could not find instance element to which template element " + safeNameAndType(graph, connects.getObject()) + " is connected to");\r
1047                 }\r
1048                 Resource hasConnector = graph.getInverse(sourceIsConnectorOf.getPredicate());\r
1049 \r
1050                 Resource newTargetConnector = cu.newConnector(targetConnection, hasConnector);\r
1051                 graph.claim(newTargetConnector, connects.getPredicate(), connectsInstanceElement);\r
1052                 changed = true;\r
1053 \r
1054                 s2t.put(sourceConnector, newTargetConnector);\r
1055                 t2s.put(newTargetConnector, sourceConnector);\r
1056 \r
1057                 typicalInfo.messageLog.add("\t\t\tadd new connector to target connection: " + NameUtils.getSafeName(graph, newTargetConnector) + " to map to source connector " + NameUtils.getSafeName(graph, sourceConnector));\r
1058             }\r
1059         }\r
1060 \r
1061         // 2. sync route lines and their connectivity:\r
1062         // 2.1. assign correspondences in target for each source route line\r
1063         //      by reusing excess route lines in target and by creating new\r
1064         //      route lines.\r
1065 \r
1066         Resource[] targetRouteLines = targetToRouteLine.keySet().toArray(Resource.NONE);\r
1067         int targetRouteLine = targetRouteLines.length - 1;\r
1068 \r
1069         for (Iterator<Map.Entry<Resource, Paster.RouteLine>> sourceIt = sourceToRouteLine.entrySet().iterator(); sourceIt.hasNext();) {\r
1070             Map.Entry<Resource, Paster.RouteLine> sourceEntry = sourceIt.next();\r
1071             Resource source = sourceEntry.getKey();\r
1072             Paster.RouteLine sourceLine = sourceEntry.getValue();\r
1073 \r
1074             typicalInfo.messageLog.add("\t\t\tassign an instance-side routeline counterpart for " + NameUtils.getSafeName(graph, source, true) + " - " + sourceLine);\r
1075 \r
1076             // Assign target route line for source\r
1077             Resource target = null;\r
1078             if (targetRouteLine < 0) {\r
1079                 // by creating new route lines\r
1080                 target = cu.newRouteLine(targetConnection, sourceLine.getPosition(), sourceLine.isHorizontal());\r
1081                 typicalInfo.messageLog.add("\t\t\tcreate new route line " + NameUtils.getSafeName(graph, target));\r
1082                 changed = true;\r
1083             } else {\r
1084                 // by reusing existing route line\r
1085                 target = targetRouteLines[targetRouteLine--];\r
1086                 copyRouteLine(graph, source, target);\r
1087                 cu.disconnectFromAllRouteNodes(target);\r
1088                 typicalInfo.messageLog.add("\t\t\treused existing route line " + NameUtils.getSafeName(graph, target));\r
1089                 changed = true;\r
1090             }\r
1091             s2t.put(source, target);\r
1092             t2s.put(target, source);\r
1093 \r
1094             typicalInfo.messageLog.add("\t\t\tmapped source route line " + NameUtils.getSafeName(graph, source) + " to target route line " + NameUtils.getSafeName(graph, target));\r
1095         }\r
1096 \r
1097         if (targetRouteLine >= 0) {\r
1098             typicalInfo.messageLog.add("\t\t\tremove excess route lines (" + (targetRouteLine + 1) + ") from target connection");\r
1099             for (; targetRouteLine >= 0; targetRouteLine--) {\r
1100                 typicalInfo.messageLog.add("\t\t\t\tremove excess route line: " + NameUtils.getSafeName(graph, targetRouteLines[targetRouteLine], true));\r
1101                 cu.removeConnectionPart(targetRouteLines[targetRouteLine]);\r
1102             }\r
1103         }\r
1104 \r
1105         if (DEBUG) {\r
1106             debug(typicalInfo, "Take 2: Source to target route nodes map : " + s2t);\r
1107             debug(typicalInfo, "Take 2: Target to source route nodes map : " + t2s);\r
1108         }\r
1109 \r
1110         // 2.2. Synchronize target connection topology (DIA.AreConnected)\r
1111         changed |= connectRouteNodes(graph, typicalInfo, sourceInteriorRouteNodes);\r
1112         changed |= connectRouteNodes(graph, typicalInfo, sourceConnectors);\r
1113 \r
1114         // 3. remove excess routelines & connectors from target connection\r
1115         changed |= cu.removeExtraInteriorRouteNodes(targetConnection) > 0;\r
1116         changed |= cu.removeUnusedConnectors(targetConnection) > 0;\r
1117 \r
1118         // 3.1. Ensure that all mapped route nodes in the target connection\r
1119         //      are tagged with MOD.IsTemplatized. Future synchronization\r
1120         //      can then take advantage of this information to more easily\r
1121         //      decide which parts of the connection are originated from\r
1122         //      the template and which are not.\r
1123         changed |= markMappedRouteNodesTemplatized(graph, s2t.values());\r
1124 \r
1125         // 4. Add temporarily disconnected instance-specific connectors\r
1126         //    back to the synchronized connection. The route line to attach\r
1127         //    to is based on a simple heuristic.\r
1128         if (instanceOnlyConnectors != null) {\r
1129             if (originalSourceToRouteLine.isEmpty()) {\r
1130                 // If there are 0 route lines in the template connection,\r
1131                 // then one must be added to the instance connection.\r
1132                 // This can only happen if the template connection is\r
1133                 // simple, i.e. just between two terminals without any\r
1134                 // custom routing.\r
1135 \r
1136                 // Attach all target connection connectors to the newly created route line\r
1137                 Resource rl = cu.newRouteLine(targetConnection, null, null);\r
1138                 for (Resource sourceConnector : sourceConnectors) {\r
1139                     Resource targetConnector = s2t.get(sourceConnector);\r
1140                     graph.deny(targetConnector, DIA.AreConnected);\r
1141                     graph.claim(targetConnector, DIA.AreConnected, DIA.AreConnected, rl);\r
1142                 }\r
1143 \r
1144                 // Copy orientation and position for new route line from original target route lines.\r
1145                 // This is a simplification that will attach any amount of route lines in the original\r
1146                 // target connection into just one route line. There is room for improvement here\r
1147                 // but it will require a more elaborate algorithm to find and cut the non-templatized\r
1148                 // route lines as well as connectors out of the connection before synchronizing it.\r
1149                 //\r
1150                 // TODO: This implementation chooses the added route line position at random if\r
1151                 //       there are multiple route lines in the target connection.\r
1152                 if (!originalTargetToRouteLine.isEmpty()) {\r
1153                     RouteLine originalRl = originalTargetToRouteLine.values().iterator().next();\r
1154                     setRouteLine(graph, rl, originalRl);\r
1155                 }\r
1156 \r
1157                 // Attach the instance specific connectors also to the only route line\r
1158                 for (Connector connector : instanceOnlyConnectors) {\r
1159                     graph.claim(targetConnection, connector.attachmentRelation, connector.connector);\r
1160                     graph.claim(connector.connector, DIA.AreConnected, DIA.AreConnected, rl);\r
1161                 }\r
1162 \r
1163                 changed = true;\r
1164             } else {\r
1165                 for (Connector connector : instanceOnlyConnectors) {\r
1166                     // Find the route line that most closely matches the original\r
1167                     // route line that the connector was connected to.\r
1168                     Resource closestMatch = null;\r
1169                     double closestDistance = Double.MAX_VALUE;\r
1170                     if (connector.attachedTo != null) {\r
1171                         for (Map.Entry<Resource, Paster.RouteLine> sourceLine : originalSourceToRouteLine.entrySet()) {\r
1172                             double dist = distance(sourceLine.getValue(), connector.attachedTo);\r
1173                             if (dist < closestDistance) {\r
1174                                 closestMatch = s2t.get(sourceLine.getKey());\r
1175                                 closestDistance = dist;\r
1176                             }\r
1177                         }\r
1178                     } else {\r
1179                         closestMatch = originalSourceToRouteLine.keySet().iterator().next();\r
1180                     }\r
1181                     graph.claim(targetConnection, connector.attachmentRelation, connector.connector);\r
1182                     graph.claim(connector.connector, DIA.AreConnected, DIA.AreConnected, closestMatch);\r
1183                     if (closestDistance > 0)\r
1184                         changed = true;\r
1185                     typicalInfo.messageLog.add("\t\t\treattached instance-specific connector "\r
1186                             + NameUtils.getSafeName(graph, connector.connector) + " to nearest existing route line "\r
1187                             + NameUtils.getSafeName(graph, closestMatch) + " with distance " + closestDistance);\r
1188                 }\r
1189             }\r
1190         }\r
1191 \r
1192         return changed;\r
1193     }\r
1194 \r
1195     private boolean markMappedRouteNodesTemplatized(WriteGraph graph, Iterable<Resource> routeNodes) throws DatabaseException {\r
1196         boolean changed = false;\r
1197         for (Resource rn : routeNodes) {\r
1198             if (!graph.hasStatement(rn, MOD.IsTemplatized)) {\r
1199                 graph.claim(rn, MOD.IsTemplatized, MOD.IsTemplatized, rn);\r
1200                 changed = true;\r
1201             }\r
1202         }\r
1203         return changed;\r
1204     }\r
1205 \r
1206     private static double distance(RouteLine l1, RouteLine l2) {\r
1207         double dist = Math.abs(l2.getPosition() - l1.getPosition());\r
1208         dist *= l2.isHorizontal() == l1.isHorizontal() ? 1 : 1000;\r
1209         return dist;\r
1210     }\r
1211 \r
1212     private boolean connectRouteNodes(WriteGraph graph, TypicalInfo typicalInfo, Collection<Resource> sourceRouteNodes) throws DatabaseException {\r
1213         boolean changed = false;\r
1214         for (Resource src : sourceRouteNodes) {\r
1215             Resource dst = s2t.get(src);\r
1216             if (dst == null) {\r
1217                 throw new DatabaseException("TARGET ROUTE NODE == NULL FOR SRC: " + NameUtils.getSafeName(graph, src));\r
1218             }\r
1219 \r
1220             Collection<Resource> connectedToSrcs = graph.getObjects(src, DIA.AreConnected);\r
1221             Collection<Resource> connectedToDsts = graph.getObjects(dst, DIA.AreConnected);\r
1222 \r
1223             // Remove excess statements\r
1224             for (Resource connectedToDst : connectedToDsts) {\r
1225                 Resource connectedToSrc = t2s.get(connectedToDst);\r
1226                 if (connectedToSrc == null) {\r
1227                     throw new DatabaseException("CONNECTED TO SRC == NULL FOR DST: " + NameUtils.getSafeName(graph, connectedToDst));\r
1228                 }\r
1229                 if (connectedToSrc == null || !graph.hasStatement(src, DIA.AreConnected, connectedToSrc)) {\r
1230                     graph.deny(dst, DIA.AreConnected, DIA.AreConnected, connectedToDst);\r
1231                     changed = true;\r
1232                     typicalInfo.messageLog.add("\t\t\tdisconnected route nodes (" + NameUtils.getSafeName(graph, dst) + ", " + NameUtils.getSafeName(graph, connectedToDst) + ")");\r
1233                 }\r
1234             }\r
1235 \r
1236             // Add necessary statements\r
1237             for (Resource connectedToSrc : connectedToSrcs) {\r
1238                 Resource connectedToDst = s2t.get(connectedToSrc);\r
1239                 if (connectedToDst == null) {\r
1240                     throw new DatabaseException("CONNECTED TO DST == NULL FOR SRC: " + NameUtils.getSafeName(graph, connectedToSrc));\r
1241                 }\r
1242                 if (!graph.hasStatement(dst, DIA.AreConnected, connectedToDst)) {\r
1243                     graph.claim(dst, DIA.AreConnected, DIA.AreConnected, connectedToDst);\r
1244                     changed = true;\r
1245                     typicalInfo.messageLog.add("\t\t\tconnected route nodes (" + NameUtils.getSafeName(graph, dst) + ", " + NameUtils.getSafeName(graph, connectedToDst) + ")");\r
1246                 }\r
1247             }\r
1248         }\r
1249         return changed;\r
1250     }\r
1251 \r
1252     private void setRouteLine(WriteGraph graph, Resource line, double position, boolean horizontal) throws DatabaseException {\r
1253         graph.claimLiteral(line, DIA.HasPosition, L0.Double, position, Bindings.DOUBLE);\r
1254         graph.claimLiteral(line, DIA.IsHorizontal, L0.Boolean, horizontal, Bindings.BOOLEAN);\r
1255     }\r
1256 \r
1257     private void setRouteLine(WriteGraph graph, Resource line, RouteLine rl) throws DatabaseException {\r
1258         setRouteLine(graph, line, rl.getPosition(), rl.isHorizontal());\r
1259     }\r
1260 \r
1261     private void copyRouteLine(WriteGraph graph, Resource src, Resource tgt) throws DatabaseException {\r
1262         Double pos = graph.getPossibleRelatedValue(src, DIA.HasPosition, Bindings.DOUBLE);\r
1263         Boolean hor = graph.getPossibleRelatedValue(src, DIA.IsHorizontal, Bindings.BOOLEAN);\r
1264         if (pos == null)\r
1265             pos = 0.0;\r
1266         if (hor == null)\r
1267             hor = Boolean.TRUE;\r
1268         graph.claimLiteral(tgt, DIA.HasPosition, L0.Double, pos, Bindings.DOUBLE);\r
1269         graph.claimLiteral(tgt, DIA.IsHorizontal, L0.Boolean, hor, Bindings.BOOLEAN);\r
1270     }\r
1271 \r
1272     private static String safeNameAndType(ReadGraph graph, Resource r) throws DatabaseException {\r
1273         StringBuilder sb = new StringBuilder();\r
1274         sb.append(NameUtils.getSafeName(graph, r, true));\r
1275         sb.append(" : [");\r
1276         boolean first = true;\r
1277         for (Resource type : graph.getPrincipalTypes(r)) {\r
1278             if (!first)\r
1279                 sb.append(",");\r
1280             first = false;\r
1281             sb.append(NameUtils.getSafeName(graph, type, true));\r
1282         }\r
1283         sb.append("]");\r
1284         return sb.toString();\r
1285     }\r
1286 \r
1287     private static <K, V> Map<K, V> newOrClear(Map<K, V> current) {\r
1288         if (current == null)\r
1289             return new THashMap<>();\r
1290         current.clear();\r
1291         return current;\r
1292     }\r
1293 \r
1294     private void debug(TypicalInfo typicalInfo, String message) {\r
1295         if (DEBUG) {\r
1296             System.out.println(message);\r
1297             typicalInfo.messageLog.add(message);\r
1298         }\r
1299     }\r
1300 \r
1301 }