1 package org.simantics.db.common.utils;
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;
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;
33 import gnu.trove.list.array.TIntArrayList;
34 import gnu.trove.procedure.TIntProcedure;
35 import gnu.trove.set.hash.TIntHashSet;
37 public class CommonDBUtils {
39 private static final Logger LOGGER = LoggerFactory.getLogger(CommonDBUtils.class);
41 public static boolean isParent(ReadGraph graph, Resource possibleParent, Resource possibleChild) throws DatabaseException {
42 return graph.sync(new IsParent(possibleParent, possibleChild));
45 public static Resource parent(ReadGraph graph, Resource child) throws DatabaseException {
46 return graph.getSingleObject(child, Layer0.getInstance(graph).PartOf);
49 public static String possibleRelatedString(ReadGraph graph, Resource subject, Resource relation) throws DatabaseException {
50 return graph.getPossibleRelatedValue(subject, relation, Bindings.STRING);
53 public static Integer possibleRelatedInteger(ReadGraph graph, Resource subject, Resource relation) throws DatabaseException {
54 return graph.getPossibleRelatedValue(subject, relation, Bindings.INTEGER);
57 public static Resource getPossibleOwner(ReadGraph graph, Resource resource) throws DatabaseException {
58 return graph.syncRequest(new PossibleOwner(resource));
61 public static Resource commonAncestor(ReadGraph graph, Resource r1, Resource r2) throws DatabaseException {
62 Layer0 L0 = Layer0.getInstance(graph);
63 if(r1.equals(r2)) return r1;
64 HashSet<Resource> visited = new HashSet<Resource>();
69 r1 = graph.getPossibleObject(r1, L0.IsOwnedBy);
71 if(!visited.add(r1)) return r1;
73 else if(r2 == null) return null;
75 r2 = graph.getPossibleObject(r2, L0.IsOwnedBy);
77 if(!visited.add(r2)) return r2;
82 public static Resource getNearestOwner(ReadGraph graph, Collection<Resource> resources) throws DatabaseException {
84 Layer0 L0 = Layer0.getInstance(graph);
87 Set<Resource> direct = new HashSet<Resource>();
88 Set<Resource> owners = new HashSet<Resource>();
90 for(Resource r : resources) {
92 Collection<Resource> objects = graph.getObjects(r, L0.IsOwnedBy);
94 // TODO: getObjects returns duplicate entries (https://www.simantics.org/redmine/issues/4885) and therefore direct is Set<Resource>. Fix getObjects to not return duplicate entries
95 if (objects.size() > 1) objects = new HashSet<Resource>(objects);
97 if (objects.size() == 1)
98 direct.addAll(objects);
99 else if (objects.isEmpty()) {
100 for(Statement stm : graph.getStatements(r, L0.IsWeaklyRelatedTo)) {
101 Resource inverse = graph.getPossibleInverse(stm.getPredicate());
102 if(inverse != null) {
103 if(graph.isSubrelationOf(inverse, L0.IsRelatedTo)) {
105 if(!r.equals(stm.getObject()))
106 owners.add(stm.getObject());
111 System.err.println("Multiple owners for " + graph.getPossibleURI(r) + " id : " + r);
112 for (Resource r2 : objects)
113 System.err.println("owner : " + graph.getPossibleURI(r2) + " id " + r2);
118 if(!direct.isEmpty()) {
119 Iterator<Resource> iter = direct.iterator();
120 Resource common = iter.next();
121 while (iter.hasNext()) {
122 Resource other = iter.next();
123 common = commonAncestor(graph, common, other);
124 if (common == null) break;
130 if(!Collections.disjoint(owners, resources)) {
131 System.err.println("Overlapping owners:");
132 for(Resource r : resources)
133 System.err.println("-resource " + NameUtils.getSafeName(graph, r, true));
134 for(Resource r : owners)
135 System.err.println("-owner " + NameUtils.getSafeName(graph, r, true));
139 if(owners.size() == 1) return owners.iterator().next();
140 if(owners.size() == 0) return null;
142 return getNearestOwner(graph, owners);
146 public static Resource getClusterSetForNewResource(ReadGraph graph, Resource ... resources) throws DatabaseException {
148 if(resources.length == 1) return getClusterSetForNewResource(graph, resources[0]);
150 Resource owner = getNearestOwner(graph, CollectionUtils.toList(resources));
151 if(owner == null) return null;
152 return getClusterSetForNewResource(graph, owner, new HashSet<Resource>());
156 public static Resource getClusterSetForNewResource(ReadGraph graph, Collection<Resource> resources) throws DatabaseException {
158 if(resources.size() == 1) return getClusterSetForNewResource(graph, resources.iterator().next());
160 Resource owner = getNearestOwner(graph, resources);
161 return getClusterSetForNewResource(graph, owner, new HashSet<Resource>());
165 public static Resource getClusterSetForNewResource(ReadGraph graph, Resource resource, Set<Resource> visited) throws DatabaseException {
167 ClusteringSupport cs = graph.getService(ClusteringSupport.class);
168 if(cs.isClusterSet(resource)) return resource;
170 Resource owner = getPossibleOwner(graph, resource);
172 if(owner == null || owner == resource) return null;
173 if(!visited.add(owner)) return null;
175 return getClusterSetForNewResource(graph, owner, visited);
179 public static Resource getClusterSetForNewResource(ReadGraph graph, Resource r) throws DatabaseException {
180 return getClusterSetForNewResource(graph, r, new HashSet<Resource>());
184 public static void selectClusterSet(WriteGraph graph, Collection<Resource> resources) throws DatabaseException {
185 Resource clusterSet = getClusterSetForNewResource(graph, resources);
186 if(clusterSet == null) clusterSet = graph.getRootLibrary();
187 graph.setClusterSet4NewResource(clusterSet);
190 public static void selectClusterSet(WriteGraph graph, Resource ... resources) throws DatabaseException {
191 Resource clusterSet = getClusterSetForNewResource(graph, resources);
192 if(clusterSet == null) clusterSet = graph.getRootLibrary();
193 graph.setClusterSet4NewResource(clusterSet);
196 public static void selectClusterSet(WriteGraph graph, Resource resource) throws DatabaseException {
197 Resource clusterSet = getClusterSetForNewResource(graph, resource);
198 if(clusterSet == null) clusterSet = graph.getRootLibrary();
199 graph.setClusterSet4NewResource(clusterSet);
202 public static List<Resource> objectsWithType(ReadGraph graph, Resource subject, Resource relation, Resource type) throws DatabaseException {
203 return new ArrayList<Resource>(graph.syncRequest(new ObjectsWithType(subject, relation, type)));
206 public static Resource possibleObjectWithType(ReadGraph graph, Resource subject, Resource relation, Resource type) throws DatabaseException {
207 return graph.syncRequest(new PossibleObjectWithType(subject, relation, type));
210 public static List<ClusterUID> listClusters(ReadGraph graph) throws DatabaseException {
211 XSupport xs = graph.getService(XSupport.class);
212 ClusterUID uids[] = xs.listClusters();
213 ArrayList<ClusterUID> result = new ArrayList<>(uids.length);
214 for(ClusterUID uid : uids) result.add(uid);
218 public static List<Resource> resourcesByCluster(ReadGraph graph, ClusterUID uid) throws DatabaseException {
219 SerialisationSupport ss = graph.getService(SerialisationSupport.class);
220 ArrayList<Resource> result = new ArrayList<Resource>();
221 // Index 0 is illegal
222 for(int i=1;i<1<<12;i++) {
224 result.add(ss.getResource(uid.toRID(i)));
225 } catch (InvalidResourceReferenceException e) {
231 public static List<Statement> directStatements(ReadGraph graph, Resource resource, boolean ignoreVirtual) throws DatabaseException {
233 DirectQuerySupport dqs = graph.getService(DirectQuerySupport.class);
234 DirectStatementProcedure proc = new DirectStatementProcedure();
237 dqs.forEachDirectPersistentStatement(graph, resource, proc);
239 dqs.forEachDirectStatement(graph, resource, proc);
242 return proc.getOrThrow();
246 public static List<Resource> garbageResources(ReadGraph graph) throws DatabaseException {
248 SerialisationSupport ss = graph.getService(SerialisationSupport.class);
250 TIntArrayList refs = new TIntArrayList();
251 TIntArrayList res = new TIntArrayList();
253 // Find all statements in the database
254 for(ClusterUID uid : listClusters(graph)) {
255 for(Resource r : resourcesByCluster(graph, uid)) {
256 int sid = ss.getTransientId(r);
257 for(Statement stm : directStatements(graph, r, true)) {
258 int oid = ss.getTransientId(stm.getObject());
266 TIntHashSet reached = new TIntHashSet();
269 int root = ss.getTransientId(graph.getRootLibrary());
272 int[] refArray = refs.toArray();
274 boolean changes = true;
278 for(int i=0;i<refArray.length;i+=2) {
280 int o = refArray[i+1];
281 if(reached.contains(s)) {
288 System.err.println("Reachability iteration, changes = " + changes);
291 ArrayList<Resource> result = new ArrayList<>();
292 for(int i=0;i<refArray.length;i+=2) {
294 if(reached.contains(s)) {
295 if(reached.add(refArray[i+1]))
300 res.forEach(new TIntProcedure() {
303 public boolean execute(int r) {
304 if(!reached.contains(r)) {
306 result.add(ss.getResource(r));
307 } catch (DatabaseException e) {
308 LOGGER.error("Unexpected error while resolving garbage resources.", e);
320 public static ClusterUID clusterUIDOfResource(ReadGraph graph, Resource resource) throws DatabaseException {
321 SerialisationSupport ss = graph.getService(SerialisationSupport.class);
322 return ss.getUID(resource).asCID();
325 public static boolean isClusterLoaded(ReadGraph graph, ClusterUID clusterUID) throws DatabaseException {
326 XSupport xs = graph.getService(XSupport.class);
327 return xs.isClusterLoaded(clusterUID);