]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.district.network/src/org/simantics/district/network/DistrictNetworkUtil.java
596c3667543cd78a714925f9386fbcbe54ebe0c7
[simantics/district.git] / org.simantics.district.network / src / org / simantics / district / network / DistrictNetworkUtil.java
1 package org.simantics.district.network;
2
3 import java.awt.geom.Rectangle2D;
4 import java.util.ArrayList;
5 import java.util.Collection;
6 import java.util.Iterator;
7 import java.util.List;
8 import java.util.stream.Collectors;
9 import java.util.stream.Stream;
10
11 import org.simantics.databoard.Bindings;
12 import org.simantics.datatypes.literal.RGB;
13 import org.simantics.datatypes.literal.RGB.Integer;
14 import org.simantics.db.ReadGraph;
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.IndexRoot;
19 import org.simantics.db.common.request.ResourceRead;
20 import org.simantics.db.common.utils.OrderedSetUtils;
21 import org.simantics.db.exception.BindingException;
22 import org.simantics.db.exception.DatabaseException;
23 import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;
24 import org.simantics.db.exception.ServiceException;
25 import org.simantics.db.indexing.IndexUtils;
26 import org.simantics.db.layer0.request.PossibleVariable;
27 import org.simantics.db.layer0.variable.Variable;
28 import org.simantics.diagram.stubs.DiagramResource;
29 import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
30 import org.simantics.diagram.synchronization.graph.layer.GraphLayer;
31 import org.simantics.diagram.synchronization.graph.layer.IGraphLayerUtil;
32 import org.simantics.district.network.ontology.DistrictNetworkResource;
33 import org.simantics.layer0.Layer0;
34 import org.simantics.modeling.ModelingResources;
35 import org.simantics.modeling.adapters.NewCompositeActionFactory;
36 import org.simantics.operation.Layer0X;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 public class DistrictNetworkUtil {
41
42     private static final Logger LOGGER = LoggerFactory.getLogger(DistrictNetworkUtil.class);
43
44     public static Resource createEdge(WriteGraph graph, Resource composite, double[] detailedGeometryCoords) throws DatabaseException {
45         return createEdge(graph, composite, graph.getPossibleObject(composite, DistrictNetworkResource.getInstance(graph).EdgeDefaultMapping), detailedGeometryCoords);
46     }
47
48     public static Resource createEdge(WriteGraph graph, Resource composite, Resource mapping, double[] detailedGeometryCoords) throws DatabaseException {
49         Layer0 L0 = Layer0.getInstance(graph);
50         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
51         if (mapping == null) {
52             mapping = graph.getSingleObject(composite, DN.EdgeDefaultMapping);
53         }
54         
55         Resource edge = graph.newResource();
56         graph.claim(edge, L0.InstanceOf, DN.Edge);
57         
58         graph.claim(edge, DN.HasMapping, null, mapping);
59         
60         OrderedSetUtils.addFirst(graph, composite, edge);
61         graph.claim(composite, L0.ConsistsOf, L0.PartOf, edge);
62         
63         claimFreshElementName(graph, composite, edge);
64         
65         // We need to put GraphLayer to newLayers so...
66         for (Resource layer : graph.getObjects(composite, DiagramResource.getInstance(graph).HasLayer)) {
67             IGraphLayerUtil layerUtil = graph.adapt(graph.getSingleObject(layer, Layer0.getInstance(graph).InstanceOf), IGraphLayerUtil.class);
68             
69             GraphLayer gl = layerUtil.loadLayer(graph, layer);
70             gl.forEachTag(tag -> {
71                 DiagramGraphUtil.tag(graph, edge, tag, true);
72             });
73         }
74         
75         // add detailed geometry (if any)
76         graph.claimLiteral(edge, DN.Edge_HasGeometry, detailedGeometryCoords, Bindings.DOUBLE_ARRAY);
77         return edge;
78     }
79
80     public static Resource createVertex(WriteGraph graph, Resource composite, double[] coords, double elevation) throws DatabaseException {
81         Resource defaultVertexMapping = graph.getPossibleObject(composite, DistrictNetworkResource.getInstance(graph).VertexDefaultMapping);
82         return createVertex(graph, composite, coords, elevation, defaultVertexMapping);
83     }
84
85     public static Resource createVertex(WriteGraph graph, Resource composite, double[] coords, double elevation, Resource mapping) throws DatabaseException {
86         Layer0 L0 = Layer0.getInstance(graph);
87         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
88         DiagramResource DIA = DiagramResource.getInstance(graph);
89         Resource vertex = graph.newResource();
90         graph.claim(vertex, L0.InstanceOf, DN.Vertex);
91         graph.claimLiteral(vertex, DIA.HasLocation, coords);
92         graph.claimLiteral(vertex, DN.Vertex_HasElevation, elevation, Bindings.DOUBLE);
93         
94         graph.claim(vertex, DN.HasMapping, null, mapping);
95         
96         OrderedSetUtils.add(graph, composite, vertex);
97         graph.claim(composite, L0.ConsistsOf, L0.PartOf, vertex);
98         
99         claimFreshElementName(graph, composite, vertex);
100         
101         // We need to put GraphLayer to newLayers so...
102         for (Resource layer : graph.getObjects(composite, DiagramResource.getInstance(graph).HasLayer)) {
103             IGraphLayerUtil layerUtil = graph.adapt(graph.getSingleObject(layer, Layer0.getInstance(graph).InstanceOf), IGraphLayerUtil.class);
104             
105             GraphLayer gl = layerUtil.loadLayer(graph, layer);
106             gl.forEachTag(tag -> {
107                 DiagramGraphUtil.tag(graph, vertex, tag, true);
108             });
109         }
110         
111         return vertex;
112     }
113     
114     public static Resource joinVertices(WriteGraph graph, Collection<Resource> vertices) throws DatabaseException {
115         if (vertices.isEmpty())
116             throw new IllegalArgumentException("vertices-collection should not be empty for joining vertices!");
117         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
118         Iterator<Resource> verticeIterator = vertices.iterator();
119         Resource master = verticeIterator.next();
120         while (verticeIterator.hasNext()) {
121             Resource slave = verticeIterator.next();
122             Resource composite = graph.getSingleObject(slave, Layer0.getInstance(graph).PartOf);
123             Collection<Resource> startVertexEdges = graph.getObjects(slave, DN.HasStartVertex_Inverse);
124             for (Resource startVertexEdge : startVertexEdges) {
125                 graph.deny(startVertexEdge, DN.HasStartVertex);
126                 graph.claim(startVertexEdge, DN.HasStartVertex, master);
127             }
128             Collection<Resource> endVertexEdges = graph.getObjects(slave, DN.HasEndVertex_Inverse);
129             for (Resource endVertexEdge : endVertexEdges) {
130                 graph.deny(endVertexEdge, DN.HasEndVertex);
131                 graph.claim(endVertexEdge, DN.HasEndVertex, master);
132             }
133             OrderedSetUtils.remove(graph, composite, slave);
134             // Remove ConsistsOf statement
135             graph.deny(composite, Layer0.getInstance(graph).ConsistsOf, slave);
136         }
137         return master;
138     }
139     
140     public static double calculateDistance(ReadGraph graph, Resource startVertex, Resource endVertex) throws DatabaseException {
141         Layer0 L0 = Layer0.getInstance(graph);
142         Resource startComposite = graph.getSingleObject(startVertex, L0.PartOf);
143         Resource endComposite = graph.getSingleObject(endVertex, L0.PartOf);
144         if (!startComposite.equalsResource(endComposite)) {
145             throw new DatabaseException("Can not calculate distance between vertices on different composites! " + startVertex + " -> " + endVertex);
146         }
147         Resource crs = graph.getSingleObject(startComposite, DistrictNetworkResource.getInstance(graph).HasSpatialRefSystem);
148         
149         CRS crsClass = graph.adapt(crs, CRS.class);
150         
151         double[] startCoords = graph.getRelatedValue2(startVertex, DiagramResource.getInstance(graph).HasLocation, Bindings.DOUBLE_ARRAY);
152         double[] endCoords = graph.getRelatedValue2(endVertex, DiagramResource.getInstance(graph).HasLocation, Bindings.DOUBLE_ARRAY);
153         
154         return crsClass.calculateDistance(startCoords, endCoords);
155     }
156     
157     public static final String claimFreshElementName(WriteGraph graph, Resource diagram, Resource element) throws DatabaseException {
158         Layer0 L0 = Layer0.getInstance(graph);
159         DiagramResource DIA = DiagramResource.getInstance(graph);
160         // Get name prefix from diagram
161         String namePrefix = graph.getPossibleRelatedValue2(diagram, Layer0X.getInstance(graph).HasGeneratedNamePrefix);
162         if (namePrefix == null)
163             namePrefix = "";
164         // Give running name to element and increment the counter attached to the diagram.
165         Long l = graph.getPossibleRelatedValue(diagram, DIA.HasModCount, Bindings.LONG);
166         if (l == null)
167             l = Long.valueOf(0L);
168         String name = namePrefix + l.toString();
169         graph.claimLiteral(element, L0.HasName, name, Bindings.STRING);
170         graph.claimLiteral(diagram, DIA.HasModCount, ++l, Bindings.LONG);
171         return name;
172     }
173
174     public static Resource getDiagramElement(ReadGraph graph, Resource component) throws DatabaseException {
175         if (component == null)
176             return null;
177         DiagramResource DIA = DiagramResource.getInstance(graph);
178         if (graph.isInstanceOf(component, DIA.Element))
179             return component;
180         ModelingResources MOD = ModelingResources.getInstance(graph);
181         Resource element = graph.getPossibleObject(component, MOD.ComponentToElement);
182         return element != null && graph.isInstanceOf(element, DIA.Element) ? element : null;
183     }
184
185     public static Resource getMappedElement(ReadGraph graph, Resource element) throws DatabaseException {
186         if (element == null)
187             return null;
188         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
189         return graph.getPossibleObject(element, DN.MappedComponent);
190     }
191
192     public static Resource getMappedComponent(ReadGraph graph, Resource element) throws DatabaseException {
193         if (element == null)
194             return null;
195         Resource mappedElement = getMappedElement(graph, element);
196         if (mappedElement == null)
197             return null;
198         ModelingResources MOD = ModelingResources.getInstance(graph);
199         return graph.getPossibleObject(mappedElement, MOD.ElementToComponent);
200     }
201     
202     public static Resource getMappedComponentCached(ReadGraph graph, Resource vertex) throws DatabaseException {
203         return graph.syncRequest(new MappedComponentRequest(vertex), TransientCacheListener.instance());
204     }
205
206     public static Resource getMappedDNElement(ReadGraph graph, Resource element) throws DatabaseException {
207         if (element == null)
208             return null;
209         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
210         return graph.getPossibleObject(element, DN.MappedFromElement);
211     }
212
213     public static Variable toMappedConfigurationModule(ReadGraph graph, Resource input) throws DatabaseException {
214         if (input == null)
215             return null;
216
217         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
218         if (graph.isInstanceOf(input, DN.Element)) {
219             Resource mappedElement = getMappedElement(graph, input);
220             if (mappedElement == null)
221                 return null;
222
223             ModelingResources MOD = ModelingResources.getInstance(graph);
224             Resource mappedComponent = graph.getPossibleObject(mappedElement, MOD.ElementToComponent);
225             if (mappedComponent == null)
226                 return null;
227
228             return graph.syncRequest(new PossibleVariable(mappedComponent));
229         }
230         return null;
231     }
232
233     public static void toggleDrawMap(WriteGraph graph, Resource diagram) throws ManyObjectsForFunctionalRelationException, BindingException, ServiceException {
234         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
235         Boolean current = graph.getPossibleRelatedValue(diagram, DN.Diagram_drawMapEnabled, Bindings.BOOLEAN);
236         if (current == null)
237             current = true;
238         graph.claimLiteral(diagram, DN.Diagram_drawMapEnabled, !current, Bindings.BOOLEAN);
239     }
240
241     public static Boolean drawMapEnabled(ReadGraph graph, Resource diagram) throws ManyObjectsForFunctionalRelationException, BindingException, ServiceException {
242         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
243         Boolean current = graph.getPossibleRelatedValue(diagram, DN.Diagram_drawMapEnabled, Bindings.BOOLEAN);
244         return current != null ? current : true;
245     }
246
247     public static void changeMapBackgroundColor(WriteGraph graph, Resource diagram, Integer integer) throws DatabaseException {
248         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
249         graph.claimLiteral(diagram, DN.Diagram_backgroundColor, integer, Bindings.getBindingUnchecked(RGB.Integer.class));
250     }
251     
252     public static Boolean trackChangesEnabled(ReadGraph graph, Resource diagram) throws DatabaseException {
253         if (diagram != null && graph.hasStatement(diagram)) {
254             return Boolean.TRUE.equals(graph.getPossibleRelatedValue(diagram,
255                 DistrictNetworkResource.getInstance(graph).Diagram_trackChangesEnabled));
256         } else {
257             return false;
258         }
259     }
260
261     public static RGB.Integer backgroundColor(ReadGraph graph, Resource diagram) throws DatabaseException {
262         return graph.getPossibleRelatedValue(diagram,
263                 DistrictNetworkResource.getInstance(graph).Diagram_backgroundColor,
264                 Bindings.getBindingUnchecked(RGB.Integer.class));
265     }
266     
267     public static Resource createNetworkDiagram(WriteGraph graph, Resource target, Resource compositeType, String defaultName, Resource defaultEdgeMapping, Resource defaultVertexMapping, Resource rightClickVertexMapping, Resource leftClickVertexMapping, Resource crs) throws DatabaseException {
268         Resource composite = NewCompositeActionFactory.createComposite(graph, target, defaultName, compositeType);
269
270         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
271         Resource diagram = graph.getSingleObject(composite, ModelingResources.getInstance(graph).CompositeToDiagram);
272         graph.claim(diagram, DN.EdgeDefaultMapping, defaultEdgeMapping);
273         graph.claim(diagram, DN.VertexDefaultMapping, defaultVertexMapping);
274         graph.claim(diagram, DN.RightClickDefaultMapping, rightClickVertexMapping);
275         graph.claim(diagram, DN.LeftClickDefaultMapping, leftClickVertexMapping);
276         graph.claim(diagram, DN.HasSpatialRefSystem, crs);
277         
278         // Generated name prefix from composite name
279         String compositeName = graph.getRelatedValue2(composite, Layer0.getInstance(graph).HasName, Bindings.STRING);
280         graph.claimLiteral(diagram, Layer0X.getInstance(graph).HasGeneratedNamePrefix, "N" + compositeName.substring(compositeName.length() - 1, compositeName.length()));
281         
282         return composite;
283     }
284
285     public static final class MappedComponentRequest extends ResourceRead<Resource> {
286         public MappedComponentRequest(Resource element) {
287             super(element);
288         }
289
290         @Override
291         public Resource perform(ReadGraph graph) throws DatabaseException {
292             return getMappedComponent(graph, resource);
293         }
294     }
295
296     public static class ResourceVertex {
297         
298         public final boolean isConsumer;
299         public final Resource vertex;
300         public final double[] coords;
301         
302         public ResourceVertex(Resource vertex, double[] coords, boolean isConsumer) {
303             this.vertex = vertex;
304             this.coords = coords;
305             this.isConsumer = isConsumer;
306         }
307     }
308     
309     public static void changeMappingType(WriteGraph graph, Resource newMapping, List<Resource> elements) throws DatabaseException {
310         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
311         for (Resource element : elements) {
312             graph.deny(element, DN.HasMapping);
313             graph.claim(element, DN.HasMapping, newMapping);
314         }
315     }
316
317     public static Stream<Resource> findDNElementsById(ReadGraph graph, Resource context, String idToFind) throws DatabaseException {
318         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph); 
319         return IndexUtils.findByType(graph,
320             graph.syncRequest(new IndexRoot(context)),
321             DN.Element
322         ).stream().filter(element -> {
323             try {
324                 String id = graph.getPossibleRelatedValue(element, DN.HasId, Bindings.STRING);
325                 return id != null && id.contains(idToFind);
326             } catch (DatabaseException e) {
327                 LOGGER.error("Could not read id for element {]", element, e);
328                 return false;
329             }
330         });
331     }
332     
333     public static Resource findDNElementById(ReadGraph graph, Resource context, String idToFind) throws DatabaseException {
334         List<Resource> elements = findDNElementsById(graph, context, idToFind).collect(Collectors.toList());
335         if (elements.size() == 1) {
336             return elements.iterator().next();
337         }
338         return null;
339     }
340     
341     public static List<Resource> findDNElementByXYCoordinates(ReadGraph graph, Resource context, double lat, double lon, double padding) throws DatabaseException {
342         DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
343         DiagramResource DIA = DiagramResource.getInstance(graph);
344         List<Resource> results = new ArrayList<>();
345         Collection<Resource> vertices = IndexUtils.findByType(graph, graph.syncRequest(new IndexRoot(context)), DN.Vertex);
346         Rectangle2D rect = new Rectangle2D.Double(lat, lon, padding, padding);
347         for (Resource vertex : vertices) {
348             double[] location = graph.getRelatedValue(vertex, DIA.HasLocation, Bindings.DOUBLE_ARRAY);
349             if (rect.contains(location[0], location[1])) {
350                 results.add(vertex);
351             }
352         }
353         return results;
354     }
355 }