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.NameUtils;
21 import org.simantics.db.common.utils.NearestOwnerFinder;
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;
39 import gnu.trove.map.hash.THashMap;
40 import gnu.trove.set.hash.THashSet;
42 public class ConnectionBrowser {
45 * Finds the components connected by the connection. Also connections
49 * @param connection A connection whose related modules are searched.
50 * @param configuration A variable that represents the composite where the connection belongs to.
51 * @return A map whose keys are components and they are mapped to
54 public static Collection<ResourceWithContext> findConnectedComponents(
55 ReadGraph graph, Resource connection, Variable configuration)
56 throws DatabaseException {
58 ArrayList<ResourceWithContext> result =
59 new ArrayList<ResourceWithContext>();
60 THashSet<Resource> visitedConnections = new THashSet<Resource>();
63 findConnectedComponents(graph, connection, configuration, result,
68 private static void findConnectedComponents(
69 ReadGraph graph, Resource connection, Variable configuration,
70 ArrayList<ResourceWithContext> result,
71 THashSet<Resource> visitedConnections) throws DatabaseException {
72 if(visitedConnections.add(connection)) {
73 StructuralResource2 STR = StructuralResource2.getInstance(graph);
74 Layer0 L0 = Layer0.getInstance(graph);
76 // Browse related components
77 for(Statement stat : graph.getStatements(connection, STR.Connects)) {
78 Resource component = stat.getObject();
79 Resource relation = graph.getInverse(stat.getPredicate());
80 //System.out.println(NameUtils.getSafeName(graph, component) + "." + NameUtils.getSafeName(graph, relation));
81 Resource boundConnection = graph.getPossibleObject(relation, STR.IsBoundBy);
82 Resource type = StructuralUtils.getPossibleComponentType(graph, configuration, component);
83 Resource def = type != null ? graph.getPossibleObject(type, STR.IsDefinedBy) : null;
84 if(boundConnection != null && def != null) {
85 // The connection point is bound in component type
86 Variable newContext = configuration.browsePossible(graph, component);
87 Resource newComposite = getCompositeOfConnection(graph, boundConnection);
88 if(newContext != null && newComposite != null) {
89 newContext = browse(graph, def, newContext, newComposite);
90 if (newContext != null)
91 findConnectedComponents(graph, boundConnection,
93 result, visitedConnections);
97 //System.out.println("added result");
98 // A primitive connection point
99 Variable context = configuration.browsePossible(graph, component);
101 result.add(new ResourceWithContext(component, context));
105 // Browse over connection joins
106 for(Resource join : graph.getObjects(connection, STR.IsJoinedBy))
107 for(Resource otherConnection : graph.getObjects(join, STR.Joins))
108 if(!connection.equals(otherConnection)) {
109 Resource sourceComposite = getCompositeOfConnection(graph, connection);
110 Resource targetComposite = getCompositeOfConnection(graph, otherConnection);
111 if (sourceComposite != null && targetComposite != null) {
112 Variable sibling = browseSibling(graph,
117 findConnectedComponents(graph, otherConnection,
118 sibling, result, visitedConnections);
124 for(Resource relation : graph.getObjects(connection, STR.Binds)) {
125 Resource composite = getCompositeOfConnection(graph, connection);
126 if (composite == null)
129 Variable curConfiguration = configuration;
130 while(!graph.hasStatement(composite, STR.Defines)) {
131 composite = graph.getSingleObject(composite, L0.PartOf);
132 curConfiguration = curConfiguration.getParent(graph);
134 Variable parent = curConfiguration.getParent(graph);
135 Resource component = curConfiguration.getRepresents(graph);
136 for(Resource c : graph.getObjects(component, relation))
137 findConnectedComponents(graph, c,
138 parent, result, visitedConnections);
140 } catch(NoSingleResultException e) {
141 } catch(MissingVariableException e) {
142 } catch(MissingVariableValueException e) {
147 public static Collection<VariableConnectionPointDescriptor> drill(ReadGraph graph, VariableConnectionPointDescriptor pair) throws DatabaseException {
149 Collection<InterfaceResolution> interfaceDescription = pair.getInterfaceDescription(graph);
150 if(interfaceDescription != null && interfaceDescription.size() > 0) {
152 Variable cp = pair.getVariable(graph);
153 Variable context = cp.getParent(graph);
154 String cpName = cp.getName(graph);
156 Collection<VariableConnectionPointDescriptor> result = new ArrayList<VariableConnectionPointDescriptor>();
157 for(InterfaceResolution r : interfaceDescription) {
158 if(r.interfaceName.equals(cpName)) {
159 String path = Functions.resolveInterfacePath(graph, context, r.componentName, r.connectionPoint);
160 result.add(new BrowseConnectionDescriptor(context, path));
164 if(result.isEmpty()) return null;
169 return Collections.singleton(pair);
174 public static class JoinConnections extends ResourceRead<Collection<Resource>> {
176 public JoinConnections(Resource join) {
181 public Collection<Resource> perform(ReadGraph graph) throws DatabaseException {
182 ConnectionSet cs = new ConnectionSet(graph);
183 cs.addJoin(graph, resource);
184 return cs.getConnections();
190 public static final class VariableChildren extends TransientUnaryRead<Variable, Map<Resource,Variable>> {
192 public VariableChildren(ReadGraph graph, Variable variable) throws DatabaseException {
193 super(graph, variable);
196 public VariableChildren(ReadGraph graph, QueryControl qc, Variable variable) throws DatabaseException {
197 super(graph, qc, variable);
201 public Map<Resource, Variable> perform(ReadGraph graph, Variable parameter) throws DatabaseException {
202 CollectionSupport cs = graph.getService(CollectionSupport.class);
203 Map<Resource,Variable> result = cs.createMap(Variable.class);
204 for(Variable child : parameter.getChildren(graph)) {
205 Resource represents = child.getPossibleRepresents(graph);
206 if(represents != null) result.put(represents, child);
213 static Variable resolve(ReadGraph graph, Variable base, Resource component) throws DatabaseException {
214 Map<Resource,Variable> map = graph.syncRequest(new VariableChildren(graph, base), TransientCacheAsyncListener.<Map<Resource,Variable>>instance());
215 Variable result = map.get(component);
216 if(result != null) return result;
218 Layer0 L0 = Layer0.getInstance(graph);
219 Resource parent = graph.getPossibleObject(component, L0.PartOf);
220 if(parent == null) return null;
221 Variable v = resolve(graph, base, parent);
222 if (v == null) return null;
223 map = graph.syncRequest(new VariableChildren(graph, v), TransientCacheAsyncListener.<Map<Resource,Variable>>instance());
224 return map.get(component);
228 public static class ConnectionComponentsWithAncestor extends TransientUnaryRead<Resource, List<Resource>> {
230 final private List<Resource> result;
232 public ConnectionComponentsWithAncestor(ReadGraph graph, Resource conn) throws DatabaseException {
233 this(graph, conn, null);
236 public ConnectionComponentsWithAncestor(ReadGraph graph, QueryControl qc, Resource conn, List<Resource> result) throws DatabaseException {
237 super(graph, qc, conn);
238 this.result = result;
241 public ConnectionComponentsWithAncestor(ReadGraph graph, Resource conn, List<Resource> result) throws DatabaseException {
243 this.result = result;
246 private ConnectionSet connSet(ReadGraph graph, Resource r ) throws DatabaseException {
247 ConnectionSet cs = new ConnectionSet(graph);
248 cs.addConnection(graph, r);
253 public List<Resource> perform(ReadGraph graph, Resource resource) throws DatabaseException {
255 if(result != null) return result;
257 Layer0 L0 = Layer0.getInstance(graph);
258 StructuralResource2 STR = StructuralResource2.getInstance(graph);
259 CollectionSupport colls = graph.getService(CollectionSupport.class);
260 THashSet<Resource> ancestorGenerators = new THashSet<Resource>();
261 Set<Resource> parts = colls.createSet();
262 ConnectionSet cs = connSet(graph, resource);
263 for(Resource connRes : cs.getConnections()) {
264 for(Statement stm : graph.getStatements(connRes, STR.Connects)) {
265 Resource component = stm.getObject();
266 Resource parent = graph.getPossibleObject(component, L0.PartOf);
267 if(parent != null && !graph.isInstanceOf(component, ModelingResources.getInstance(graph).ReferenceElement))
268 ancestorGenerators.add(parent);
272 for (Resource join : cs.getJoins()) {
274 for (Resource composite : graph.getObjects(join, STR.JoinsComposite))
275 ancestorGenerators.add(composite);
277 Resource ancestor = ancestorGenerators.size() == 1 ? ancestorGenerators.iterator().next() : NearestOwnerFinder.getNearestOwnerFromDirectOwners(graph, ancestorGenerators);
279 List<Resource> result = colls.createList();
280 result.add(ancestor);
281 result.addAll(colls.asSortedList(parts));
283 if(parameter != WITH_PARENT) {
284 for(int i=1;i<result.size();i++) {
285 Resource r = result.get(i);
287 if(!r.equals(resource))
288 graph.syncRequest(new ConnectionComponentsWithAncestor(graph, r, result), TransientCacheAsyncListener.<List<Resource>>instance());
298 public static Collection<VariableConnectionPointDescriptor> climb(ReadGraph graph, Variable child, Resource cp, String subPath_) throws DatabaseException {
300 boolean isStructural = false;
302 Variable curConfiguration = child.getParent(graph);
306 Collection<InterfaceResolution> interfaceDescription = Functions.computeInterfacePaths(graph, curConfiguration);
307 if(interfaceDescription != null) {
308 isStructural = interfaceDescription != Functions.BUILTIN_STRUCTURAL_CPS;
309 if(interfaceDescription.size() > 0) {
311 if(subPath_ == null) {
313 String childName = child.getName(graph);
314 for(InterfaceResolution r : interfaceDescription) {
315 if(r.componentName.equals(childName) && r.connectionPoint.equals(cp)) {
316 Variable pConn = curConfiguration.getPossibleProperty(graph, r.interfaceName);
318 Resource cp2 = pConn.getPossiblePredicateResource(graph);
319 Collection<VariableConnectionPointDescriptor> res = climb(graph, curConfiguration, cp2, null);
320 if(res != null) return res;
322 return Collections.emptyList();
327 throw new UnsupportedOperationException("");
334 if(child instanceof StandardProceduralChildVariable) {
336 Variable conn = child.getPossibleProperty(graph, cp);
337 FixedConnection fc = (FixedConnection)conn.getValue(graph);
338 Set<VariableConnectionPointDescriptor> result = new THashSet<VariableConnectionPointDescriptor>(1+fc.size());
339 result.add(new ComponentConnectionDescriptor(child, cp));
340 fc.addConnectionDescriptors(graph, curConfiguration, result);
346 Resource represents = child.getRepresents(graph);
350 Collection<Resource> conns = graph.getObjects(represents, res);
351 HashSet<VariableConnectionPointDescriptor> result = new HashSet<VariableConnectionPointDescriptor>();
352 for(Resource c : conns) {
353 List<Resource> rs = graph.syncRequest(new ConnectionComponentsWithAncestor(graph, c), TransientCacheAsyncListener.<List<Resource>>instance());
354 result.addAll(graph.syncRequest(ConnectionVariables.forStructural(graph, curConfiguration, rs)));
360 Resource connection = graph.getPossibleObject(represents, res);
361 if(connection != null) {
362 List<Resource> rs = graph.syncRequest(new ConnectionComponentsWithAncestor(graph, connection), TransientCacheAsyncListener.<List<Resource>>instance());
363 return graph.syncRequest(ConnectionVariables.forConfiguration(graph, curConfiguration, rs));
366 Collection<Resource> conns = graph.getObjects(represents, res);
367 HashSet<VariableConnectionPointDescriptor> result = new HashSet<VariableConnectionPointDescriptor>();
368 for(Resource c : conns) {
369 List<Resource> rs = graph.syncRequest(new ConnectionComponentsWithAncestor(graph, c), TransientCacheAsyncListener.<List<Resource>>instance());
370 result.addAll(graph.syncRequest(ConnectionVariables.forConfiguration(graph, curConfiguration, rs)));
381 public static void reportDescriptor(ReadGraph graph, VariableConnectionPointDescriptor d) throws DatabaseException {
383 if(d instanceof ActualConnectionDescriptor) {
384 ActualConnectionDescriptor d2 = (ActualConnectionDescriptor)d;
386 System.err.println("--ActualConnectionPointDescriptor2");
387 System.err.println("---root: " + d2.root.getURI(graph));
388 System.err.println("---component: " + graph.getPossibleURI(d2.component));
389 System.err.println("---type: " + graph.getPossibleURI(d2.componentType));
390 System.err.println("---cp: " + graph.getPossibleURI(d2.cp));
391 System.err.println("---var: " + d2.getVariable(graph).getURI(graph));
396 public static class ConnectionVariables extends BinaryRead<Variable, List<Resource>, Collection<VariableConnectionPointDescriptor>> {
398 private ConnectionVariables(Variable parameter1, List<Resource> parameter2) {
399 super(parameter1, parameter2);
402 public static ConnectionVariables forConfiguration(ReadGraph graph, Variable configuration, List<Resource> rs) throws DatabaseException {
403 return new ConnectionVariables(parent(graph, configuration, rs.get(0)), rs);
406 public static ConnectionVariables forStructural(ReadGraph graph, Variable configuration, List<Resource> rs) throws DatabaseException {
407 return new ConnectionVariables(configuration, rs);
411 * Finds the parent variable of <code>configuration</code> that
412 * represents <code>ancestor</code>.
415 * @param configuration
418 * @throws DatabaseException if no parent was found that represents ancestor
420 private static Variable parent(ReadGraph graph, Variable configuration, Resource ancestor) throws DatabaseException {
421 Variable v = configuration;
422 Resource represents = v.getRepresents(graph);
423 while(!represents.equals(ancestor)) {
424 v = v.getParent(graph);
426 throw new DatabaseException(
427 "parent representing ancestor not found for variable, configuration="
428 + safeURI(graph, configuration)
430 + NameUtils.getURIOrSafeNameInternal(graph, ancestor));
432 represents = v.getRepresents(graph);
438 public Collection<VariableConnectionPointDescriptor> perform(ReadGraph graph) throws DatabaseException {
439 if(parameter == null) return Collections.emptyList();
440 Layer0 L0 = Layer0.getInstance(graph);
441 StructuralResource2 STR = StructuralResource2.getInstance(graph);
442 ArrayList<VariableConnectionPointDescriptor> result = null;
443 for(int i=1;i<parameter2.size();i++) {
444 Resource connRes = parameter2.get(i);
445 for(Statement stm : graph.getStatements(connRes, STR.Connects)) {
446 Resource component = stm.getObject();
447 Resource connectionPoint = graph.getInverse(stm.getPredicate());
448 if(result == null) result = new ArrayList<VariableConnectionPointDescriptor>();
449 String componentName = graph.getRelatedValue(component, L0.HasName, Bindings.STRING);
450 Variable possibleChild = parameter.getPossibleChild(graph, componentName);
451 if(possibleChild != null) {
452 Resource type = possibleChild.getPossibleType(graph, STR.Component);
454 result.add(new ActualConnectionDescriptor(parameter, component, possibleChild.getType(graph), connectionPoint));
456 throw new DatabaseException("Child does not have a structural type: " + possibleChild.getURI(graph));
459 Resource type = graph.getPossibleType(component, STR.Component);
461 result.add(new ActualConnectionDescriptor(parameter, component, type, connectionPoint));
463 throw new DatabaseException("Child with name " + componentName + " does not have a structural type: " + parameter.getURI(graph));
468 if(result == null) return Collections.emptyList();
474 static class IsLeafType extends ResourceRead<Boolean> {
476 protected IsLeafType(Resource type) {
481 public Boolean perform(ReadGraph graph) throws DatabaseException {
483 StructuralComponentClass clazz = StructuralComponentClass.get(graph, resource);
484 return StructuralComponentClass.PRIMITIVE.equals(clazz);
490 static class ChildMapOfVariable extends VariableRead<Map<Resource,Variable>> {
492 public ChildMapOfVariable(Variable variable) {
497 public Map<Resource, Variable> perform(ReadGraph graph) throws DatabaseException {
498 HashMap<Resource,Variable> result = new HashMap<Resource,Variable>();
499 for(Variable child : variable.getChildren(graph)) {
500 Resource represents = child.getPossibleRepresents(graph);
501 if(represents != null) result.put(represents, child);
509 * Given a root composite, related variable and some other component inside the composite,
510 * finds the related variable for that component.
512 public static Variable browse(ReadGraph graph, Resource root, Variable rootContext, Resource target) throws DatabaseException {
513 if(target.equals(root))
516 Layer0 L0 = Layer0.getInstance(graph);
517 String name = (String)graph.getPossibleRelatedValue(target, L0.HasName, Bindings.STRING);
518 Resource parent = graph.getPossibleObject(target, L0.PartOf);
519 if(name == null || parent == null)
521 Variable parentVariable = browse(graph, root, rootContext, parent);
522 if(parentVariable == null)
524 return parentVariable.getPossibleChild(graph, name);
529 * Finds a variable whose location related to sourceContext is the same as
530 * between target and source. In other words, the method solves {@code targetContext}
531 * in the following equations:
533 * URI(source) = resourceURIBase + sourceSuffix
534 * URI(sourceContext) = variableURIBase + sourceSuffix
535 * URI(target) = resourceURIBase + targetSuffix
536 * URI(targetContext) = variableURIBase + targetSuffix
539 public static Variable browseSibling(ReadGraph graph, Resource source, Variable sourceContext, Resource target) throws DatabaseException {
540 Layer0 L0 = Layer0.getInstance(graph);
541 THashMap<Resource, Variable> sourceMap = new THashMap<Resource, Variable>();
542 while(source != null && sourceContext != null) {
543 sourceMap.put(source, sourceContext);
544 source = graph.getPossibleObject(source, L0.PartOf);
545 sourceContext = sourceContext.getParent(graph);
547 return browseSibling(graph, sourceMap, target);
550 private static Variable browseSibling(ReadGraph graph, THashMap<Resource, Variable> sourceMap, Resource target) throws DatabaseException {
551 Layer0 L0 = Layer0.getInstance(graph);
552 Variable result = sourceMap.get(target);
555 String name = (String)graph.getPossibleRelatedValue(target, L0.HasName, Bindings.STRING);
556 Resource parent = graph.getPossibleObject(target, L0.PartOf);
557 if(name == null || parent == null)
559 Variable parentVariable = browseSibling(graph, sourceMap, parent);
560 if(parentVariable == null)
562 return parentVariable.getPossibleChild(graph, name);
566 * Returns the composite where the connection given as a parameter resides.
568 public static Resource getCompositeOfConnection(ReadGraph graph, Resource connection) throws DatabaseException {
569 Layer0 L0 = Layer0.getInstance(graph);
570 StructuralResource2 STR = StructuralResource2.getInstance(graph);
571 // First from connected components
572 for(Resource component : graph.getObjects(connection, STR.Connects))
573 for(Resource composite : graph.getObjects(component, L0.PartOf))
575 // It could be that the connection is only supported by joins (input flag -> output flag) - use diagram info TODO!!
576 Resource connToDiagramConn = graph.getPossibleResource("http://www.simantics.org/Modeling-1.2/ConnectionToDiagramConnection");
577 if(connToDiagramConn != null) {
578 Resource diagramConnection = graph.getPossibleObject(connection, connToDiagramConn);
579 if(diagramConnection != null) {
580 Resource diagram = graph.getPossibleObject(diagramConnection, L0.PartOf);
581 if(diagram != null) {
582 Resource diagramToComposite = graph.getPossibleResource("http://www.simantics.org/Modeling-1.2/DiagramToComposite");
583 if(diagramToComposite != null) {
584 return graph.getPossibleObject(diagram, diagramToComposite);
592 static class Flatten extends BinaryRead<Variable,Resource,Collection<VariableConnectionPointDescriptor>> {
594 public Flatten(Variable parameter1,
595 Resource parameter2) {
596 super(parameter1, parameter2);
600 public Collection<VariableConnectionPointDescriptor> perform(ReadGraph graph)
601 throws DatabaseException {
602 return doFlatten(graph, parameter, parameter2, null);
607 public static Collection<VariableConnectionPointDescriptor> flatten(ReadGraph graph, Variable child, Resource cp, Resource relationType) throws DatabaseException {
609 if(relationType == null) return graph.syncRequest(new Flatten(child, cp));
611 return doFlatten(graph, child, cp, relationType);
615 public static Collection<VariableConnectionPointDescriptor> doFlatten(ReadGraph graph, Variable child, Resource cp, Resource relationType) throws DatabaseException {
617 Set<VariableConnectionPointDescriptor> result = null;
618 Set<VariableConnectionPointDescriptor> needDrill = null;
620 Collection<VariableConnectionPointDescriptor> climbed = climb(graph, child, cp, null);
621 for(VariableConnectionPointDescriptor desc : climbed) {
622 if(!desc.isLeaf(graph)) {
623 if(needDrill == null)
624 needDrill = new THashSet<VariableConnectionPointDescriptor>(climbed.size());
628 result = new THashSet<VariableConnectionPointDescriptor>(climbed.size());
633 if(needDrill == null) {
635 * All descriptors were already flat - just take case of filtering
637 if(relationType != null) {
638 ArrayList<VariableConnectionPointDescriptor> filtered = new ArrayList<VariableConnectionPointDescriptor>(climbed.size());
639 for(VariableConnectionPointDescriptor desc : climbed)
640 if(filterByRelationType(graph, desc, relationType))
650 * There were some descriptors that require drill
652 for(VariableConnectionPointDescriptor top : needDrill) {
653 Collection<VariableConnectionPointDescriptor> drilled = drill(graph, top);
654 if(drilled != null) {
655 for(VariableConnectionPointDescriptor drill : drilled) {
656 if(relationType != null) {
657 if(!filterByRelationType(graph, drill, relationType))
661 result = new THashSet<VariableConnectionPointDescriptor>(climbed.size());
670 private static boolean filterByRelationType(ReadGraph graph, VariableConnectionPointDescriptor desc, Resource relationType) throws DatabaseException {
671 Resource predicateResource = desc.getConnectionPointResource(graph);
672 return predicateResource != null && graph.isInstanceOf(predicateResource, relationType);
675 private static String safeURI(ReadGraph graph, Variable v) {
677 return "null variable";
679 return v.getURI(graph);
680 } catch (DatabaseException e) {