]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/request/PossibleModelInstances.java
New implementation NearestOwnerFinder of CommonDBUtils.getNearestOwner
[simantics/platform.git] / bundles / org.simantics.db.layer0 / src / org / simantics / db / layer0 / request / PossibleModelInstances.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.ResourceRead2;
12 import org.simantics.db.exception.DatabaseException;
13 import org.simantics.db.layer0.adapter.Instances;
14 import org.simantics.layer0.Layer0;
15 import org.simantics.simulation.ontology.SimulationResource;
16
17 /**
18  * Returns a Name->Resource map for instances of given type in a given model.
19  * 
20  * Uses Dependencies-index for obtaining instances. Uses L0.HasName for
21  * obtaining name.
22  * 
23  * @author Antti Villberg
24  */
25 public class PossibleModelInstances extends ResourceRead2<Map<String, Resource>> {
26
27     /**
28      * @parameter modelPart is a Resource with URI under a model e.g. model can
29      *            be found using L0.PartOf
30      * @parameter type is the type to search instances for. The query returns
31      *            properly all instances of all subtypes.
32      */
33     public PossibleModelInstances(Resource modelPart, Resource type) {
34         super(modelPart, type);
35     }
36
37     private Resource getModel(ReadGraph graph) throws DatabaseException {
38         SimulationResource SIMU = SimulationResource.getInstance(graph);
39         if (graph.isInstanceOf(resource, SIMU.Model)) {
40             return resource;
41         } else {
42             return graph.sync(new PossibleModel(resource));
43         }
44     }
45
46     @Override
47     public Map<String, Resource> perform(ReadGraph graph) throws DatabaseException {
48
49         Layer0 L0 = Layer0.getInstance(graph);
50
51         Instances query = graph.getPossibleAdapter(resource2, Instances.class);
52         if (query == null)
53             return Collections.emptyMap();
54
55         Resource model = getModel(graph);
56         if (model == null)
57             return Collections.emptyMap();
58
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.getPossibleRelatedValue(instance, L0.HasName, Bindings.STRING);
66             if (name != null)
67                 result.put(name, instance);
68         }
69         return result;
70
71     }
72
73 }