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.THashSet;
36 import gnu.trove.set.hash.TIntHashSet;
38 public class CommonDBUtils {
40 private static final Logger LOGGER = LoggerFactory.getLogger(CommonDBUtils.class);
42 public static boolean isParent(ReadGraph graph, Resource possibleParent, Resource possibleChild) throws DatabaseException {
43 return graph.sync(new IsParent(possibleParent, possibleChild));
46 public static Resource parent(ReadGraph graph, Resource child) throws DatabaseException {
47 return graph.getSingleObject(child, Layer0.getInstance(graph).PartOf);
50 public static String possibleRelatedString(ReadGraph graph, Resource subject, Resource relation) throws DatabaseException {
51 return graph.getPossibleRelatedValue(subject, relation, Bindings.STRING);
54 public static Integer possibleRelatedInteger(ReadGraph graph, Resource subject, Resource relation) throws DatabaseException {
55 return graph.getPossibleRelatedValue(subject, relation, Bindings.INTEGER);
58 public static Resource getPossibleOwner(ReadGraph graph, Resource resource) throws DatabaseException {
59 return graph.syncRequest(new PossibleOwner(resource));
63 * Finds a resource that is reachable from both input resources by as short as possible IsOwnedBy chain
65 public static Resource commonAncestor(ReadGraph graph, Resource r1, Resource r2) throws DatabaseException {
69 Layer0 L0 = Layer0.getInstance(graph);
70 HashSet<Resource> visited = new HashSet<Resource>();
75 r1 = graph.getPossibleObject(r1, L0.IsOwnedBy);
76 if(r1 != null && !visited.add(r1))
82 r2 = graph.getPossibleObject(r2, L0.IsOwnedBy);
83 if(r2 != null && !visited.add(r2))
89 private static Collection<Resource> getDirectOwners(ReadGraph graph, Resource resource) throws DatabaseException {
91 if(resource.equals(graph.getRootLibrary()))
92 return Collections.emptyList();
94 Layer0 L0 = Layer0.getInstance(graph);
96 Collection<Resource> owners = graph.getObjects(resource, L0.IsOwnedBy);
97 if(owners.isEmpty()) {
98 owners = new THashSet<Resource>();
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)) {
106 if(resource.equals(statement.getObject()))
108 owners.add(statement.getObject());
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);
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}.
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());
131 return NearestOwnerFinder.getNearestOwnerFromDirectOwners(graph, resources);
134 public static Resource getClusterSetForNewResource(ReadGraph graph, Resource ... resources) throws DatabaseException {
136 if(resources.length == 1) return getClusterSetForNewResource(graph, resources[0]);
138 Resource owner = NearestOwnerFinder.getNearestOwnerFromDirectOwners(graph, CollectionUtils.toList(resources));
139 if(owner == null) return null;
140 return getClusterSetForNewResource(graph, owner, new HashSet<Resource>());
144 public static Resource getClusterSetForNewResource(ReadGraph graph, Collection<Resource> resources) throws DatabaseException {
146 if(resources.size() == 1) return getClusterSetForNewResource(graph, resources.iterator().next());
148 Resource owner = NearestOwnerFinder.getNearestOwnerFromDirectOwners(graph, resources);
149 return getClusterSetForNewResource(graph, owner, new HashSet<Resource>());
153 public static Resource getClusterSetForNewResource(ReadGraph graph, Resource resource, Set<Resource> visited) throws DatabaseException {
155 ClusteringSupport cs = graph.getService(ClusteringSupport.class);
156 if(cs.isClusterSet(resource)) return resource;
158 Resource owner = getPossibleOwner(graph, resource);
160 if(owner == null || owner == resource) return null;
161 if(!visited.add(owner)) return null;
163 return getClusterSetForNewResource(graph, owner, visited);
167 public static Resource getClusterSetForNewResource(ReadGraph graph, Resource r) throws DatabaseException {
168 return getClusterSetForNewResource(graph, r, new HashSet<Resource>());
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);
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);
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);
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)));
194 public static Resource possibleObjectWithType(ReadGraph graph, Resource subject, Resource relation, Resource type) throws DatabaseException {
195 return graph.syncRequest(new PossibleObjectWithType(subject, relation, type));
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);
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++) {
212 result.add(ss.getResource(uid.toRID(i)));
213 } catch (InvalidResourceReferenceException e) {
219 public static List<Statement> directStatements(ReadGraph graph, Resource resource, boolean ignoreVirtual) throws DatabaseException {
221 DirectQuerySupport dqs = graph.getService(DirectQuerySupport.class);
222 DirectStatementProcedure proc = new DirectStatementProcedure();
225 return dqs.getDirectPersistentStatements(graph, resource);
227 return dqs.getDirectStatements(graph, resource);
232 public static List<Resource> garbageResources(ReadGraph graph) throws DatabaseException {
234 SerialisationSupport ss = graph.getService(SerialisationSupport.class);
236 TIntArrayList refs = new TIntArrayList();
237 TIntArrayList res = new TIntArrayList();
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());
252 TIntHashSet reached = new TIntHashSet();
255 int root = ss.getTransientId(graph.getRootLibrary());
258 int[] refArray = refs.toArray();
260 boolean changes = true;
264 for(int i=0;i<refArray.length;i+=2) {
266 int o = refArray[i+1];
267 if(reached.contains(s)) {
274 System.err.println("Reachability iteration, changes = " + changes);
277 ArrayList<Resource> result = new ArrayList<>();
278 for(int i=0;i<refArray.length;i+=2) {
280 if(reached.contains(s)) {
281 if(reached.add(refArray[i+1]))
286 res.forEach(new TIntProcedure() {
289 public boolean execute(int r) {
290 if(!reached.contains(r)) {
292 result.add(ss.getResource(r));
293 } catch (DatabaseException e) {
294 LOGGER.error("Unexpected error while resolving garbage resources.", e);
306 public static ClusterUID clusterUIDOfResource(ReadGraph graph, Resource resource) throws DatabaseException {
307 SerialisationSupport ss = graph.getService(SerialisationSupport.class);
308 return ss.getUID(resource).asCID();
311 public static boolean isClusterLoaded(ReadGraph graph, ClusterUID clusterUID) throws DatabaseException {
312 XSupport xs = graph.getService(XSupport.class);
313 return xs.isClusterLoaded(clusterUID);