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;
10 import org.simantics.databoard.Bindings;
11 import org.simantics.db.ReadGraph;
12 import org.simantics.db.Resource;
13 import org.simantics.db.Statement;
14 import org.simantics.db.WriteGraph;
15 import org.simantics.db.common.procedure.adapter.DirectStatementProcedure;
16 import org.simantics.db.common.request.IsParent;
17 import org.simantics.db.common.request.ObjectsWithType;
18 import org.simantics.db.common.request.PossibleChild;
19 import org.simantics.db.common.request.PossibleObjectWithType;
20 import org.simantics.db.common.request.PossibleOwner;
21 import org.simantics.db.common.request.RuntimeEnvironmentRequest;
22 import org.simantics.db.exception.DatabaseException;
23 import org.simantics.db.exception.InvalidResourceReferenceException;
24 import org.simantics.db.service.ClusterUID;
25 import org.simantics.db.service.ClusteringSupport;
26 import org.simantics.db.service.DirectQuerySupport;
27 import org.simantics.db.service.SerialisationSupport;
28 import org.simantics.db.service.XSupport;
29 import org.simantics.layer0.Layer0;
30 import org.simantics.scl.compiler.environment.Environments;
31 import org.simantics.scl.compiler.runtime.RuntimeEnvironment;
32 import org.simantics.scl.compiler.top.SCLExpressionCompilationException;
33 import org.simantics.scl.compiler.types.Type;
34 import org.simantics.utils.datastructures.collections.CollectionUtils;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
38 import gnu.trove.list.array.TIntArrayList;
39 import gnu.trove.procedure.TIntProcedure;
40 import gnu.trove.set.hash.THashSet;
41 import gnu.trove.set.hash.TIntHashSet;
43 public class CommonDBUtils {
45 private static final Logger LOGGER = LoggerFactory.getLogger(CommonDBUtils.class);
47 public static boolean isParent(ReadGraph graph, Resource possibleParent, Resource possibleChild) throws DatabaseException {
48 return graph.sync(new IsParent(possibleParent, possibleChild));
51 public static Resource parent(ReadGraph graph, Resource child) throws DatabaseException {
52 return graph.getSingleObject(child, Layer0.getInstance(graph).PartOf);
55 public static String possibleRelatedString(ReadGraph graph, Resource subject, Resource relation) throws DatabaseException {
56 return graph.getPossibleRelatedValue(subject, relation, Bindings.STRING);
59 public static Integer possibleRelatedInteger(ReadGraph graph, Resource subject, Resource relation) throws DatabaseException {
60 return graph.getPossibleRelatedValue(subject, relation, Bindings.INTEGER);
63 public static Resource getPossibleOwner(ReadGraph graph, Resource resource) throws DatabaseException {
64 return graph.syncRequest(new PossibleOwner(resource));
68 * Finds a resource that is reachable from both input resources by as short as possible IsOwnedBy chain
70 public static Resource commonAncestor(ReadGraph graph, Resource r1, Resource r2) throws DatabaseException {
74 Layer0 L0 = Layer0.getInstance(graph);
75 HashSet<Resource> visited = new HashSet<Resource>();
80 r1 = graph.getPossibleObject(r1, L0.IsOwnedBy);
81 if(r1 != null && !visited.add(r1))
87 r2 = graph.getPossibleObject(r2, L0.IsOwnedBy);
88 if(r2 != null && !visited.add(r2))
94 private static Collection<Resource> getDirectOwners(ReadGraph graph, Resource resource) throws DatabaseException {
96 if(resource.equals(graph.getRootLibrary()))
97 return Collections.emptyList();
99 Layer0 L0 = Layer0.getInstance(graph);
101 Collection<Resource> owners = graph.getObjects(resource, L0.IsOwnedBy);
102 if(owners.isEmpty()) {
103 owners = new THashSet<Resource>();
105 // If there are no owners, collect resources referring to this resource by IsRelatedTo
106 for(Statement statement : graph.getStatements(resource, L0.IsWeaklyRelatedTo)) {
107 Resource inverse = graph.getPossibleInverse(statement.getPredicate());
108 if(inverse != null) {
109 if(graph.isSubrelationOf(inverse, L0.IsRelatedTo)) {
111 if(resource.equals(statement.getObject()))
113 owners.add(statement.getObject());
118 else if(owners.size() > 1) {
119 // TODO: getObjects returns duplicate entries (https://www.simantics.org/redmine/issues/4885) and therefore direct is Set<Resource>.
120 // Fix getObjects to not return duplicate entries
121 owners = new HashSet<Resource>(owners);
128 * This method didn't have a clear specification and therefore should not be used. Use instead
129 * the methods in the class {@link NearestOwnerFinder}.
132 public static Resource getNearestOwner(ReadGraph graph, Collection<Resource> resources) throws DatabaseException {
133 if(resources.size() == 1)
134 return NearestOwnerFinder.getNearestOwner(graph, resources.iterator().next());
136 return NearestOwnerFinder.getNearestOwnerFromDirectOwners(graph, resources);
139 public static Resource getClusterSetForNewResource(ReadGraph graph, Resource ... resources) throws DatabaseException {
141 if(resources.length == 1) return getClusterSetForNewResource(graph, resources[0]);
143 Resource owner = NearestOwnerFinder.getNearestOwnerFromDirectOwners(graph, CollectionUtils.toList(resources));
144 if(owner == null) return null;
145 return getClusterSetForNewResource(graph, owner, new HashSet<Resource>());
149 public static Resource getClusterSetForNewResource(ReadGraph graph, Collection<Resource> resources) throws DatabaseException {
151 if(resources.size() == 1) return getClusterSetForNewResource(graph, resources.iterator().next());
153 Resource owner = NearestOwnerFinder.getNearestOwnerFromDirectOwners(graph, resources);
154 return getClusterSetForNewResource(graph, owner, new HashSet<Resource>());
158 public static Resource getClusterSetForNewResource(ReadGraph graph, Resource resource, Set<Resource> visited) throws DatabaseException {
160 ClusteringSupport cs = graph.getService(ClusteringSupport.class);
161 if(cs.isClusterSet(resource)) return resource;
163 Resource owner = getPossibleOwner(graph, resource);
165 if(owner == null || owner == resource) return null;
166 if(!visited.add(owner)) return null;
168 return getClusterSetForNewResource(graph, owner, visited);
172 public static Resource getClusterSetForNewResource(ReadGraph graph, Resource r) throws DatabaseException {
173 return getClusterSetForNewResource(graph, r, new HashSet<Resource>());
177 public static void selectClusterSet(WriteGraph graph, Collection<Resource> resources) throws DatabaseException {
178 Resource clusterSet = getClusterSetForNewResource(graph, resources);
179 if(clusterSet == null) clusterSet = graph.getRootLibrary();
180 graph.setClusterSet4NewResource(clusterSet);
183 public static void selectClusterSet(WriteGraph graph, Resource ... resources) throws DatabaseException {
184 Resource clusterSet = getClusterSetForNewResource(graph, resources);
185 if(clusterSet == null) clusterSet = graph.getRootLibrary();
186 graph.setClusterSet4NewResource(clusterSet);
189 public static void selectClusterSet(WriteGraph graph, Resource resource) throws DatabaseException {
190 Resource clusterSet = getClusterSetForNewResource(graph, resource);
191 if(clusterSet == null) clusterSet = graph.getRootLibrary();
192 graph.setClusterSet4NewResource(clusterSet);
195 public static List<Resource> objectsWithType(ReadGraph graph, Resource subject, Resource relation, Resource type) throws DatabaseException {
196 return new ArrayList<Resource>(graph.syncRequest(new ObjectsWithType(subject, relation, type)));
199 public static Resource possibleObjectWithType(ReadGraph graph, Resource subject, Resource relation, Resource type) throws DatabaseException {
200 return graph.syncRequest(new PossibleObjectWithType(subject, relation, type));
203 public static List<ClusterUID> listClusters(ReadGraph graph) throws DatabaseException {
204 XSupport xs = graph.getService(XSupport.class);
205 ClusterUID uids[] = xs.listClusters();
206 ArrayList<ClusterUID> result = new ArrayList<>(uids.length);
207 for(ClusterUID uid : uids) result.add(uid);
211 public static List<Resource> resourcesByCluster(ReadGraph graph, ClusterUID uid) throws DatabaseException {
212 SerialisationSupport ss = graph.getService(SerialisationSupport.class);
213 ArrayList<Resource> result = new ArrayList<Resource>();
214 // Index 0 is illegal
215 for(int i=1;i<1<<12;i++) {
217 result.add(ss.getResource(uid.toRID(i)));
218 } catch (InvalidResourceReferenceException e) {
224 public static List<Statement> directStatements(ReadGraph graph, Resource resource, boolean ignoreVirtual) throws DatabaseException {
226 DirectQuerySupport dqs = graph.getService(DirectQuerySupport.class);
227 DirectStatementProcedure proc = new DirectStatementProcedure();
230 return dqs.getDirectPersistentStatements(graph, resource);
232 return dqs.getDirectStatements(graph, resource);
237 public static List<Resource> garbageResources(ReadGraph graph) throws DatabaseException {
239 SerialisationSupport ss = graph.getService(SerialisationSupport.class);
241 TIntArrayList refs = new TIntArrayList();
242 TIntArrayList res = new TIntArrayList();
244 // Find all statements in the database
245 for(ClusterUID uid : listClusters(graph)) {
246 for(Resource r : resourcesByCluster(graph, uid)) {
247 int sid = ss.getTransientId(r);
248 for(Statement stm : directStatements(graph, r, true)) {
249 int oid = ss.getTransientId(stm.getObject());
257 TIntHashSet reached = new TIntHashSet();
260 int root = ss.getTransientId(graph.getRootLibrary());
263 int[] refArray = refs.toArray();
265 boolean changes = true;
269 for(int i=0;i<refArray.length;i+=2) {
271 int o = refArray[i+1];
272 if(reached.contains(s)) {
279 System.err.println("Reachability iteration, changes = " + changes);
282 ArrayList<Resource> result = new ArrayList<>();
283 for(int i=0;i<refArray.length;i+=2) {
285 if(reached.contains(s)) {
286 if(reached.add(refArray[i+1]))
291 res.forEach(new TIntProcedure() {
294 public boolean execute(int r) {
295 if(!reached.contains(r)) {
297 result.add(ss.getResource(r));
298 } catch (DatabaseException e) {
299 LOGGER.error("Unexpected error while resolving garbage resources.", e);
311 public static ClusterUID clusterUIDOfResource(ReadGraph graph, Resource resource) throws DatabaseException {
312 SerialisationSupport ss = graph.getService(SerialisationSupport.class);
313 return ss.getUID(resource).asCID();
316 public static boolean isClusterLoaded(ReadGraph graph, ClusterUID clusterUID) throws DatabaseException {
317 XSupport xs = graph.getService(XSupport.class);
318 return xs.isClusterLoaded(clusterUID);
321 public static void setImmutable(ReadGraph graph, Resource resource, boolean value) throws DatabaseException {
322 XSupport xs = graph.getService(XSupport.class);
323 xs.setImmutable(resource, value);
326 public static Type getSCLType(ReadGraph graph, RuntimeEnvironment runtimeEnvironment, String typeText) throws DatabaseException {
328 return Environments.getType(runtimeEnvironment.getEnvironment(), typeText);
329 } catch (SCLExpressionCompilationException e) {
330 throw new DatabaseException(e);
334 public static Type getSCLType(ReadGraph graph, Resource resource, String typeText) throws DatabaseException {
336 RuntimeEnvironment runtimeEnvironment = graph.syncRequest(new RuntimeEnvironmentRequest(resource));
337 return Environments.getType(runtimeEnvironment.getEnvironment(), typeText);
338 } catch (SCLExpressionCompilationException e) {
339 throw new DatabaseException(e);
343 public static Resource getPossibleChild(ReadGraph graph, Resource resource, String name) throws DatabaseException {
344 return graph.sync(new PossibleChild(resource, name));
347 public static Resource getPossibleChild(ReadGraph graph, Resource resource, Resource type, String name) throws DatabaseException {
348 Resource child = graph.sync(new PossibleChild(resource, name));
349 if(child == null) return null;
350 if(!graph.isInstanceOf(child, type)) return null;