]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.district.network/src/org/simantics/district/network/techtype/TechTypeUtils.java
Updating of component properties when type code changes
[simantics/district.git] / org.simantics.district.network / src / org / simantics / district / network / techtype / TechTypeUtils.java
1 package org.simantics.district.network.techtype;
2
3 import java.util.Collection;
4 import java.util.Map;
5
6 import org.simantics.Simantics;
7 import org.simantics.databoard.Bindings;
8 import org.simantics.databoard.binding.NumberBinding;
9 import org.simantics.databoard.binding.error.BindingException;
10 import org.simantics.databoard.type.Datatype;
11 import org.simantics.databoard.type.NumberType;
12 import org.simantics.databoard.type.StringType;
13 import org.simantics.db.ReadGraph;
14 import org.simantics.db.RequestProcessor;
15 import org.simantics.db.Resource;
16 import org.simantics.db.WriteGraph;
17 import org.simantics.db.common.procedure.adapter.TransientCacheListener;
18 import org.simantics.db.common.request.PossibleIndexRoot;
19 import org.simantics.db.common.request.WriteRequest;
20 import org.simantics.db.exception.DatabaseException;
21 import org.simantics.db.layer0.QueryIndexUtils;
22 import org.simantics.db.layer0.request.PossibleVariable;
23 import org.simantics.db.layer0.variable.Variable;
24 import org.simantics.district.network.ontology.DistrictNetworkResource;
25 import org.simantics.district.network.techtype.requests.PossibleTechTypeItem;
26 import org.simantics.district.network.techtype.requests.PossibleTechTypeTable;
27 import org.simantics.district.network.techtype.requests.TechTypeTableKeyName;
28 import org.simantics.scl.runtime.SCLContext;
29 import org.simantics.structural.stubs.StructuralResource2;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 public class TechTypeUtils {
34         
35         final static Logger LOGGER = LoggerFactory.getLogger(TechTypeUtils.class);
36
37         public static String DEFAULT_KEY_NAME = "pipeCode";
38
39         /**
40          * Execute a cached query for a possible tech type table item in a table with a given item key.
41          * 
42          * Result is null, if no such item was found.
43          * 
44          * @param session  A request processor on which to run the query
45          * @param itemCode  A key value, such as a pipe code
46          * @throws DatabaseException
47          */
48         public static Map<String, String> getTableItem(RequestProcessor session, Resource table, String itemCode) throws DatabaseException {
49                 return session.syncRequest(new PossibleTechTypeItem(table, itemCode), TransientCacheListener.instance());
50         }
51
52         /**
53          * Get a single row in a tech type table for a given item code
54          * 
55          * Result is null, if no such item was found.
56          * 
57          * @param table  A TechTypeTable resource
58          * @param itemCode  A key value, such as a pipe code
59          * @return  A map from property name to value
60          * @throws DatabaseException
61          */
62         public static Map<String, String> getTableItem(Resource table, String itemCode) throws DatabaseException {
63                 Object graph = SCLContext.getCurrent().get("graph");
64                 if (graph != null && graph instanceof ReadGraph)
65                         return getTableItem((ReadGraph) graph, table, itemCode);
66                 else
67                         return getTableItem(Simantics.getSession(), table, itemCode);
68         }
69         
70         /**
71          * Reset all components that address the given tech type table to the table values.
72          * 
73          * @param table  A tech type table
74          * @throws DatabaseException
75          */
76         public static void resetComponents(Resource table) throws DatabaseException {
77                 Simantics.getSession().syncRequest(new WriteRequest() {
78                         @Override
79                         public void perform(WriteGraph graph) throws DatabaseException {
80                                 Resource model = graph.syncRequest(new PossibleIndexRoot(table), TransientCacheListener.instance());
81                                 if (model == null)
82                                         return;
83                                 
84                                 Resource type = graph.getPossibleObject(table, DistrictNetworkResource.getInstance(graph).TechType_TechTypeTable_HasComponentType);
85                                 if (type == null)
86                                         return;
87                                 
88                                 Collection<Resource> components = QueryIndexUtils.searchByType(graph, model, type);
89                                 for (Resource component : components) {
90                                         updateComponent(graph, component, table);
91                                 }
92                         }
93                 });
94         }
95         
96         /**
97          * Update property values of a component based on the values in an associated tech type table, if any
98          * 
99          * @param graph  A write access interface to the graph database
100          * @param component  A structural component
101          * @throws DatabaseException
102          */
103         public static void updateComponent(WriteGraph graph, Resource component) throws DatabaseException {
104                 StructuralResource2 STR = StructuralResource2.getInstance(graph);
105                 
106                 Resource type = graph.getSingleType(component, STR.Component);
107                 Resource model = graph.syncRequest(new PossibleIndexRoot(component));
108                 if (model == null) {
109                         LOGGER.info("updateComponent: No model for {}", component);
110                         return;
111                 }
112                 
113                 Resource table = graph.syncRequest(new PossibleTechTypeTable(model, type), TransientCacheListener.instance());
114                 if (table == null) {
115                         LOGGER.info("updateComponent: No tech type table for {} in {}", type, model);
116                         return;
117                 }
118                 
119                 updateComponent(graph, component, table);
120         }
121
122         /**
123          * Update property values of a component based on the values in an associated tech type table, if any
124          * 
125          * @param component  A structural component
126          * @throws DatabaseException
127          */
128         public static void updateComponent(Resource component) throws DatabaseException {
129                 if (LOGGER.isTraceEnabled())
130                         LOGGER.trace("updateComponent({})", component);
131                                         
132                 Simantics.getSession().syncRequest(new WriteRequest() {
133                         @Override
134                         public void perform(WriteGraph graph) throws DatabaseException {
135                                 updateComponent(graph, component);
136                         }
137                 });
138         }
139
140         /**
141          * Update a single component's property values to those selected from a tech
142          * type table
143          * 
144          * @param graph  A write interface to the db
145          * @param component  The component to be updated
146          * @param table  A tech type table
147          * @throws DatabaseException
148          */
149         public static void updateComponent(WriteGraph graph, Resource component, Resource table)
150                         throws DatabaseException {
151                 if (LOGGER.isTraceEnabled())
152                         LOGGER.trace("updateComponent(graph, {}, {}), component, table)");
153                                         
154                 Variable v = graph.syncRequest(new PossibleVariable(component));
155                 if (v == null) {
156                         LOGGER.info("No variable found for {}", component);
157                         return;
158                 }
159                 
160                 String keyProp = getKeyPropertyName(graph, table);
161                 String itemCode = v.getPropertyValue(graph, keyProp);
162                 
163                 Map<String, String> map = graph.syncRequest(new PossibleTechTypeItem(table, itemCode), TransientCacheListener.instance());
164                 if (map == null) {
165                         LOGGER.info("No entry found for \"{}\" in tech type table {}", itemCode, table);
166                         return;
167                 }
168                 
169                 for (String key : map.keySet()) {
170                         // Don't write the key property
171                         if (key.equals(DEFAULT_KEY_NAME))
172                                 continue;
173                         
174                         Variable prop = v.getPossibleProperty(graph, key);
175                         if (prop == null) continue;
176                         
177                         Datatype dt = prop.getPossibleDatatype(graph);
178                         if (dt == null) continue;
179                         
180                         String value = map.get(key);
181                         if (dt instanceof NumberType) {
182                                 try {
183                                         Double num = Double.valueOf(value.replace(",", "."));
184                                         NumberBinding binding = Bindings.getBinding(dt);
185                                         prop.setValue(graph, binding.create(num));
186                                 } catch (NumberFormatException e) {
187                                         // Revert to asserted value
188                                         Resource pred = prop.getPossiblePredicateResource(graph);
189                                         if (pred != null)
190                                                 graph.deny(component, pred);
191                                 } catch (BindingException e) {
192                                         LOGGER.error("Failed to get binding for datatype {}", dt, e);
193                                 }
194                         } else if (dt instanceof StringType) {
195                                 prop.setValue(graph, value);
196                         } else {
197                                 LOGGER.warn("updateComponent: Unsupported property type {}", dt);
198                         }
199                 }
200         }
201
202         public static String getKeyPropertyName(ReadGraph graph, Resource table) throws DatabaseException {
203                 String name = graph.syncRequest(new TechTypeTableKeyName(table), TransientCacheListener.instance());
204                 if (name == null) name = "_" + DEFAULT_KEY_NAME;
205                 return name; 
206         }
207 }