1 package org.simantics.district.network.techtype;
3 import java.util.Collection;
4 import java.util.HashMap;
6 import java.util.Objects;
8 import org.simantics.Simantics;
9 import org.simantics.databoard.Bindings;
10 import org.simantics.databoard.binding.NumberBinding;
11 import org.simantics.databoard.binding.error.BindingException;
12 import org.simantics.databoard.type.Datatype;
13 import org.simantics.databoard.type.NumberType;
14 import org.simantics.databoard.type.StringType;
15 import org.simantics.db.ReadGraph;
16 import org.simantics.db.RequestProcessor;
17 import org.simantics.db.Resource;
18 import org.simantics.db.WriteGraph;
19 import org.simantics.db.common.procedure.adapter.TransientCacheListener;
20 import org.simantics.db.common.request.PossibleIndexRoot;
21 import org.simantics.db.common.request.WriteRequest;
22 import org.simantics.db.exception.DatabaseException;
23 import org.simantics.db.layer0.QueryIndexUtils;
24 import org.simantics.db.layer0.request.PossibleVariable;
25 import org.simantics.db.layer0.request.PropertyInfo;
26 import org.simantics.db.layer0.request.PropertyInfoRequest;
27 import org.simantics.db.layer0.variable.Variable;
28 import org.simantics.district.network.ontology.DistrictNetworkResource;
29 import org.simantics.district.network.techtype.requests.PossibleTechTypeItem;
30 import org.simantics.district.network.techtype.requests.PossibleTechTypeTable;
31 import org.simantics.district.network.techtype.requests.TechTypeTableData;
32 import org.simantics.district.network.techtype.requests.TechTypeTableKeyName;
33 import org.simantics.layer0.Layer0;
34 import org.simantics.scl.runtime.SCLContext;
35 import org.simantics.structural.stubs.StructuralResource2;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
39 public class TechTypeUtils {
41 final static Logger LOGGER = LoggerFactory.getLogger(TechTypeUtils.class);
43 public static String DEFAULT_KEY_NAME = "pipeCode";
46 * Execute a cached query for a possible tech type table item in a table with a given item key.
48 * Result is null, if no such item was found.
50 * @param session A request processor on which to run the query
51 * @param itemCode A key value, such as a pipe code
52 * @throws DatabaseException
54 public static Map<String, String> getTableItem(RequestProcessor session, Resource table, String itemCode) throws DatabaseException {
55 return session.syncRequest(new PossibleTechTypeItem(table, itemCode), TransientCacheListener.instance());
59 * Get a single row in a tech type table for a given item code
61 * Result is null, if no such item was found.
63 * @param table A TechTypeTable resource
64 * @param itemCode A key value, such as a pipe code
65 * @return A map from property name to value
66 * @throws DatabaseException
68 public static Map<String, String> getTableItem(Resource table, String itemCode) throws DatabaseException {
69 Object graph = SCLContext.getCurrent().get("graph");
70 if (graph != null && graph instanceof ReadGraph)
71 return getTableItem((ReadGraph) graph, table, itemCode);
73 return getTableItem(Simantics.getSession(), table, itemCode);
77 * Reset all components that address the given tech type table to the table values.
79 * @param table A tech type table
80 * @throws DatabaseException
82 public static void resetComponents(Resource table) throws DatabaseException {
83 Simantics.getSession().syncRequest(new WriteRequest() {
85 public void perform(WriteGraph graph) throws DatabaseException {
86 Resource model = graph.syncRequest(new PossibleIndexRoot(table), TransientCacheListener.instance());
90 Resource type = graph.getPossibleObject(table, DistrictNetworkResource.getInstance(graph).TechType_TechTypeTable_HasComponentType);
94 Collection<Resource> components = QueryIndexUtils.searchByType(graph, model, type);
95 for (Resource component : components) {
96 updateComponent(graph, component, table);
103 * Reset all components that address the given tech type table to the table values.
105 * @param table A tech type table
106 * @throws DatabaseException
108 public static void resetMapElements(Resource table) throws DatabaseException {
109 Simantics.getSession().syncRequest(new WriteRequest() {
111 public void perform(WriteGraph graph) throws DatabaseException {
112 Resource model = graph.syncRequest(new PossibleIndexRoot(table), TransientCacheListener.instance());
116 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
117 Resource type = graph.getPossibleObject(table, DN.TechType_TechTypeTable_HasComponentType);
121 Layer0 L0 = Layer0.getInstance(graph);
122 String typeName = graph.getRelatedValue2(type, L0.HasName);
124 Resource mapping = null;
125 for (Resource m : QueryIndexUtils.searchByType(graph, model, DN.Mapping_Base)) {
126 String name = graph.getRelatedValue2(m, DN.Mapping_ComponentType);
127 if (Objects.equals(name, typeName)) {
133 if (mapping == null) {
134 LOGGER.warn("No mapping found for component type {}", type);
138 Map<String, PropertyInfo> properties = new HashMap<>();
139 Resource mappingType = graph.getSingleType(mapping, DN.Mapping_Base);
140 Collection<Resource> mappingRelations = graph.getObjects(mappingType, L0.DomainOf);
141 for (Resource r : mappingRelations) {
142 String propertyName = graph.getPossibleRelatedValue2(mapping, r);
143 if (propertyName == null)
146 Resource relation = graph.getPossibleObject(r, DN.Mapping_HasPropertyRelation);
147 if (relation == null)
150 properties.put(propertyName, graph.syncRequest(new PropertyInfoRequest(relation)));
153 Map<String, Map<String, String>> data = graph.syncRequest(new TechTypeTableData(table), TransientCacheListener.instance());
154 String keyName = graph.syncRequest(new TechTypeTableKeyName(table), TransientCacheListener.instance());
155 Resource keyRelation = properties.get(keyName).predicate;
157 if (keyRelation == null) {
158 LOGGER.warn("No relation mapped to property {} found in {} mapping", keyName, mapping);
162 Resource elementType = graph.isInstanceOf(mapping, DN.Mapping_EdgeMapping) ? DN.Edge :
163 graph.isInstanceOf(mapping, DN.Mapping_VertexMapping) ? DN.Vertex :
166 Collection<Resource> elements = QueryIndexUtils.searchByType(graph, model, elementType);
167 for (Resource element : elements) {
168 Resource elementMapping = graph.getPossibleObject(element, DN.HasMapping);
169 if (!mapping.equals(elementMapping))
172 String key = graph.getPossibleRelatedValue2(element, keyRelation);
173 Map<String, String> values = data.get(key);
174 if (values == null) {
175 LOGGER.info("Key {} no found in tech type table {}", key, table);
179 for (Map.Entry<String, String> entry : values.entrySet()) {
180 PropertyInfo prop = properties.get(entry.getKey());
184 String value = entry.getValue();
185 Datatype dt = prop.requiredDatatype;
186 if (dt instanceof NumberType) {
188 Object num = ((NumberBinding)prop.defaultBinding).create(value.replace(",", "."));
189 graph.claimLiteral(element, prop.predicate, prop.literalRange, num, prop.defaultBinding);
190 } catch (NumberFormatException e) {
191 // Revert to asserted value
192 graph.deny(element, prop.predicate);
193 } catch (BindingException e) {
194 LOGGER.error("Failed to get binding for datatype {}", dt, e);
196 } else if (dt instanceof StringType) {
197 graph.claimLiteral(element, prop.predicate, prop.literalRange, value, Bindings.STRING);
199 LOGGER.warn("updateComponent: Unsupported property type {}", dt);
208 * Update property values of a component based on the values in an associated tech type table, if any
210 * @param graph A write access interface to the graph database
211 * @param component A structural component
212 * @throws DatabaseException
214 public static void updateComponent(WriteGraph graph, Resource component) throws DatabaseException {
215 StructuralResource2 STR = StructuralResource2.getInstance(graph);
217 Resource type = graph.getSingleType(component, STR.Component);
218 Resource model = graph.syncRequest(new PossibleIndexRoot(component));
220 LOGGER.info("updateComponent: No model for {}", component);
224 Resource table = graph.syncRequest(new PossibleTechTypeTable(model, type), TransientCacheListener.instance());
226 LOGGER.info("updateComponent: No tech type table for {} in {}", type, model);
230 updateComponent(graph, component, table);
234 * Update property values of a component based on the values in an associated tech type table, if any
236 * @param component A structural component
237 * @throws DatabaseException
239 public static void updateComponent(Resource component) throws DatabaseException {
240 if (LOGGER.isTraceEnabled())
241 LOGGER.trace("updateComponent({})", component);
243 Simantics.getSession().syncRequest(new WriteRequest() {
245 public void perform(WriteGraph graph) throws DatabaseException {
246 updateComponent(graph, component);
252 * Update a single component's property values to those selected from a tech
255 * @param graph A write interface to the db
256 * @param component The component to be updated
257 * @param table A tech type table
258 * @throws DatabaseException
260 public static void updateComponent(WriteGraph graph, Resource component, Resource table)
261 throws DatabaseException {
262 if (LOGGER.isTraceEnabled())
263 LOGGER.trace("updateComponent(graph, {}, {}), component, table)");
265 Variable v = graph.syncRequest(new PossibleVariable(component));
267 LOGGER.info("No variable found for {}", component);
271 String keyProp = getKeyPropertyName(graph, table);
272 String itemCode = v.getPropertyValue(graph, keyProp);
274 Map<String, String> map = graph.syncRequest(new PossibleTechTypeItem(table, itemCode), TransientCacheListener.instance());
276 LOGGER.info("No entry found for \"{}\" in tech type table {}", itemCode, table);
280 for (String key : map.keySet()) {
281 // Don't write the key property
282 if (key.equals(DEFAULT_KEY_NAME))
285 Variable prop = v.getPossibleProperty(graph, key);
286 if (prop == null) continue;
288 Datatype dt = prop.getPossibleDatatype(graph);
289 if (dt == null) continue;
291 String value = map.get(key);
292 if (dt instanceof NumberType) {
294 Double num = Double.valueOf(value.replace(",", "."));
295 NumberBinding binding = Bindings.getBinding(dt);
296 prop.setValue(graph, binding.create(num));
297 } catch (NumberFormatException e) {
298 // Revert to asserted value
299 Resource pred = prop.getPossiblePredicateResource(graph);
301 graph.deny(component, pred);
302 } catch (BindingException e) {
303 LOGGER.error("Failed to get binding for datatype {}", dt, e);
305 } else if (dt instanceof StringType) {
306 prop.setValue(graph, value);
308 LOGGER.warn("updateComponent: Unsupported property type {}", dt);
313 public static String getKeyPropertyName(ReadGraph graph, Resource table) throws DatabaseException {
314 String name = graph.syncRequest(new TechTypeTableKeyName(table), TransientCacheListener.instance());
315 if (name == null) name = "_" + DEFAULT_KEY_NAME;