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