]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.common/src/org/simantics/db/common/utils/CommonDBUtils.java
New implementation NearestOwnerFinder of CommonDBUtils.getNearestOwner
[simantics/platform.git] / bundles / org.simantics.db.common / src / org / simantics / db / common / utils / CommonDBUtils.java
1 package org.simantics.db.common.utils;
2
3 import java.util.ArrayList;
4 import java.util.Collection;
5 import java.util.Collections;
6 import java.util.HashSet;
7 import java.util.Iterator;
8 import java.util.List;
9 import java.util.Set;
10
11 import org.simantics.databoard.Bindings;
12 import org.simantics.db.ReadGraph;
13 import org.simantics.db.Resource;
14 import org.simantics.db.Statement;
15 import org.simantics.db.WriteGraph;
16 import org.simantics.db.common.procedure.adapter.DirectStatementProcedure;
17 import org.simantics.db.common.request.IsParent;
18 import org.simantics.db.common.request.ObjectsWithType;
19 import org.simantics.db.common.request.PossibleObjectWithType;
20 import org.simantics.db.common.request.PossibleOwner;
21 import org.simantics.db.exception.DatabaseException;
22 import org.simantics.db.exception.InvalidResourceReferenceException;
23 import org.simantics.db.service.ClusterUID;
24 import org.simantics.db.service.ClusteringSupport;
25 import org.simantics.db.service.DirectQuerySupport;
26 import org.simantics.db.service.SerialisationSupport;
27 import org.simantics.db.service.XSupport;
28 import org.simantics.layer0.Layer0;
29 import org.simantics.utils.datastructures.collections.CollectionUtils;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 import gnu.trove.list.array.TIntArrayList;
34 import gnu.trove.procedure.TIntProcedure;
35 import gnu.trove.set.hash.THashSet;
36 import gnu.trove.set.hash.TIntHashSet;
37
38 public class CommonDBUtils {
39
40         private static final Logger LOGGER = LoggerFactory.getLogger(CommonDBUtils.class);
41
42         public static boolean isParent(ReadGraph graph, Resource possibleParent, Resource possibleChild) throws DatabaseException {
43                 return graph.sync(new IsParent(possibleParent, possibleChild));
44         }
45         
46         public static Resource parent(ReadGraph graph, Resource child) throws DatabaseException {
47                 return graph.getSingleObject(child, Layer0.getInstance(graph).PartOf);
48         }
49         
50         public static String possibleRelatedString(ReadGraph graph, Resource subject, Resource relation) throws DatabaseException {
51                 return graph.getPossibleRelatedValue(subject, relation, Bindings.STRING);
52         }
53
54         public static Integer possibleRelatedInteger(ReadGraph graph, Resource subject, Resource relation) throws DatabaseException {
55                 return graph.getPossibleRelatedValue(subject, relation, Bindings.INTEGER);
56         }
57
58     public static Resource getPossibleOwner(ReadGraph graph, Resource resource) throws DatabaseException {
59         return graph.syncRequest(new PossibleOwner(resource));
60     }
61     
62     /**
63      * Finds a resource that is reachable from both input resources by as short as possible IsOwnedBy chain
64      */
65     public static Resource commonAncestor(ReadGraph graph, Resource r1, Resource r2) throws DatabaseException {
66         if(r1.equals(r2))
67             return r1;
68         
69         Layer0 L0 = Layer0.getInstance(graph);
70         HashSet<Resource> visited = new HashSet<Resource>();
71         visited.add(r1);
72         visited.add(r2);
73         while(true) {
74             if(r1 != null) {
75                 r1 = graph.getPossibleObject(r1, L0.IsOwnedBy);
76                 if(r1 != null && !visited.add(r1))
77                     return r1;
78             }
79             else if(r2 == null)
80                 return null;
81             if(r2 != null) {
82                 r2 = graph.getPossibleObject(r2, L0.IsOwnedBy);
83                 if(r2 != null && !visited.add(r2))
84                     return r2;
85             }
86         }
87     }
88     
89     private static Collection<Resource> getDirectOwners(ReadGraph graph, Resource resource) throws DatabaseException {
90         // TODO is necessary?
91         if(resource.equals(graph.getRootLibrary()))
92             return Collections.emptyList();
93         
94         Layer0 L0 = Layer0.getInstance(graph);
95         
96         Collection<Resource> owners = graph.getObjects(resource, L0.IsOwnedBy);
97         if(owners.isEmpty()) {
98             owners = new THashSet<Resource>();
99             
100             // If there are no owners, collect resources referring to this resource by IsRelatedTo
101             for(Statement statement : graph.getStatements(resource, L0.IsWeaklyRelatedTo)) {
102                 Resource inverse = graph.getPossibleInverse(statement.getPredicate());
103                 if(inverse != null) {
104                     if(graph.isSubrelationOf(inverse, L0.IsRelatedTo)) {
105                         // Filter away tags
106                         if(resource.equals(statement.getObject()))
107                             continue;
108                         owners.add(statement.getObject());
109                     }
110                 }
111             }
112         }
113         else if(owners.size() > 1) {
114             // TODO: getObjects returns duplicate entries (https://www.simantics.org/redmine/issues/4885) and therefore direct is Set<Resource>.
115             // Fix getObjects to not return duplicate entries
116             owners = new HashSet<Resource>(owners);
117         }
118
119         return owners;
120     }
121     
122     /**
123      * This method didn't have a clear specification and therefore should not be used. Use instead
124      * the methods in the class {@link NearestOwnerFinder}.
125      */
126     @Deprecated
127     public static Resource getNearestOwner(ReadGraph graph, Collection<Resource> resources) throws DatabaseException {
128         if(resources.size() == 1)
129             return NearestOwnerFinder.getNearestOwner(graph, resources.iterator().next());
130         else
131             return NearestOwnerFinder.getNearestOwnerFromDirectOwners(graph, resources);
132     }
133     
134     public static Resource getClusterSetForNewResource(ReadGraph graph, Resource ... resources) throws DatabaseException {
135
136         if(resources.length == 1) return getClusterSetForNewResource(graph, resources[0]);
137         
138         Resource owner = NearestOwnerFinder.getNearestOwnerFromDirectOwners(graph, CollectionUtils.toList(resources));
139         if(owner == null) return null;
140         return getClusterSetForNewResource(graph, owner, new HashSet<Resource>());
141         
142     }
143     
144     public static Resource getClusterSetForNewResource(ReadGraph graph, Collection<Resource> resources) throws DatabaseException {
145
146         if(resources.size() == 1) return getClusterSetForNewResource(graph, resources.iterator().next());
147
148         Resource owner = NearestOwnerFinder.getNearestOwnerFromDirectOwners(graph, resources);
149         return getClusterSetForNewResource(graph, owner, new HashSet<Resource>());
150         
151     }
152     
153     public static Resource getClusterSetForNewResource(ReadGraph graph, Resource resource, Set<Resource> visited) throws DatabaseException {
154         
155         ClusteringSupport cs = graph.getService(ClusteringSupport.class);
156         if(cs.isClusterSet(resource)) return resource;
157         
158         Resource owner = getPossibleOwner(graph, resource);
159         
160         if(owner == null || owner == resource) return null;
161         if(!visited.add(owner)) return null;
162
163         return getClusterSetForNewResource(graph, owner, visited);
164         
165     }
166
167     public static Resource getClusterSetForNewResource(ReadGraph graph, Resource r) throws DatabaseException {
168         return getClusterSetForNewResource(graph, r, new HashSet<Resource>());
169     }
170
171
172     public static void selectClusterSet(WriteGraph graph, Collection<Resource> resources) throws DatabaseException {
173         Resource clusterSet = getClusterSetForNewResource(graph, resources);
174         if(clusterSet == null) clusterSet = graph.getRootLibrary();
175         graph.setClusterSet4NewResource(clusterSet);
176     }
177
178     public static void selectClusterSet(WriteGraph graph, Resource ... resources) throws DatabaseException {
179         Resource clusterSet = getClusterSetForNewResource(graph, resources);
180         if(clusterSet == null) clusterSet = graph.getRootLibrary();
181         graph.setClusterSet4NewResource(clusterSet);
182     }
183     
184     public static void selectClusterSet(WriteGraph graph, Resource resource) throws DatabaseException {
185         Resource clusterSet = getClusterSetForNewResource(graph, resource);
186         if(clusterSet == null) clusterSet = graph.getRootLibrary();
187         graph.setClusterSet4NewResource(clusterSet);
188     }
189     
190     public static List<Resource> objectsWithType(ReadGraph graph, Resource subject, Resource relation, Resource type) throws DatabaseException {
191         return new ArrayList<Resource>(graph.syncRequest(new ObjectsWithType(subject, relation, type)));
192     }
193
194     public static Resource possibleObjectWithType(ReadGraph graph, Resource subject, Resource relation, Resource type) throws DatabaseException {
195         return graph.syncRequest(new PossibleObjectWithType(subject, relation, type));
196     }
197
198         public static List<ClusterUID> listClusters(ReadGraph graph) throws DatabaseException {
199         XSupport xs = graph.getService(XSupport.class);
200         ClusterUID uids[] = xs.listClusters();
201         ArrayList<ClusterUID> result = new ArrayList<>(uids.length);
202         for(ClusterUID uid : uids) result.add(uid);
203         return result;
204     }
205         
206         public static List<Resource> resourcesByCluster(ReadGraph graph, ClusterUID uid) throws DatabaseException {
207         SerialisationSupport ss = graph.getService(SerialisationSupport.class);
208         ArrayList<Resource> result = new ArrayList<Resource>();
209         // Index 0 is illegal
210                 for(int i=1;i<1<<12;i++) {
211                         try {
212                                 result.add(ss.getResource(uid.toRID(i)));
213                         } catch (InvalidResourceReferenceException e) {
214                         }
215                 }
216                 return result;
217         }
218         
219         public static List<Statement> directStatements(ReadGraph graph, Resource resource, boolean ignoreVirtual) throws DatabaseException {
220                 
221                 DirectQuerySupport dqs = graph.getService(DirectQuerySupport.class);
222                 DirectStatementProcedure proc = new DirectStatementProcedure();
223
224                 if (ignoreVirtual) {
225                         return dqs.getDirectPersistentStatements(graph, resource);
226                 } else {
227                         return dqs.getDirectStatements(graph, resource);
228                 }
229
230         }
231         
232     public static List<Resource> garbageResources(ReadGraph graph) throws DatabaseException {
233         
234         SerialisationSupport ss = graph.getService(SerialisationSupport.class);
235         
236         TIntArrayList refs = new TIntArrayList();
237         TIntArrayList res = new TIntArrayList();
238         
239         // Find all statements in the database
240         for(ClusterUID uid : listClusters(graph)) {
241                 for(Resource r : resourcesByCluster(graph, uid)) {
242                         int sid = ss.getTransientId(r);
243                         for(Statement stm : directStatements(graph, r, true)) {
244                                 int oid = ss.getTransientId(stm.getObject());
245                                 refs.add(sid);
246                                 refs.add(oid);
247                         }
248                         res.add(sid);
249                 }
250         }
251
252         TIntHashSet reached = new TIntHashSet();
253         
254         // Initialize root
255         int root = ss.getTransientId(graph.getRootLibrary());
256         reached.add(root);
257         
258         int[] refArray = refs.toArray();
259         
260         boolean changes = true;
261         
262         while(changes) {
263                 changes = false;
264                 for(int i=0;i<refArray.length;i+=2) {
265                         int s = refArray[i];
266                         int o = refArray[i+1];
267                         if(reached.contains(s)) {
268                                 if(reached.add(o)) {
269                                         changes = true;
270                                 }
271                         }
272                 }
273                 
274                 System.err.println("Reachability iteration, changes = " + changes);
275         }
276         
277         ArrayList<Resource> result = new ArrayList<>();
278                 for(int i=0;i<refArray.length;i+=2) {
279                         int s = refArray[i];
280                         if(reached.contains(s)) {
281                                 if(reached.add(refArray[i+1]))
282                                         changes = true;
283                         }
284                 }
285
286                 res.forEach(new TIntProcedure() {
287                         
288                         @Override
289                         public boolean execute(int r) {
290                                 if(!reached.contains(r)) {
291                                         try {
292                                                 result.add(ss.getResource(r));
293                                         } catch (DatabaseException e) {
294                                                 LOGGER.error("Unexpected error while resolving garbage resources.", e);
295                                         }
296                                 }
297                                 return true;
298                         }
299                         
300                 });
301                 
302         return result;
303         
304     }
305
306     public static ClusterUID clusterUIDOfResource(ReadGraph graph, Resource resource) throws DatabaseException {
307         SerialisationSupport ss = graph.getService(SerialisationSupport.class);
308         return ss.getUID(resource).asCID();
309     }
310     
311     public static boolean isClusterLoaded(ReadGraph graph, ClusterUID clusterUID) throws DatabaseException {
312         XSupport xs = graph.getService(XSupport.class);
313         return xs.isClusterLoaded(clusterUID);
314     }
315     
316     
317 }