00df313ad4e34eaed68253b4ccc93640f52d1c79
[simantics/platform.git] / bundles / org.simantics.scl.db / src / org / simantics / scl / db / SCLFunctions.java
1 package org.simantics.scl.db;
2
3 import java.io.IOException;
4
5 import org.cojen.classfile.TypeDesc;
6 import org.simantics.Simantics;
7 import org.simantics.db.ReadGraph;
8 import org.simantics.db.Resource;
9 import org.simantics.db.VirtualGraph;
10 import org.simantics.db.WriteGraph;
11 import org.simantics.db.common.procedure.adapter.TransientCacheAsyncListener;
12 import org.simantics.db.common.request.BinaryRead;
13 import org.simantics.db.common.request.DelayedWriteRequest;
14 import org.simantics.db.common.request.ReadRequest;
15 import org.simantics.db.common.request.WriteRequest;
16 import org.simantics.db.common.request.WriteResultRequest;
17 import org.simantics.db.exception.DatabaseException;
18 import org.simantics.db.layer0.util.Layer0Utils;
19 import org.simantics.db.layer0.variable.Variables;
20 import org.simantics.db.request.Read;
21 import org.simantics.db.service.ClusterControl;
22 import org.simantics.db.service.SerialisationSupport;
23 import org.simantics.db.service.VirtualGraphSupport;
24 import org.simantics.layer0.utils.triggers.IActivationManager;
25 import org.simantics.scl.compiler.environment.specification.EnvironmentSpecification;
26 import org.simantics.scl.compiler.errors.Failable;
27 import org.simantics.scl.compiler.internal.codegen.types.JavaTypeTranslator;
28 import org.simantics.scl.compiler.module.Module;
29 import org.simantics.scl.compiler.module.repository.ImportFailureException;
30 import org.simantics.scl.compiler.runtime.RuntimeEnvironment;
31 import org.simantics.scl.compiler.types.Type;
32 import org.simantics.scl.osgi.SCLOsgi;
33 import org.simantics.scl.runtime.SCLContext;
34 import org.simantics.scl.runtime.function.Function;
35 import org.simantics.scl.runtime.function.Function1;
36 import org.simantics.scl.runtime.tuple.Tuple0;
37 import org.simantics.utils.DataContainer;
38
39 @SuppressWarnings({"rawtypes", "unchecked"})
40 public class SCLFunctions {
41
42     public static final String GRAPH = "graph";
43
44     public static <T> T safeExec(final Function f) {
45         try {
46             return (T)f.apply(Tuple0.INSTANCE);
47         } catch (Throwable t) {
48             t.printStackTrace();
49             return null;
50         }
51     }
52     
53     public static void asyncRead(final Function f) throws DatabaseException {
54         final SCLContext context = SCLContext.getCurrent();
55         Object graph = context.get(GRAPH);
56         if (graph != null) {
57             f.apply(Tuple0.INSTANCE);
58         } else {
59             Simantics.getSession().asyncRequest(new ReadRequest() {
60                 @Override
61                 public void run(ReadGraph graph) throws DatabaseException {
62                     SCLContext.push(context);
63                     ReadGraph oldGraph = (ReadGraph)context.put(GRAPH, graph);
64                     try {
65                         f.apply(Tuple0.INSTANCE);
66                     } finally {
67                         context.put(GRAPH, oldGraph);
68                         SCLContext.pop();
69                     }
70                 }
71             });
72         }
73     }
74     
75     public static <T> T syncRead(final Function f) throws DatabaseException {
76         final SCLContext context = SCLContext.getCurrent();
77         Object graph = context.get(GRAPH);
78         if (graph != null) {
79             return (T)f.apply(Tuple0.INSTANCE);
80         } else {
81             return Simantics.getSession().syncRequest(new Read<T>() {
82                 @Override
83                 public T perform(ReadGraph graph) throws DatabaseException {
84                     SCLContext.push(context);
85                     ReadGraph oldGraph = (ReadGraph)context.put(GRAPH, graph);
86                     try {
87                         return (T)f.apply(Tuple0.INSTANCE);
88                     } finally {
89                         context.put(GRAPH, oldGraph);
90                         SCLContext.pop();
91                     }
92                 }
93             });
94         }
95     }
96     
97     public static void asyncWrite(final Function f) throws DatabaseException {
98         final SCLContext context = SCLContext.getCurrent();
99         Object graph = context.get(GRAPH);
100         if (graph != null) {
101             f.apply(Tuple0.INSTANCE);
102         } else {
103             Simantics.getSession().asyncRequest(new WriteRequest() {
104                 @Override
105                 public void perform(WriteGraph graph) throws DatabaseException {
106                     SCLContext.push(context);
107                     ReadGraph oldGraph = (ReadGraph)context.put(GRAPH, graph);
108                     try {
109                         f.apply(Tuple0.INSTANCE);
110                     } finally {
111                         context.put(GRAPH, oldGraph);
112                         SCLContext.pop();
113                     }
114                 }
115             });
116         }
117     }
118     
119     public static <T> T syncWrite(final Function f) throws DatabaseException {
120         final SCLContext context = SCLContext.getCurrent();
121         Object graph = context.get(GRAPH);
122         if (graph != null) {
123             return (T)f.apply(Tuple0.INSTANCE);
124         } else {
125             return Simantics.getSession().syncRequest(new WriteResultRequest<T>() {
126                 @Override
127                 public T perform(WriteGraph graph) throws DatabaseException {
128                     SCLContext.push(context);
129                     ReadGraph oldGraph = (ReadGraph)context.put(GRAPH, graph);
130                     try {
131                         return (T)f.apply(Tuple0.INSTANCE);
132                     } finally {
133                         context.put(GRAPH, oldGraph);
134                         SCLContext.pop();
135                     }
136                 }
137             });
138         }
139     }
140     
141     public static <T> T delayedSyncWrite(final Function f) throws DatabaseException {
142         final SCLContext context = SCLContext.getCurrent();
143         final DataContainer<T> dc = new DataContainer<T>(null);
144
145         DelayedWriteRequest request = new DelayedWriteRequest() {
146             @Override
147             public void perform(WriteGraph graph) throws DatabaseException {
148                 final SCLContext context = SCLContext.getCurrent();
149                 SCLContext.push(context);
150                 ReadGraph oldGraph = (ReadGraph)context.put(GRAPH, graph);
151                 try {
152                     dc.set((T)f.apply(Tuple0.INSTANCE));
153                 } finally {
154                     context.put(GRAPH, oldGraph);
155                     SCLContext.pop();
156                 }
157             }
158         };
159         
160         Object graph = context.get(GRAPH);
161         if (graph != null) {
162             if (graph instanceof WriteGraph) {
163                 ((WriteGraph)graph).syncRequest(request);
164             } else {
165                 throw new DatabaseException("Caller is inside a read transaction.");
166             }
167         } else {
168             Simantics.getSession().syncRequest(request);
169         }
170         return dc.get();
171     }
172
173     public static <T> T virtualSyncWriteMem(WriteGraph graph, String virtualGraphId, final Function f) throws DatabaseException {
174         final SCLContext context = SCLContext.getCurrent();
175         VirtualGraphSupport vgs = graph.getService(VirtualGraphSupport.class);
176         VirtualGraph vg = vgs.getMemoryPersistent(virtualGraphId);
177         return graph.syncRequest(new WriteResultRequest<T>(vg) {
178             @Override
179             public T perform(WriteGraph graph) throws DatabaseException {
180                 SCLContext.push(context);
181                 ReadGraph oldGraph = (ReadGraph)context.put(GRAPH, graph);
182                 try {
183                     return (T)f.apply(Tuple0.INSTANCE);
184                 } finally {
185                     context.put(GRAPH, oldGraph);
186                     SCLContext.pop();
187                 }
188             }
189         });
190     }
191     
192     public static <T> T virtualSyncWriteWS(WriteGraph graph, String virtualGraphId, final Function f) throws DatabaseException {
193         final SCLContext context = SCLContext.getCurrent();
194         VirtualGraphSupport vgs = graph.getService(VirtualGraphSupport.class);
195         VirtualGraph vg = vgs.getWorkspacePersistent(virtualGraphId);
196         return graph.syncRequest(new WriteResultRequest<T>(vg) {
197             @Override
198             public T perform(WriteGraph graph) throws DatabaseException {
199                 SCLContext.push(context);
200                 ReadGraph oldGraph = (ReadGraph)context.put(GRAPH, graph);
201                 try {
202                     return (T)f.apply(Tuple0.INSTANCE);
203                 } finally {
204                     context.put(GRAPH, oldGraph);
205                     SCLContext.pop();
206                 }
207             }
208         });
209     }
210     
211     public static <T> T readValue(final String uri) throws DatabaseException {
212         return Simantics.getSession().syncRequest(new Read<T>() {
213             @Override
214             public T perform(ReadGraph graph) throws DatabaseException {
215                 return Variables.getVariable(graph, uri).getValue(graph);
216             }            
217         });
218     }
219     
220     public static <T> void writeValue(final String uri, final T value) throws DatabaseException {
221         Simantics.getSession().syncRequest(new WriteRequest() {
222             @Override
223             public void perform(WriteGraph graph) throws DatabaseException {
224                 Variables.getVariable(graph, uri).setValue(graph, value);
225             }            
226         });
227     }
228     
229     public static void activateOnce(Resource r) {
230         Simantics.getSession().getService(IActivationManager.class).activateOnce(r);
231     }
232     
233     public static void syncActivateOnce(WriteGraph graph, Resource r) throws DatabaseException {
234         graph.getService(IActivationManager.class).activateOnce(graph, r);
235     }
236
237     public static Resource resourceFromId(ReadGraph graph, long id) throws DatabaseException, IOException {
238         SerialisationSupport ss = graph.getService(SerialisationSupport.class);
239         return ss.getResource(id);
240     }
241     
242     public static void disableDependencies(WriteGraph graph) {
243         Layer0Utils.setDependenciesIndexingDisabled(graph, true);       
244     }
245     
246     public static void enableDependencies(WriteGraph graph) {
247         Layer0Utils.setDependenciesIndexingDisabled(graph, false);       
248     }
249     
250     public static void collectClusters() {
251         Simantics.getSession().getService(ClusterControl.class).collectClusters(Integer.MAX_VALUE);
252     }
253     
254     public static class SCLUnaryRead extends BinaryRead<Function1<Object,Object>, Object, Object> {
255
256                 public SCLUnaryRead(Function1<Object, Object> parameter1, Object parameter2) {
257                         super(parameter1, parameter2);
258                 }
259
260                 @Override
261                 public Object perform(ReadGraph graph) throws DatabaseException {
262                         return Simantics.applySCLRead(graph, parameter, parameter2);
263                 }
264         
265     }
266     
267     public static Object unaryQuery(ReadGraph graph, Function1<Object,Object> fn, Object value) throws DatabaseException {
268         return graph.syncRequest(new SCLUnaryRead(fn, value));
269     }
270
271     public static Object unaryQueryCached(ReadGraph graph, Function1<Object,Object> fn, Object value) throws DatabaseException {
272         return graph.syncRequest(new SCLUnaryRead(fn, value), TransientCacheAsyncListener.<Object>instance());
273     }
274     
275
276     private static class Subquery implements Read<Object> {
277         Function q;
278
279         public Subquery(Function q) {
280             this.q = q;
281         }
282
283         @Override
284         public Object perform(ReadGraph graph) throws DatabaseException {
285             SCLContext sclContext = SCLContext.getCurrent();
286             Object oldGraph = sclContext.put("graph", graph);
287             try {
288                 return q.apply(Tuple0.INSTANCE);
289             } catch (Throwable e) {
290                 if(e instanceof DatabaseException)
291                     throw (DatabaseException)e;
292                 else
293                     throw new DatabaseException(e);
294             } finally {
295                 sclContext.put("graph", oldGraph);
296             }
297         }
298
299         @Override
300         public int hashCode() {
301             return q.hashCode();
302         }
303         
304         @Override
305         public boolean equals(Object obj) {
306             if(this == obj)
307                 return true;
308             if(obj == null || obj.getClass() != getClass())
309                 return false;
310             Subquery other = (Subquery)obj;
311             return q.equals(other.q);
312         }
313     }
314
315     public static Object subquery(ReadGraph graph, Function q) throws DatabaseException {
316         return graph.syncRequest(new Subquery(q));
317     }
318
319     public static Object subqueryC(ReadGraph graph, Function q) throws DatabaseException {
320         return graph.syncRequest(new Subquery(q), TransientCacheAsyncListener.<Object>instance());
321     }
322
323     public static Object possibleFromDynamic(Type expectedType, String moduleName, Object value) {
324         
325         try {
326
327                 
328             Failable<Module> failable = SCLOsgi.MODULE_REPOSITORY.getModule(moduleName);
329             Module module = failable.getResult();
330             
331                 RuntimeEnvironment env = SCLOsgi.MODULE_REPOSITORY.createRuntimeEnvironment(
332                                 EnvironmentSpecification.of(moduleName, ""), module.getParentClassLoader());
333
334             JavaTypeTranslator tr = new JavaTypeTranslator(env.getEnvironment());
335             TypeDesc desc = tr.toTypeDesc(expectedType);
336             String className = desc.getFullName();
337             Class<?> clazz = env.getMutableClassLoader().loadClass(className);
338             if (!clazz.isAssignableFrom(value.getClass()))
339                 return null;
340             
341         } catch (ImportFailureException | ClassNotFoundException e) {
342         }
343         return value;
344     }
345
346 }