1 package org.simantics.db.common.request;
3 import gnu.trove.map.hash.THashMap;
5 import java.util.ArrayList;
6 import java.util.Collections;
11 import org.simantics.db.ReadGraph;
12 import org.simantics.db.Resource;
13 import org.simantics.db.ResourceSet;
14 import org.simantics.db.exception.DatabaseException;
15 import org.simantics.db.service.CollectionSupport;
17 public class ResourceSetGraph {
19 final public CollectionSupport coll;
20 final public List<ResourceSetGraph> references;
21 final public Resource resource;
22 final public Map<ResourceSet,Set<Resource>> cache = new THashMap<ResourceSet,Set<Resource>>();
24 public ResourceSetGraph(ReadGraph graph, Resource result) {
25 this.resource = result;
26 this.references = new ArrayList<ResourceSetGraph>();
27 this.coll = graph.getService(CollectionSupport.class);
30 private Set<Resource> probe(ReadGraph graph, ResourceSet types) {
31 return cache.get(types);
34 private Set<Resource> resolve(ReadGraph graph, ResourceSet types, Set<Resource> visited) throws DatabaseException {
37 if(!visited.add(this.resource)) return Collections.emptySet();
39 Set<Resource> cached = cache.get(types);
40 if(cached != null) return cached;
42 boolean includeThis = !types.disjoint(graph.getTypes(this.resource));
44 Set<Resource> allRefs = null;
45 for(ResourceSetGraph ref : references) {
46 Set<Resource> refs = ref.probe(graph, types);
49 visited = coll.createSet();
50 visited.add(this.resource);
52 refs = ref.resolve(graph, types, visited);
55 if(allRefs == null) allRefs = coll.createSet(refs.size());
60 Set<Resource> result = Collections.emptySet();
62 if(allRefs.size() == 1) {
64 allRefs.add(resource);
65 if(allRefs.size() == 1) result = Collections.singleton(allRefs.iterator().next());
66 else result = allRefs;
68 result = Collections.singleton(allRefs.iterator().next());
71 if(includeThis) allRefs.add(resource);
75 if(includeThis) result = Collections.singleton(resource);
78 cache.put(types, result);
84 public Set<Resource> resolve(ReadGraph graph, ResourceSet types) throws DatabaseException {
85 Set<Resource> result = resolve(graph, types, null);
86 if(result == null) result = Collections.emptySet();