1 package org.simantics.structural2.variables;
3 import java.util.ArrayList;
4 import java.util.Collection;
5 import java.util.Collections;
6 import java.util.HashMap;
7 import java.util.HashSet;
12 import org.simantics.databoard.Bindings;
13 import org.simantics.db.ReadGraph;
14 import org.simantics.db.Resource;
15 import org.simantics.db.Statement;
16 import org.simantics.db.common.procedure.adapter.TransientCacheAsyncListener;
17 import org.simantics.db.common.request.BinaryRead;
18 import org.simantics.db.common.request.ResourceRead;
19 import org.simantics.db.common.request.TransientUnaryRead;
20 import org.simantics.db.common.utils.CommonDBUtils;
21 import org.simantics.db.common.utils.NameUtils;
22 import org.simantics.db.exception.DatabaseException;
23 import org.simantics.db.exception.NoSingleResultException;
24 import org.simantics.db.layer0.exception.MissingVariableException;
25 import org.simantics.db.layer0.exception.MissingVariableValueException;
26 import org.simantics.db.layer0.request.VariableRead;
27 import org.simantics.db.layer0.variable.Variable;
28 import org.simantics.db.service.CollectionSupport;
29 import org.simantics.db.service.QueryControl;
30 import org.simantics.layer0.Layer0;
31 import org.simantics.modeling.ModelingResources;
32 import org.simantics.structural.stubs.StructuralResource2;
33 import org.simantics.structural2.Functions;
34 import org.simantics.structural2.Functions.InterfaceResolution;
35 import org.simantics.structural2.queries.ConnectionSet;
36 import org.simantics.structural2.utils.StructuralUtils;
37 import org.simantics.structural2.utils.StructuralUtils.StructuralComponentClass;
38 import org.simantics.structural2.variables.StandardProceduralChildVariable.FixedConnection;
39 import org.simantics.utils.datastructures.Pair;
41 import gnu.trove.map.hash.THashMap;
42 import gnu.trove.set.hash.THashSet;
44 public class ConnectionBrowser {
47 * Finds the components connected by the connection. Also connections
51 * @param connection A connection whose related modules are searched.
52 * @param configuration A variable that represents the composite where the connection belongs to.
53 * @return A map whose keys are components and they are mapped to
56 public static Collection<ResourceWithContext> findConnectedComponents(
57 ReadGraph graph, Resource connection, Variable configuration)
58 throws DatabaseException {
60 ArrayList<ResourceWithContext> result =
61 new ArrayList<ResourceWithContext>();
62 THashSet<Resource> visitedConnections = new THashSet<Resource>();
65 findConnectedComponents(graph, connection, configuration, result,
70 private static void findConnectedComponents(
71 ReadGraph graph, Resource connection, Variable configuration,
72 ArrayList<ResourceWithContext> result,
73 THashSet<Resource> visitedConnections) throws DatabaseException {
74 if(visitedConnections.add(connection)) {
75 StructuralResource2 STR = StructuralResource2.getInstance(graph);
76 Layer0 L0 = Layer0.getInstance(graph);
78 // Browse related components
79 for(Statement stat : graph.getStatements(connection, STR.Connects)) {
80 Resource component = stat.getObject();
81 Resource relation = graph.getInverse(stat.getPredicate());
82 //System.out.println(NameUtils.getSafeName(graph, component) + "." + NameUtils.getSafeName(graph, relation));
83 Resource boundConnection = graph.getPossibleObject(relation, STR.IsBoundBy);
84 Resource type = StructuralUtils.getPossibleComponentType(graph, configuration, component);
85 Resource def = type != null ? graph.getPossibleObject(type, STR.IsDefinedBy) : null;
86 if(boundConnection != null && def != null) {
87 // The connection point is bound in component type
88 Variable newContext = configuration.browsePossible(graph, component);
89 Resource newComposite = getCompositeOfConnection(graph, boundConnection);
90 if(newContext != null && newComposite != null) {
91 newContext = browse(graph, def, newContext, newComposite);
92 if (newContext != null)
93 findConnectedComponents(graph, boundConnection,
95 result, visitedConnections);
99 //System.out.println("added result");
100 // A primitive connection point
101 Variable context = configuration.browsePossible(graph, component);
103 result.add(new ResourceWithContext(component, context));
107 // Browse over connection joins
108 for(Resource join : graph.getObjects(connection, STR.IsJoinedBy))
109 for(Resource otherConnection : graph.getObjects(join, STR.Joins))
110 if(!connection.equals(otherConnection)) {
111 Resource sourceComposite = getCompositeOfConnection(graph, connection);
112 Resource targetComposite = getCompositeOfConnection(graph, otherConnection);
113 if (sourceComposite != null && targetComposite != null) {
114 Variable sibling = browseSibling(graph,
119 findConnectedComponents(graph, otherConnection,
120 sibling, result, visitedConnections);
126 for(Resource relation : graph.getObjects(connection, STR.Binds)) {
127 Resource composite = getCompositeOfConnection(graph, connection);
128 if (composite == null)
131 Variable curConfiguration = configuration;
132 while(!graph.hasStatement(composite, STR.Defines)) {
133 composite = graph.getSingleObject(composite, L0.PartOf);
134 curConfiguration = curConfiguration.getParent(graph);
136 Variable parent = curConfiguration.getParent(graph);
137 Resource component = curConfiguration.getRepresents(graph);
138 for(Resource c : graph.getObjects(component, relation))
139 findConnectedComponents(graph, c,
140 parent, result, visitedConnections);
142 } catch(NoSingleResultException e) {
143 } catch(MissingVariableException e) {
144 } catch(MissingVariableValueException e) {
149 public static Collection<VariableConnectionPointDescriptor> drill(ReadGraph graph, VariableConnectionPointDescriptor pair) throws DatabaseException {
151 Collection<InterfaceResolution> interfaceDescription = pair.getInterfaceDescription(graph);
152 if(interfaceDescription != null && interfaceDescription.size() > 0) {
154 Variable cp = pair.getVariable(graph);
155 Variable context = cp.getParent(graph);
156 String cpName = cp.getName(graph);
158 Collection<VariableConnectionPointDescriptor> result = new ArrayList<VariableConnectionPointDescriptor>();
159 for(InterfaceResolution r : interfaceDescription) {
160 if(r.interfaceName.equals(cpName)) {
161 String path = Functions.resolveInterfacePath(graph, context, r.componentName, r.connectionPoint);
162 result.add(new BrowseConnectionDescriptor(context, path));
166 if(result.isEmpty()) return null;
171 return Collections.singleton(pair);
176 public static class JoinConnections extends ResourceRead<Collection<Resource>> {
178 public JoinConnections(Resource join) {
183 public Collection<Resource> perform(ReadGraph graph) throws DatabaseException {
184 ConnectionSet cs = new ConnectionSet(graph);
185 cs.addJoin(graph, resource);
186 return cs.getConnections();
192 public static final class VariableChildren extends TransientUnaryRead<Variable, Map<Resource,Variable>> {
194 public VariableChildren(ReadGraph graph, Variable variable) throws DatabaseException {
195 super(graph, variable);
198 public VariableChildren(ReadGraph graph, QueryControl qc, Variable variable) throws DatabaseException {
199 super(graph, qc, variable);
203 public Map<Resource, Variable> perform(ReadGraph graph, Variable parameter) throws DatabaseException {
204 CollectionSupport cs = graph.getService(CollectionSupport.class);
205 Map<Resource,Variable> result = cs.createMap(Variable.class);
206 for(Variable child : parameter.getChildren(graph)) {
207 Resource represents = child.getPossibleRepresents(graph);
208 if(represents != null) result.put(represents, child);
215 static Variable resolve(ReadGraph graph, Variable base, Resource component) throws DatabaseException {
216 Map<Resource,Variable> map = graph.syncRequest(new VariableChildren(graph, base), TransientCacheAsyncListener.<Map<Resource,Variable>>instance());
217 Variable result = map.get(component);
218 if(result != null) return result;
220 Layer0 L0 = Layer0.getInstance(graph);
221 Resource parent = graph.getPossibleObject(component, L0.PartOf);
222 if(parent == null) return null;
223 Variable v = resolve(graph, base, parent);
224 if (v == null) return null;
225 map = graph.syncRequest(new VariableChildren(graph, v), TransientCacheAsyncListener.<Map<Resource,Variable>>instance());
226 return map.get(component);
230 public static class ConnectionComponentsWithAncestor extends TransientUnaryRead<Resource, List<Resource>> {
232 final private List<Resource> result;
234 public ConnectionComponentsWithAncestor(ReadGraph graph, Resource conn) throws DatabaseException {
235 this(graph, conn, null);
238 public ConnectionComponentsWithAncestor(ReadGraph graph, QueryControl qc, Resource conn, List<Resource> result) throws DatabaseException {
239 super(graph, qc, conn);
240 this.result = result;
243 public ConnectionComponentsWithAncestor(ReadGraph graph, Resource conn, List<Resource> result) throws DatabaseException {
245 this.result = result;
248 private ConnectionSet connSet(ReadGraph graph, Resource r ) throws DatabaseException {
249 ConnectionSet cs = new ConnectionSet(graph);
250 cs.addConnection(graph, r);
255 public List<Resource> perform(ReadGraph graph, Resource resource) throws DatabaseException {
257 if(result != null) return result;
259 Layer0 L0 = Layer0.getInstance(graph);
260 StructuralResource2 STR = StructuralResource2.getInstance(graph);
261 CollectionSupport colls = graph.getService(CollectionSupport.class);
262 THashSet<Resource> ancestorGenerators = new THashSet<Resource>();
263 Set<Resource> parts = colls.createSet();
264 ConnectionSet cs = connSet(graph, resource);
265 for(Resource connRes : cs.getConnections()) {
266 for(Statement stm : graph.getStatements(connRes, STR.Connects)) {
267 Resource component = stm.getObject();
268 Resource parent = graph.getPossibleObject(component, L0.PartOf);
269 if(parent != null && !graph.isInstanceOf(component, ModelingResources.getInstance(graph).ReferenceElement))
270 ancestorGenerators.add(parent);
274 for (Resource join : cs.getJoins()) {
276 for (Resource composite : graph.getObjects(join, STR.JoinsComposite))
277 ancestorGenerators.add(composite);
279 Resource ancestor = ancestorGenerators.size() == 1 ? ancestorGenerators.iterator().next() : CommonDBUtils.getNearestOwner(graph, ancestorGenerators);
281 List<Resource> result = colls.createList();
282 result.add(ancestor);
283 result.addAll(colls.asSortedList(parts));
285 if(parameter != WITH_PARENT) {
286 for(int i=1;i<result.size();i++) {
287 Resource r = result.get(i);
289 if(!r.equals(resource))
290 graph.syncRequest(new ConnectionComponentsWithAncestor(graph, r, result), TransientCacheAsyncListener.<List<Resource>>instance());
300 public static Collection<VariableConnectionPointDescriptor> climb(ReadGraph graph, Variable child, Resource cp, String subPath_) throws DatabaseException {
302 boolean isStructural = false;
304 Variable curConfiguration = child.getParent(graph);
308 Collection<InterfaceResolution> interfaceDescription = Functions.computeInterfacePaths(graph, curConfiguration);
309 if(interfaceDescription != null) {
310 isStructural = interfaceDescription != Functions.BUILTIN_STRUCTURAL_CPS;
311 if(interfaceDescription.size() > 0) {
313 if(subPath_ == null) {
315 String childName = child.getName(graph);
316 for(InterfaceResolution r : interfaceDescription) {
317 if(r.componentName.equals(childName) && r.connectionPoint.equals(cp)) {
318 Variable pConn = curConfiguration.getPossibleProperty(graph, r.interfaceName);
320 Resource cp2 = pConn.getPossiblePredicateResource(graph);
321 Collection<VariableConnectionPointDescriptor> res = climb(graph, curConfiguration, cp2, null);
322 if(res != null) return res;
324 return Collections.emptyList();
329 throw new UnsupportedOperationException("");
336 if(child instanceof StandardProceduralChildVariable) {
338 Variable conn = child.getPossibleProperty(graph, cp);
339 FixedConnection fc = (FixedConnection)conn.getValue(graph);
340 Set<VariableConnectionPointDescriptor> result = new THashSet<VariableConnectionPointDescriptor>(1+fc.cps.size());
341 result.add(new ComponentConnectionDescriptor(child, cp));// (graph, STR, curConfiguration, "/" + c.name + "#" + conn.getName(graph)));
342 for(Pair<String,Resource> cpzz : fc.cps) {
343 if(cpzz.first == null) {
344 throw new DatabaseException("Lifted connection was not resolved.");
346 result.add(new PairConnectionDescriptor(curConfiguration, cpzz));
353 Resource represents = child.getRepresents(graph);
357 Collection<Resource> conns = graph.getObjects(represents, res);
358 HashSet<VariableConnectionPointDescriptor> result = new HashSet<VariableConnectionPointDescriptor>();
359 for(Resource c : conns) {
360 List<Resource> rs = graph.syncRequest(new ConnectionComponentsWithAncestor(graph, c), TransientCacheAsyncListener.<List<Resource>>instance());
361 result.addAll(graph.syncRequest(ConnectionVariables.forStructural(graph, curConfiguration, rs)));
367 Resource connection = graph.getPossibleObject(represents, res);
368 if(connection != null) {
369 List<Resource> rs = graph.syncRequest(new ConnectionComponentsWithAncestor(graph, connection), TransientCacheAsyncListener.<List<Resource>>instance());
370 return graph.syncRequest(ConnectionVariables.forConfiguration(graph, curConfiguration, rs));
373 Collection<Resource> conns = graph.getObjects(represents, res);
374 HashSet<VariableConnectionPointDescriptor> result = new HashSet<VariableConnectionPointDescriptor>();
375 for(Resource c : conns) {
376 List<Resource> rs = graph.syncRequest(new ConnectionComponentsWithAncestor(graph, c), TransientCacheAsyncListener.<List<Resource>>instance());
377 result.addAll(graph.syncRequest(ConnectionVariables.forConfiguration(graph, curConfiguration, rs)));
388 public static void reportDescriptor(ReadGraph graph, VariableConnectionPointDescriptor d) throws DatabaseException {
390 if(d instanceof ActualConnectionDescriptor) {
391 ActualConnectionDescriptor d2 = (ActualConnectionDescriptor)d;
393 System.err.println("--ActualConnectionPointDescriptor2");
394 System.err.println("---root: " + d2.root.getURI(graph));
395 System.err.println("---component: " + graph.getPossibleURI(d2.component));
396 System.err.println("---type: " + graph.getPossibleURI(d2.componentType));
397 System.err.println("---cp: " + graph.getPossibleURI(d2.cp));
398 System.err.println("---var: " + d2.getVariable(graph).getURI(graph));
403 public static class ConnectionVariables extends BinaryRead<Variable, List<Resource>, Collection<VariableConnectionPointDescriptor>> {
405 private ConnectionVariables(Variable parameter1, List<Resource> parameter2) {
406 super(parameter1, parameter2);
409 public static ConnectionVariables forConfiguration(ReadGraph graph, Variable configuration, List<Resource> rs) throws DatabaseException {
410 return new ConnectionVariables(parent(graph, configuration, rs.get(0)), rs);
413 public static ConnectionVariables forStructural(ReadGraph graph, Variable configuration, List<Resource> rs) throws DatabaseException {
414 return new ConnectionVariables(configuration, rs);
418 * Finds the parent variable of <code>configuration</code> that
419 * represents <code>ancestor</code>.
422 * @param configuration
425 * @throws DatabaseException if no parent was found that represents ancestor
427 private static Variable parent(ReadGraph graph, Variable configuration, Resource ancestor) throws DatabaseException {
428 Variable v = configuration;
429 Resource represents = v.getRepresents(graph);
430 while(!represents.equals(ancestor)) {
431 v = v.getParent(graph);
433 throw new DatabaseException(
434 "parent representing ancestor not found for variable, configuration="
435 + safeURI(graph, configuration)
437 + NameUtils.getURIOrSafeNameInternal(graph, ancestor));
439 represents = v.getRepresents(graph);
445 public Collection<VariableConnectionPointDescriptor> perform(ReadGraph graph) throws DatabaseException {
446 if(parameter == null) return Collections.emptyList();
447 Layer0 L0 = Layer0.getInstance(graph);
448 StructuralResource2 STR = StructuralResource2.getInstance(graph);
449 ArrayList<VariableConnectionPointDescriptor> result = null;
450 for(int i=1;i<parameter2.size();i++) {
451 Resource connRes = parameter2.get(i);
452 for(Statement stm : graph.getStatements(connRes, STR.Connects)) {
453 Resource component = stm.getObject();
454 Resource connectionPoint = graph.getInverse(stm.getPredicate());
455 if(result == null) result = new ArrayList<VariableConnectionPointDescriptor>();
456 String componentName = graph.getRelatedValue(component, L0.HasName, Bindings.STRING);
457 Variable possibleChild = parameter.getPossibleChild(graph, componentName);
458 if(possibleChild != null) {
459 Resource type = possibleChild.getPossibleType(graph, STR.Component);
461 result.add(new ActualConnectionDescriptor(parameter, component, possibleChild.getType(graph), connectionPoint));
463 throw new DatabaseException("Child does not have a structural type: " + possibleChild.getURI(graph));
466 Resource type = graph.getPossibleType(component, STR.Component);
468 result.add(new ActualConnectionDescriptor(parameter, component, type, connectionPoint));
470 throw new DatabaseException("Child with name " + componentName + " does not have a structural type: " + parameter.getURI(graph));
475 if(result == null) return Collections.emptyList();
481 static class IsLeafType extends ResourceRead<Boolean> {
483 protected IsLeafType(Resource type) {
488 public Boolean perform(ReadGraph graph) throws DatabaseException {
490 StructuralComponentClass clazz = StructuralComponentClass.get(graph, resource);
491 return StructuralComponentClass.PRIMITIVE.equals(clazz);
497 static class ChildMapOfVariable extends VariableRead<Map<Resource,Variable>> {
499 public ChildMapOfVariable(Variable variable) {
504 public Map<Resource, Variable> perform(ReadGraph graph) throws DatabaseException {
505 HashMap<Resource,Variable> result = new HashMap<Resource,Variable>();
506 for(Variable child : variable.getChildren(graph)) {
507 Resource represents = child.getPossibleRepresents(graph);
508 if(represents != null) result.put(represents, child);
516 * Given a root composite, related variable and some other component inside the composite,
517 * finds the related variable for that component.
519 public static Variable browse(ReadGraph graph, Resource root, Variable rootContext, Resource target) throws DatabaseException {
520 if(target.equals(root))
523 Layer0 L0 = Layer0.getInstance(graph);
524 String name = (String)graph.getPossibleRelatedValue(target, L0.HasName, Bindings.STRING);
525 Resource parent = graph.getPossibleObject(target, L0.PartOf);
526 if(name == null || parent == null)
528 Variable parentVariable = browse(graph, root, rootContext, parent);
529 if(parentVariable == null)
531 return parentVariable.getPossibleChild(graph, name);
536 * Finds a variable whose location related to sourceContext is the same as
537 * between target and source. In other words, the method solves {@code targetContext}
538 * in the following equations:
540 * URI(source) = resourceURIBase + sourceSuffix
541 * URI(sourceContext) = variableURIBase + sourceSuffix
542 * URI(target) = resourceURIBase + targetSuffix
543 * URI(targetContext) = variableURIBase + targetSuffix
546 public static Variable browseSibling(ReadGraph graph, Resource source, Variable sourceContext, Resource target) throws DatabaseException {
547 Layer0 L0 = Layer0.getInstance(graph);
548 THashMap<Resource, Variable> sourceMap = new THashMap<Resource, Variable>();
549 while(source != null && sourceContext != null) {
550 sourceMap.put(source, sourceContext);
551 source = graph.getPossibleObject(source, L0.PartOf);
552 sourceContext = sourceContext.getParent(graph);
554 return browseSibling(graph, sourceMap, target);
557 private static Variable browseSibling(ReadGraph graph, THashMap<Resource, Variable> sourceMap, Resource target) throws DatabaseException {
558 Layer0 L0 = Layer0.getInstance(graph);
559 Variable result = sourceMap.get(target);
562 String name = (String)graph.getPossibleRelatedValue(target, L0.HasName, Bindings.STRING);
563 Resource parent = graph.getPossibleObject(target, L0.PartOf);
564 if(name == null || parent == null)
566 Variable parentVariable = browseSibling(graph, sourceMap, parent);
567 if(parentVariable == null)
569 return parentVariable.getPossibleChild(graph, name);
573 * Returns the composite where the connection given as a parameter resides.
575 public static Resource getCompositeOfConnection(ReadGraph graph, Resource connection) throws DatabaseException {
576 Layer0 L0 = Layer0.getInstance(graph);
577 StructuralResource2 STR = StructuralResource2.getInstance(graph);
578 // First from connected components
579 for(Resource component : graph.getObjects(connection, STR.Connects))
580 for(Resource composite : graph.getObjects(component, L0.PartOf))
582 // It could be that the connection is only supported by joins (input flag -> output flag) - use diagram info TODO!!
583 Resource connToDiagramConn = graph.getPossibleResource("http://www.simantics.org/Modeling-1.2/ConnectionToDiagramConnection");
584 if(connToDiagramConn != null) {
585 Resource diagramConnection = graph.getPossibleObject(connection, connToDiagramConn);
586 if(diagramConnection != null) {
587 Resource diagram = graph.getPossibleObject(diagramConnection, L0.PartOf);
588 if(diagram != null) {
589 Resource diagramToComposite = graph.getPossibleResource("http://www.simantics.org/Modeling-1.2/DiagramToComposite");
590 if(diagramToComposite != null) {
591 return graph.getPossibleObject(diagram, diagramToComposite);
599 static class Flatten extends BinaryRead<Variable,Resource,Collection<VariableConnectionPointDescriptor>> {
601 public Flatten(Variable parameter1,
602 Resource parameter2) {
603 super(parameter1, parameter2);
607 public Collection<VariableConnectionPointDescriptor> perform(ReadGraph graph)
608 throws DatabaseException {
609 return doFlatten(graph, parameter, parameter2, null);
614 public static Collection<VariableConnectionPointDescriptor> flatten(ReadGraph graph, Variable child, Resource cp, Resource relationType) throws DatabaseException {
616 if(relationType == null) return graph.syncRequest(new Flatten(child, cp));
618 return doFlatten(graph, child, cp, relationType);
622 public static Collection<VariableConnectionPointDescriptor> doFlatten(ReadGraph graph, Variable child, Resource cp, Resource relationType) throws DatabaseException {
624 Set<VariableConnectionPointDescriptor> result = null;
625 Set<VariableConnectionPointDescriptor> needDrill = null;
627 Collection<VariableConnectionPointDescriptor> climbed = climb(graph, child, cp, null);
628 for(VariableConnectionPointDescriptor desc : climbed) {
629 if(!desc.isLeaf(graph)) {
630 if(needDrill == null)
631 needDrill = new THashSet<VariableConnectionPointDescriptor>(climbed.size());
635 result = new THashSet<VariableConnectionPointDescriptor>(climbed.size());
640 if(needDrill == null) {
642 * All descriptors were already flat - just take case of filtering
644 if(relationType != null) {
645 ArrayList<VariableConnectionPointDescriptor> filtered = new ArrayList<VariableConnectionPointDescriptor>(climbed.size());
646 for(VariableConnectionPointDescriptor desc : climbed)
647 if(filterByRelationType(graph, desc, relationType))
657 * There were some descriptors that require drill
659 for(VariableConnectionPointDescriptor top : needDrill) {
660 Collection<VariableConnectionPointDescriptor> drilled = drill(graph, top);
661 if(drilled != null) {
662 for(VariableConnectionPointDescriptor drill : drilled) {
663 if(relationType != null) {
664 if(!filterByRelationType(graph, drill, relationType))
668 result = new THashSet<VariableConnectionPointDescriptor>(climbed.size());
677 private static boolean filterByRelationType(ReadGraph graph, VariableConnectionPointDescriptor desc, Resource relationType) throws DatabaseException {
678 Resource predicateResource = desc.getConnectionPointResource(graph);
679 return predicateResource != null && graph.isInstanceOf(predicateResource, relationType);
682 private static String safeURI(ReadGraph graph, Variable v) {
684 return "null variable";
686 return v.getURI(graph);
687 } catch (DatabaseException e) {