]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/request/ModelInstances.java
possibleObjectForType utility
[simantics/platform.git] / bundles / org.simantics.db.layer0 / src / org / simantics / db / layer0 / request / ModelInstances.java
1 package org.simantics.db.layer0.request;
2
3 import java.util.Collection;
4 import java.util.Collections;
5 import java.util.HashMap;
6 import java.util.Map;
7
8 import org.simantics.databoard.Bindings;
9 import org.simantics.db.ReadGraph;
10 import org.simantics.db.Resource;
11 import org.simantics.db.common.request.PossibleIndexRoot;
12 import org.simantics.db.common.request.ResourceRead2;
13 import org.simantics.db.exception.DatabaseException;
14 import org.simantics.db.layer0.adapter.Instances;
15 import org.simantics.layer0.Layer0;
16 import org.simantics.simulation.ontology.SimulationResource;
17
18 /**
19  * Returns a Name->Resource map for instances of given type in a given model.
20  * 
21  * Uses Dependencies-index for obtaining instances. Uses L0.HasName for
22  * obtaining name.
23  * 
24  * @author Antti Villberg
25  */
26 public class ModelInstances extends ResourceRead2<Map<String, Resource>> {
27
28     /**
29      * @parameter modelPart is a Resource with URI under a model e.g. model can
30      *            be found using L0.PartOf
31      * @parameter type is the type to search instances for. The query returns
32      *            properly all instances of all subtypes.
33      */
34     public ModelInstances(Resource modelPart, Resource type) {
35         super(modelPart, type);
36     }
37
38     private Resource getModel(ReadGraph graph) throws DatabaseException {
39         SimulationResource SIMU = SimulationResource.getInstance(graph);
40         if (graph.isInstanceOf(resource, SIMU.Model)) {
41             return resource;
42         } else {
43             return graph.sync(new PossibleIndexRoot(resource));
44         }
45     }
46
47     @Override
48     public Map<String, Resource> perform(ReadGraph graph) throws DatabaseException {
49
50         Layer0 L0 = Layer0.getInstance(graph);
51
52         Instances query = graph.adapt(resource2, Instances.class);
53         if (query == null)
54             return Collections.emptyMap();
55
56         Resource model = getModel(graph);
57         if(model == null)
58             return Collections.emptyMap();
59         Collection<Resource> queryResult = query.find(graph, model);
60         if (queryResult.isEmpty())
61             return Collections.emptyMap();
62
63         Map<String, Resource> result = new HashMap<String, Resource>(queryResult.size());
64         for(Resource instance : queryResult) {
65             String name = graph.getRelatedValue(instance, L0.HasName, Bindings.STRING);
66             result.put(name, instance);
67         }
68         return result;
69
70     }
71
72 }