package org.simantics.db.layer0.request; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.simantics.databoard.Bindings; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.common.request.PossibleIndexRoot; import org.simantics.db.common.request.ResourceRead2; import org.simantics.db.exception.DatabaseException; import org.simantics.db.layer0.adapter.Instances; import org.simantics.layer0.Layer0; import org.simantics.simulation.ontology.SimulationResource; /** * Returns a Name->Resource map for instances of given type in a given model. * * Uses Dependencies-index for obtaining instances. Uses L0.HasName for * obtaining name. * * @author Antti Villberg */ public class ModelInstances extends ResourceRead2> { /** * @parameter modelPart is a Resource with URI under a model e.g. model can * be found using L0.PartOf * @parameter type is the type to search instances for. The query returns * properly all instances of all subtypes. */ public ModelInstances(Resource modelPart, Resource type) { super(modelPart, type); } private Resource getModel(ReadGraph graph) throws DatabaseException { SimulationResource SIMU = SimulationResource.getInstance(graph); if (graph.isInstanceOf(resource, SIMU.Model)) { return resource; } else { return graph.sync(new PossibleIndexRoot(resource)); } } @Override public Map perform(ReadGraph graph) throws DatabaseException { Layer0 L0 = Layer0.getInstance(graph); Instances query = graph.adapt(resource2, Instances.class); if (query == null) return Collections.emptyMap(); Resource model = getModel(graph); if(model == null) return Collections.emptyMap(); Collection queryResult = query.find(graph, model); if (queryResult.isEmpty()) return Collections.emptyMap(); Map result = new HashMap(queryResult.size()); for(Resource instance : queryResult) { String name = graph.getRelatedValue(instance, L0.HasName, Bindings.STRING); result.put(name, instance); } return result; } }