Added new ExperimentRuns.createRun utility
[simantics/platform.git] / bundles / org.simantics.simulation / src / org / simantics / simulation / project / ExperimentRuns.java
1 package org.simantics.simulation.project;
2
3 import java.util.concurrent.atomic.AtomicReference;
4 import java.util.function.Consumer;
5
6 import org.simantics.databoard.Bindings;
7 import org.simantics.db.Resource;
8 import org.simantics.db.Session;
9 import org.simantics.db.VirtualGraph;
10 import org.simantics.db.WriteGraph;
11 import org.simantics.db.common.request.WriteRequest;
12 import org.simantics.db.common.request.WriteResultRequest;
13 import org.simantics.db.common.utils.NameUtils;
14 import org.simantics.db.exception.DatabaseException;
15 import org.simantics.db.service.VirtualGraphSupport;
16 import org.simantics.layer0.Layer0;
17 import org.simantics.scl.runtime.function.Function2;
18 import org.simantics.simulation.experiment.ExperimentState;
19 import org.simantics.simulation.experiment.IExperiment;
20 import org.simantics.simulation.experiment.IExperimentListener;
21 import org.simantics.simulation.ontology.SimulationResource;
22 import org.simantics.utils.ui.ErrorLogger;
23
24 /**
25  * Facade for handling experiment run modeling and experiment activation
26  * related tasks.
27  * 
28  * @author Tuukka Lehtonen
29  */
30 public class ExperimentRuns {
31
32     /**
33      * @param session
34      * @param experimentResource
35      * @param experiment
36      * @param listener
37      */
38     public static void createRun(Session session, Resource experimentResource, IExperiment experiment,
39             IExperimentActivationListener listener, Consumer<Resource> successCallback) {
40         VirtualGraphSupport support = session.getService(VirtualGraphSupport.class);
41         createRun(session, support.getWorkspacePersistent("experiments"), experimentResource, experiment, listener, successCallback);
42     }
43
44     /**
45      * Create new experiment run in a selected virtual graph.
46      * 
47      * @param session
48      * @param graph
49      * @param experimentResource
50      * @param experiment
51      * @param listener
52      */
53     public static void createRun(final Session session, VirtualGraph graph, final Resource experimentResource,
54             final IExperiment experiment, final IExperimentActivationListener listener,
55             final Consumer<Resource> successCallback)
56     {
57         createRun(session, graph, experimentResource, experiment, SimulationResource.URIs.Run, listener, successCallback);
58     }
59
60     public static void createRun(final Session session, VirtualGraph vg, final Resource experimentResource,
61             final IExperiment experiment, final String experimentRunTypeURI,
62             final IExperimentActivationListener listener, final Consumer<Resource> successCallback)
63     {
64         createRun(session, vg, experimentResource, experiment, experimentRunTypeURI, listener, null, successCallback);
65     }
66
67     /**
68      * Create new experiment run in a selected virtual graph.
69      * 
70      * @param session
71      * @param vg
72      * @param experimentResource
73      * @param experiment
74      * @param experimentRunTypeURI
75      * @param listener
76      * @param successCallback if non-null invoked with the created run resource
77      *        as an argument, just before invoking
78      *        listener.onExperimentActivated(experiment)
79      */
80     public static void createRun(final Session session, VirtualGraph vg, final Resource experimentResource,
81             final IExperiment experiment, final String experimentRunTypeURI,
82             final IExperimentActivationListener listener,
83             final Function2<WriteGraph, Resource, Object> externalWrite,
84             final Consumer<Resource> successCallback)
85     {
86         createRun(session, vg,
87                 experimentResource, experiment, experimentRunTypeURI,
88                 listener, externalWrite, successCallback, true);
89     }
90
91     /**
92      * Create new experiment run in a selected virtual graph.
93      * 
94      * @param session
95      * @param vg
96      * @param experimentResource
97      * @param experiment
98      * @param experimentRunTypeURI
99      * @param listener
100      * @param successCallback if non-null invoked with the created run resource
101      *        as an argument, just before invoking
102      *        listener.onExperimentActivated(experiment)
103      * @param attachDeactivationListener <code>true</code> to run for the created run-resource
104      *        {@link #attachStateListener(Session, IExperiment, Resource)}
105      */
106     public static void createRun(
107             Session session,
108             VirtualGraph vg,
109             Resource experimentResource,
110             IExperiment experiment,
111             String experimentRunTypeURI,
112             IExperimentActivationListener listener,
113             Function2<WriteGraph, Resource, Object> externalWrite,
114             Consumer<Resource> successCallback,
115             boolean attachDeactivationListener)
116     {
117         final AtomicReference<Resource> run = new AtomicReference<>();
118         session.asyncRequest(new WriteRequest(vg) {
119             @Override
120             public void perform(WriteGraph graph) throws DatabaseException {
121 //                System.out.println("ExperimentActivator " + experimentResource + " " + experiment.getIdentifier());
122                 run.set( createRun(graph, experimentResource, experiment, experimentRunTypeURI, externalWrite) );
123             }
124         }, e -> {
125             if (e != null) {
126                 if (listener != null)
127                     listener.onFailure(e);
128                 else
129                     ErrorLogger.defaultLogError(e);
130             } else {
131                 if (attachDeactivationListener)
132                     attachStateListener(session, experiment, run.get());
133                 if (successCallback != null)
134                     successCallback.accept(run.get());
135                 if (listener != null)
136                     listener.onExperimentActivated(experiment);
137             }
138         });
139     }
140
141     /**
142      * Create new experiment run in a selected virtual graph.
143      * 
144      * @param session
145      * @param vg
146      * @param experimentResource
147      * @param experiment
148      * @param experimentRunTypeURI
149      * @param listener
150      * @param successCallback if non-null invoked with the created run resource
151      *        as an argument, just before invoking
152      *        listener.onExperimentActivated(experiment)
153      */
154     public static Resource createRun(WriteGraph graph,
155             VirtualGraph vg, 
156             Resource experimentResource,
157             IExperiment experiment,
158             String experimentRunTypeURI,
159             Function2<WriteGraph, Resource, Object> externalWrite)
160                     throws DatabaseException
161     {
162         return graph.syncRequest(new WriteResultRequest<Resource>(vg) {
163             @Override
164             public Resource perform(WriteGraph graph) throws DatabaseException {
165                 return createRun(graph, experimentResource, experiment, experimentRunTypeURI, externalWrite);
166             }
167         });
168     }
169
170     public static Resource createRun(WriteGraph graph,
171             Resource experimentResource,
172             IExperiment experiment,
173             String experimentRunTypeURI,
174             Function2<WriteGraph, Resource, Object> externalWrite)
175                     throws DatabaseException
176     {
177         Layer0 L0 = Layer0.getInstance(graph);
178         SimulationResource SIMU = SimulationResource.getInstance(graph);
179
180         Resource run = graph.newResource();
181         String label = NameUtils.findFreshLabel(graph, "Experiment", experimentResource);
182         graph.claim(run, L0.InstanceOf, null, graph.getResource(experimentRunTypeURI));
183         graph.addLiteral(run, L0.HasName, L0.NameOf, L0.String, experiment.getIdentifier(), Bindings.STRING);
184         graph.addLiteral(run, L0.HasLabel, L0.HasLabel_Inverse, L0.String, label, Bindings.STRING);
185         graph.addLiteral(run, SIMU.HasActivationTime, SIMU.HasActivationTime_Inverse, L0.Long, System.currentTimeMillis(), Bindings.LONG);
186         graph.claim(experimentResource, L0.ConsistsOf, L0.PartOf, run);
187
188         markRunActive(graph, run, externalWrite);
189
190         return run;
191     }
192
193     /**
194      * Mark the run active in the transient virtual graph.
195      * 
196      * @param graph
197      * @param run
198      * @param externalWrite 
199      * @throws DatabaseException
200      */
201     private static void markRunActive(
202             WriteGraph graph,
203             Resource run,
204             Function2<WriteGraph, Resource, Object> externalWrite)
205                     throws DatabaseException
206     {
207         SimulationResource SIMU = SimulationResource.getInstance(graph);
208         VirtualGraph runtime = graph.getService(VirtualGraph.class);
209         graph.syncRequest(new WriteRequest(runtime) {
210             @Override
211             public void perform(WriteGraph graph) throws DatabaseException {
212                 graph.claim(run, SIMU.IsActive, run);
213                 if(externalWrite != null)
214                     externalWrite.apply(graph, run);
215             }
216         });
217     }
218
219     /**
220      * Add listener for tracking run IsActive state in the graph.
221      * 
222      * @param session
223      * @param experiment
224      * @param run
225      */
226     private static void attachStateListener(final Session session, IExperiment experiment, final Resource run) {
227         experiment.addListener(new IExperimentListener() {
228             @Override
229             public void stateChanged(ExperimentState state) {
230                 if (state == ExperimentState.DISPOSED) {
231                     VirtualGraph runtime = session.getService(VirtualGraph.class);
232                     session.asyncRequest(new WriteRequest(runtime) {
233                         @Override
234                         public void perform(WriteGraph graph) throws DatabaseException {
235                             SimulationResource SIMU = SimulationResource.getInstance(graph);
236                             graph.denyStatement(run, SIMU.IsActive, run);
237                         }
238                     }, e -> {
239                         if (e != null)
240                             ErrorLogger.defaultLogError(e);
241                     });
242                 }
243             }
244         });
245     }
246
247 }