]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.district.network/src/org/simantics/district/network/profile/ThrottledStyleBase.java
f820c9222a121537742df253be60889d7a3ee685
[simantics/district.git] / org.simantics.district.network / src / org / simantics / district / network / profile / ThrottledStyleBase.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2019 Association for Decentralized Information Management in
3  * Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     Semantum Oy - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.district.network.profile;
13
14 import java.util.Optional;
15 import java.util.concurrent.atomic.AtomicLong;
16
17 import org.simantics.databoard.Bindings;
18 import org.simantics.db.ReadGraph;
19 import org.simantics.db.Resource;
20 import org.simantics.db.common.request.UnaryRead;
21 import org.simantics.db.exception.DatabaseException;
22 import org.simantics.db.procedure.Listener;
23 import org.simantics.db.request.Read;
24 import org.simantics.diagram.profile.StyleBase;
25 import org.simantics.diagram.stubs.DiagramResource;
26 import org.simantics.district.network.ontology.DistrictNetworkResource;
27 import org.simantics.scenegraph.INode;
28 import org.simantics.scenegraph.profile.EvaluationContext;
29 import org.simantics.scenegraph.profile.Group;
30 import org.simantics.scenegraph.profile.Observer;
31 import org.simantics.scenegraph.profile.common.ObserverGroupListener;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 public abstract class ThrottledStyleBase<Result> extends StyleBase<Optional<Result>> {
36
37     private static final Logger LOGGER = LoggerFactory.getLogger(ThrottledStyleBase.class);
38     private static final long DEFAULT_INTERVAL = 2000;
39
40     //private long lastCalculateTimestamp = 0;
41     private AtomicLong interval = new AtomicLong(DEFAULT_INTERVAL);
42     private Listener<Optional<Result>> resultListener;
43
44     @Override
45     protected Read<Optional<Result>> getStyleCalculationRequest(Resource runtimeDiagram, Resource entry, Resource item) {
46         //Simantics.getSession().asyncRequest(new ProfileUpdateIntervalRead(runtimeDiagram), new ProfileUpdateIntervalListener(runtimeDiagram, entry, item)); 
47         return super.getStyleCalculationRequest(runtimeDiagram, entry, item);
48     }
49
50     @Override
51     protected Listener<Optional<Result>> getStyleResultListener(ObserverGroupListener groupListener, Resource item,
52             Group group, Observer observer, Resource runtimeDiagram) {
53         resultListener = super.getStyleResultListener(groupListener, item, group, observer, runtimeDiagram);
54         return resultListener;
55     }
56
57     @Override
58     public final Optional<Result> calculateStyle(ReadGraph graph, Resource runtimeDiagram, Resource entry,
59             Resource groupItem) throws DatabaseException {
60 // Needs fixing - this will result registration of listeners for nothing in the cache
61 //        long currentTimestamp = System.currentTimeMillis();
62 //        if (lastCalculateTimestamp > (currentTimestamp - interval.get())) {
63 //            LOGGER.debug("Throttling result calculation for {} {} {} {}", runtimeDiagram, entry, groupItem, interval.get());
64 //            return Optional.empty();
65 //        }
66 //        lastCalculateTimestamp = currentTimestamp;
67         // let's calculate
68         return Optional.ofNullable(calculateThrottledStyle(graph, runtimeDiagram, entry, groupItem));
69     }
70
71     public abstract Result calculateThrottledStyle(ReadGraph graph, Resource runtimeDiagram, Resource entry, Resource groupItem) throws DatabaseException;
72
73     @Override
74     public final void applyStyleForNode(EvaluationContext evaluationContext, INode node, Optional<Result> result) {
75         if (!result.equals(Optional.empty())) {
76             applyThrottledStyleForNode(evaluationContext, node, result.get());
77         } else {
78             LOGGER.debug("Do not apply as results are unchanged for {} {} {}", evaluationContext, node, result);
79         }
80     }
81
82     public abstract void applyThrottledStyleForNode(EvaluationContext evaluationContext, INode node, Result result);
83     
84     private static class ProfileUpdateIntervalRead extends UnaryRead<Resource, Long> {
85
86         public ProfileUpdateIntervalRead(Resource parameter) {
87             super(parameter);
88         }
89
90         @Override
91         public Long perform(ReadGraph graph) throws DatabaseException {
92             Resource configuration = graph.getPossibleObject(parameter, DiagramResource.getInstance(graph).RuntimeDiagram_HasConfiguration);
93             DistrictNetworkResource DN = DistrictNetworkResource.getInstance(graph);
94             Long interval = DEFAULT_INTERVAL;
95             if (configuration != null) {
96                 interval = graph.getPossibleRelatedValue(configuration, DN.Diagram_profileUpdateInterval, Bindings.LONG);
97             }
98             return interval != null ? interval : DEFAULT_INTERVAL;
99         }
100     }
101     
102     private class ProfileUpdateIntervalListener implements Listener<Long> {
103
104         private Resource runtimeDiagram;
105         private Resource entry;
106         private Resource item;
107
108         public ProfileUpdateIntervalListener(Resource runtimeDiagram, Resource entry, Resource item) {
109             this.runtimeDiagram = runtimeDiagram;
110             this.entry = entry;
111             this.item = item;
112         }
113
114         @Override
115         public void execute(Long result) {
116             interval.set(result);
117         }
118
119         @Override
120         public void exception(Throwable t) {
121             LOGGER.error("Could not listen interval from runtime diagram {}", runtimeDiagram, t);
122         }
123
124         @Override
125         public boolean isDisposed() {
126             return resultListener.isDisposed();
127         }
128
129         @Override
130         public int hashCode() {
131             final int prime = 31;
132             int result = 1;
133             result = prime * result + getEnclosingInstance().hashCode();
134             result = prime * result + ((entry == null) ? 0 : entry.hashCode());
135             result = prime * result + ((item == null) ? 0 : item.hashCode());
136             result = prime * result + ((runtimeDiagram == null) ? 0 : runtimeDiagram.hashCode());
137             return result;
138         }
139
140         @Override
141         public boolean equals(Object obj) {
142             if (this == obj)
143                 return true;
144             if (obj == null)
145                 return false;
146             if (getClass() != obj.getClass())
147                 return false;
148             ProfileUpdateIntervalListener other = (ProfileUpdateIntervalListener) obj;
149             if (!getEnclosingInstance().equals(other.getEnclosingInstance()))
150                 return false;
151             if (entry == null) {
152                 if (other.entry != null)
153                     return false;
154             } else if (!entry.equals(other.entry))
155                 return false;
156             if (item == null) {
157                 if (other.item != null)
158                     return false;
159             } else if (!item.equals(other.item))
160                 return false;
161             if (runtimeDiagram == null) {
162                 if (other.runtimeDiagram != null)
163                     return false;
164             } else if (!runtimeDiagram.equals(other.runtimeDiagram))
165                 return false;
166             return true;
167         }
168
169         private ThrottledStyleBase<Result> getEnclosingInstance() {
170             return ThrottledStyleBase.this;
171         }
172     }
173
174 }