1 package org.simantics.district.network;
3 import java.awt.geom.Rectangle2D;
4 import java.util.ArrayList;
5 import java.util.Collection;
6 import java.util.Iterator;
8 import java.util.stream.Collectors;
9 import java.util.stream.Stream;
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;
40 public class DistrictNetworkUtil {
42 private static final Logger LOGGER = LoggerFactory.getLogger(DistrictNetworkUtil.class);
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);
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);
55 Resource edge = graph.newResource();
56 graph.claim(edge, L0.InstanceOf, DN.Edge);
58 graph.claim(edge, DN.HasMapping, null, mapping);
60 OrderedSetUtils.addFirst(graph, composite, edge);
61 graph.claim(composite, L0.ConsistsOf, L0.PartOf, edge);
63 claimFreshElementName(graph, composite, edge);
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);
69 GraphLayer gl = layerUtil.loadLayer(graph, layer);
70 gl.forEachTag(tag -> {
71 DiagramGraphUtil.tag(graph, edge, tag, true);
75 // add detailed geometry (if any)
76 graph.claimLiteral(edge, DN.Edge_HasGeometry, detailedGeometryCoords, Bindings.DOUBLE_ARRAY);
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);
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);
94 graph.claim(vertex, DN.HasMapping, null, mapping);
96 OrderedSetUtils.add(graph, composite, vertex);
97 graph.claim(composite, L0.ConsistsOf, L0.PartOf, vertex);
99 claimFreshElementName(graph, composite, vertex);
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);
105 GraphLayer gl = layerUtil.loadLayer(graph, layer);
106 gl.forEachTag(tag -> {
107 DiagramGraphUtil.tag(graph, vertex, tag, true);
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);
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);
133 OrderedSetUtils.remove(graph, composite, slave);
134 // Remove ConsistsOf statement
135 graph.deny(composite, Layer0.getInstance(graph).ConsistsOf, slave);
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);
147 Resource crs = graph.getSingleObject(startComposite, DistrictNetworkResource.getInstance(graph).HasSpatialRefSystem);
149 CRS crsClass = graph.adapt(crs, CRS.class);
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);
154 return crsClass.calculateDistance(startCoords, endCoords);
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)
164 // Give running name to element and increment the counter attached to the diagram.
165 Long l = graph.getPossibleRelatedValue(diagram, DIA.HasModCount, Bindings.LONG);
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);
174 public static Resource getDiagramElement(ReadGraph graph, Resource component) throws DatabaseException {
175 if (component == null)
177 DiagramResource DIA = DiagramResource.getInstance(graph);
178 if (graph.isInstanceOf(component, DIA.Element))
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;
185 public static Resource getMappedElement(ReadGraph graph, Resource element) throws DatabaseException {
188 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
189 return graph.getPossibleObject(element, DN.MappedComponent);
192 public static Resource getMappedComponent(ReadGraph graph, Resource element) throws DatabaseException {
195 Resource mappedElement = getMappedElement(graph, element);
196 if (mappedElement == null)
198 ModelingResources MOD = ModelingResources.getInstance(graph);
199 return graph.getPossibleObject(mappedElement, MOD.ElementToComponent);
202 public static Resource getMappedComponentCached(ReadGraph graph, Resource vertex) throws DatabaseException {
203 return graph.syncRequest(new MappedComponentRequest(vertex), TransientCacheListener.instance());
206 public static Resource getMappedDNElement(ReadGraph graph, Resource element) throws DatabaseException {
209 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
210 return graph.getPossibleObject(element, DN.MappedFromElement);
213 public static Variable toMappedConfigurationModule(ReadGraph graph, Resource input) throws DatabaseException {
217 DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
218 if (graph.isInstanceOf(input, DN.Element)) {
219 Resource mappedElement = getMappedElement(graph, input);
220 if (mappedElement == null)
223 ModelingResources MOD = ModelingResources.getInstance(graph);
224 Resource mappedComponent = graph.getPossibleObject(mappedElement, MOD.ElementToComponent);
225 if (mappedComponent == null)
228 return graph.syncRequest(new PossibleVariable(mappedComponent));
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);
238 graph.claimLiteral(diagram, DN.Diagram_drawMapEnabled, !current, Bindings.BOOLEAN);
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;
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));
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));
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));
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);
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);
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()));
285 public static final class MappedComponentRequest extends ResourceRead<Resource> {
286 public MappedComponentRequest(Resource element) {
291 public Resource perform(ReadGraph graph) throws DatabaseException {
292 return getMappedComponent(graph, resource);
296 public static class ResourceVertex {
298 public final boolean isConsumer;
299 public final Resource vertex;
300 public final double[] coords;
302 public ResourceVertex(Resource vertex, double[] coords, boolean isConsumer) {
303 this.vertex = vertex;
304 this.coords = coords;
305 this.isConsumer = isConsumer;
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);
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)),
322 ).stream().filter(element -> {
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);
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();
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])) {