]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics/src/org/simantics/Simantics.java
Add support for dependency changes in SCL
[simantics/platform.git] / bundles / org.simantics / src / org / simantics / Simantics.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in 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  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics;
13
14 import java.io.File;
15 import java.util.UUID;
16 import java.util.concurrent.ScheduledFuture;
17 import java.util.concurrent.TimeUnit;
18
19 import org.eclipse.core.runtime.IProgressMonitor;
20 import org.eclipse.core.runtime.NullProgressMonitor;
21 import org.eclipse.core.runtime.Platform;
22 import org.simantics.SimanticsPlatform.OntologyRecoveryPolicy;
23 import org.simantics.SimanticsPlatform.RecoveryPolicy;
24 import org.simantics.application.arguments.IArguments;
25 import org.simantics.application.arguments.SimanticsArguments;
26 import org.simantics.db.ReadGraph;
27 import org.simantics.db.Resource;
28 import org.simantics.db.Session;
29 import org.simantics.db.WriteGraph;
30 import org.simantics.db.common.Indexing;
31 import org.simantics.db.common.procedure.adapter.ProcedureAdapter;
32 import org.simantics.db.exception.DatabaseException;
33 import org.simantics.db.exception.RuntimeDatabaseException;
34 import org.simantics.db.indexing.IndexUtils;
35 import org.simantics.db.layer0.util.SimanticsClipboard;
36 import org.simantics.db.layer0.util.SimanticsKeys;
37 import org.simantics.db.layer0.variable.Variable;
38 import org.simantics.db.layer0.variable.Variables;
39 import org.simantics.db.management.ISessionContext;
40 import org.simantics.db.management.ISessionContextProvider;
41 import org.simantics.db.management.ISessionContextProviderSource;
42 import org.simantics.db.management.SessionContextProvider;
43 import org.simantics.db.management.SingleSessionContextProviderSource;
44 import org.simantics.db.request.ReadInterface;
45 import org.simantics.db.request.WriteInterface;
46 import org.simantics.internal.FileServiceImpl;
47 import org.simantics.layer0.Layer0;
48 import org.simantics.project.IProject;
49 import org.simantics.project.ProjectKeys;
50 import org.simantics.scl.compiler.top.ValueNotFound;
51 import org.simantics.scl.osgi.SCLOsgi;
52 import org.simantics.scl.runtime.SCLContext;
53 import org.simantics.scl.runtime.function.Function;
54 import org.simantics.scl.runtime.function.Function1;
55 import org.simantics.scl.runtime.function.Function2;
56 import org.simantics.utils.FileService;
57 import org.simantics.utils.FileUtils;
58 import org.simantics.utils.TempFiles;
59 import org.simantics.utils.threads.ThreadUtils;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62
63 /**
64  * A facade for accessing basic Simantics platform services. Usable without a
65  * graphical UI, i.e. in headless contexts.
66  *
67  * TODO: in time, move headless functionality of SimanticsUI into this class but
68  * originals as delegates in SimanticsUI.
69  *
70  * TODO: duplicate of org.simantics.db.layer0.util.Simantics, do something about this!!
71  */
72 public class Simantics {
73     private static final Logger LOGGER = LoggerFactory.getLogger(Simantics.class);
74
75     /**
76      * Default database driver ID
77      */
78     private static final String DEFAULT_DATABASE_DRIVER_ID = "acorn";
79
80     private static String defaultDatabaseDriverId = DEFAULT_DATABASE_DRIVER_ID;
81
82     private static ISessionContextProviderSource providerSource = null;
83     private static volatile FileServiceImpl fileService = null;
84
85     /**
86      * Sets the database driver to be used by the platform. To have any effect,
87      * this must be set before platform startup.
88      * 
89      * @param id driver id
90      */
91     public static void setDefaultDatabaseDriver(String id) {
92         defaultDatabaseDriverId = id;
93     }
94
95     /**
96      * Returns currently set default database driver id.
97      */
98     public static String getDefaultDatabaseDriver() {
99         return defaultDatabaseDriverId;
100     }
101
102     /**
103      * @param args
104      * @param progress
105      * @return
106      * @throws PlatformException
107      */
108     public static ISessionContext startUpHeadless(IArguments args, IProgressMonitor progress) throws PlatformException {
109         if (SimanticsPlatform.INSTANCE.sessionContext != null) {
110             throw new RuntimeDatabaseException("Simantics is already up and running.");
111         }
112
113         RecoveryPolicy workspacePolicy = Platform.inDevelopmentMode() ? RecoveryPolicy.FixError : RecoveryPolicy.ThrowError;
114         OntologyRecoveryPolicy ontologyPolicy = Platform.inDevelopmentMode() ? OntologyRecoveryPolicy.Merge : OntologyRecoveryPolicy.ThrowError;
115
116         if (args.contains(SimanticsArguments.RECOVERY_POLICY_FIX_ERRORS)) {
117             workspacePolicy = RecoveryPolicy.FixError;
118             ontologyPolicy = OntologyRecoveryPolicy.Merge;
119         }
120
121         if (args.contains(SimanticsArguments.ONTOLOGY_RECOVERY_POLICY_REINSTALL)) {
122             ontologyPolicy = OntologyRecoveryPolicy.ReinstallDatabase;
123         }
124
125         if (args.contains(SimanticsArguments.ONTOLOGY_RECOVERY_POLICY_REINSTALL)) {
126             ontologyPolicy = OntologyRecoveryPolicy.ReinstallDatabase;
127         }
128
129         if (args.contains(SimanticsArguments.DISABLE_INDEX)) {
130             Indexing.setDefaultDependenciesIndexingEnabled(false);
131         }
132
133         String databaseDriverId = defaultDatabaseDriverId;
134         if (args.contains(SimanticsArguments.DATABASE_ID)) {
135             databaseDriverId = args.get(SimanticsArguments.DATABASE_ID);
136             Simantics.setDefaultDatabaseDriver(databaseDriverId);
137         }
138
139         int localPort = 0;
140         if (args.contains(SimanticsArguments.LOCAL_SERVER_PORT)) {
141             try {
142                 localPort = args.get(SimanticsArguments.LOCAL_SERVER_PORT);
143             } catch (IllegalArgumentException e) {
144                 throw new PlatformException("Failed to open database session", e);
145             }
146         }
147
148 //        ServerAddress remoteDatabase = null;
149 //        if (args.contains(SimanticsArguments.SERVER)) {
150 //            String serverAddress = args.get(SimanticsArguments.SERVER);
151 //            try {
152 //                remoteDatabase = new ServerAddress(serverAddress);
153 //            } catch (IllegalArgumentException e) {
154 //                throw new PlatformException("Failed to open database session", e);
155 //            }
156 //        }
157
158         return startUpHeadless(progress, workspacePolicy, ontologyPolicy, localPort, databaseDriverId /*, remoteDatabase*/);
159     }
160
161     /**
162      * @param progress
163      * @param workspacePolicy
164      * @param ontologyPolicy
165      * @param localPort
166      * @param remoteDatabase
167      * @return
168      * @throws PlatformException
169      */
170     public static ISessionContext startUpHeadless(IProgressMonitor progress, RecoveryPolicy workspacePolicy, OntologyRecoveryPolicy ontologyPolicy, int localPort, String databaseDriverId) throws PlatformException {
171         if (SimanticsPlatform.INSTANCE.sessionContext != null) {
172             throw new RuntimeDatabaseException("Simantics is already up and running.");
173         }
174
175         // Set session context provider.
176         final ISessionContextProvider provider = new SessionContextProvider(null);
177         ISessionContextProviderSource source = new SingleSessionContextProviderSource(provider);
178         setSessionContextProviderSource(source);
179         org.simantics.db.layer0.internal.SimanticsInternal.setSessionContextProviderSource(source);
180
181         if (progress == null)
182             progress = new NullProgressMonitor();
183         return SimanticsPlatform.INSTANCE.startUp(databaseDriverId, progress, workspacePolicy, ontologyPolicy, true, new ConsoleUserAgent());
184     }
185
186     /**
187      * @param progress
188      * @throws PlatformException
189      */
190     public static void shutdown(IProgressMonitor progress) throws PlatformException {
191         SimanticsPlatform.INSTANCE.shutdown(progress);
192     }
193
194     /**
195      * Queue execution of a runnable.
196      *
197      * @param runnable
198      */
199     public static void async(Runnable runnable) {
200         ThreadUtils.getBlockingWorkExecutor().execute(runnable);
201     }
202
203     public static void async(Runnable runnable, int delay, TimeUnit unit) {
204         ThreadUtils.getTimer().schedule(runnable, delay, unit);
205     }
206
207     public static ScheduledFuture<?> scheduleAtFixedRate(Runnable runnable, int initialDelay, int period, TimeUnit unit) {
208         return ThreadUtils.getTimer().scheduleAtFixedRate(runnable, initialDelay, period, unit);
209     }
210
211     /**
212      * Queue execution of a non-blocking runnable. Use this method with caution.
213      * A non-blocking runnable nevers locks anything, No Locks, No semaphores,
214      * No Object.wait(), No synchronized() {} blocks.
215      *
216      * @param runnable a non-blocking runnable
217      */
218     public static void asyncNonblocking(Runnable runnable) {
219         ThreadUtils.getNonBlockingWorkExecutor().execute(runnable);
220     }
221
222     /**
223      * Schedule execution of a non-blocking runnable. Use this method with caution.
224      * A non-blocking runnable never locks anything, No Locks, No semaphores,
225      * No Object,wait(), No synchronized() {} blocks.
226      *
227      * @param runnable a non-blocking runnable
228      * @param initialDelay
229      * @param period
230      */
231     public static void asyncNonblocking(Runnable runnable, int initialDelay, int period) {
232         ThreadUtils.getNonBlockingWorkExecutor().scheduleAtFixedRate(runnable, initialDelay, period, TimeUnit.MILLISECONDS);
233     }
234
235     public static synchronized ISessionContext setSessionContext(ISessionContext ctx) {
236         return getSessionContextProvider().setSessionContext(ctx);
237     }
238
239     public static void setSessionContextProviderSource(ISessionContextProviderSource source) {
240         if (source == null)
241             throw new IllegalArgumentException("null provider source");
242         providerSource = source;
243     }
244
245     public static ISessionContextProviderSource getProviderSource() {
246         if (providerSource == null)
247             throw new IllegalStateException(
248             "providerSource must be initialized by the application before using class Simantics");
249         return providerSource;
250     }
251
252     public static ISessionContextProvider getSessionContextProvider() {
253         return getProviderSource().getActive();
254     }
255
256     /**
257      * Returns the database session context associated with the currently active
258      * context. This method should be used to retrieve session contexts only
259      * when the client is sure that the correct context is active.
260      *
261      * @return the session context associated with the currently active context
262      *         or <code>null</code> if the context has no session context
263      */
264     public static ISessionContext getSessionContext() {
265         ISessionContextProvider provider = getSessionContextProvider();
266         return provider != null ? provider.getSessionContext() : null;
267     }
268
269     /**
270      * Returns the database Session bound to the currently active context.
271      *
272      * <p>
273      * The method always returns a non-null Session or produces an
274      * IllegalStateException if a Session was not attainable.
275      * </p>
276      *
277      * @return the Session bound to the currently active workbench window
278      * @throws IllegalStateException if no Session was available
279      */
280     public static Session getSession() {
281         ISessionContext ctx = getSessionContext();
282         if (ctx == null)
283             throw new IllegalStateException("Session unavailable, no database session open");
284         return ctx.getSession();
285     }
286
287     /**
288      * Returns the database Session bound to the currently active context.
289      * Differently from {@link #getSession()}, this method returns
290      * <code>null</code> if there is no current Session available.
291      *
292      * @see #getSession()
293      * @return the Session bound to the currently active context or
294      *         <code>null</code>
295      */
296     public static Session peekSession() {
297         ISessionContext ctx = getSessionContext();
298         return ctx == null ? null : ctx.peekSession();
299     }
300
301     /**
302      * @return the currently open and active project as a Resource
303      * @throws IllegalStateException if there is no currently active database
304      *         session, which also means there is no active project at the
305      *         moment
306      */
307     public static Resource getProjectResource() {
308         ISessionContext ctx = getSessionContext();
309         if (ctx == null)
310             throw new IllegalStateException("No current database session");
311         Resource project = ctx.getHint(SimanticsKeys.KEY_PROJECT);
312         if (project == null)
313             throw new IllegalStateException("No current project resource in session context " + ctx);
314         return project;
315     }
316
317     /**
318      * @return the currently open and active project as a {@link Resource}
319      */
320     public static Resource peekProjectResource() {
321         ISessionContext ctx = getSessionContext();
322         return ctx != null ? ctx.<Resource>getHint(SimanticsKeys.KEY_PROJECT) : null;
323     }
324
325     /**
326      * @return the currently open and active project as an {@link IProject}
327      * @throws IllegalStateException if there is no currently active database
328      *         session, which also means there is no active project at the
329      *         moment
330      */
331     public static IProject getProject() {
332         ISessionContext ctx = getSessionContext();
333         if (ctx == null)
334             throw new IllegalStateException("No current database session");
335         IProject project = ctx.getHint(ProjectKeys.KEY_PROJECT);
336         if (project == null)
337             throw new IllegalStateException("No current project in session context " + ctx);
338         return project;
339     }
340
341     /**
342      * @return the currently open and active project as an {@link IProject} or
343      *         <code>null</code> if there is no active session or project
344      */
345     public static IProject peekProject() {
346         ISessionContext ctx = getSessionContext();
347         return ctx == null ? null : ctx.<IProject>getHint(ProjectKeys.KEY_PROJECT);
348     }
349
350     // FIXME: once org.simantics.db.layer0.util.Simantics is gone, re-enable this
351 //    private static SimanticsClipboard clipboard = SimanticsClipboard.EMPTY;
352
353     /**
354      * @param content
355      */
356     public static void setClipboard(SimanticsClipboard content) {
357         // FIXME: once org.simantics.db.layer0.util.Simantics is gone, re-enable this
358 //        if (content == null)
359 //            throw new NullPointerException("null clipboard content");
360 //        clipboard = content;
361         org.simantics.db.layer0.internal.SimanticsInternal.setClipboard(content);
362     }
363
364     public static SimanticsClipboard getClipboard() {
365         // FIXME: once org.simantics.db.layer0.util.Simantics is gone, re-enable this
366         //return clipboard;
367         return org.simantics.db.layer0.internal.SimanticsInternal.getClipboard();
368     }
369
370     public static Layer0 getLayer0() throws DatabaseException {
371         return Layer0.getInstance(getSession());
372     }
373
374     public static <T> T sync(ReadInterface<T> r) throws DatabaseException {
375         return getSession().sync(r);
376     }
377
378     public static <T> T sync(WriteInterface<T> r) throws DatabaseException {
379         return getSession().sync(r);
380     }
381
382     public static <T> void async(ReadInterface<T> r) {
383         getSession().async(r, new ProcedureAdapter<T>());
384     }
385
386     public static <T> void async(WriteInterface<T> r) {
387         getSession().async(r);
388     }
389
390     public static void clearTemporaryDirectory() {
391         FileUtils.deleteDir(getTemporaryDirectory());
392     }
393
394     public static File getTempfile(String directory, String suffix) {
395         File dir = getTemporaryDirectory(directory);
396         return new File(dir, UUID.randomUUID().toString() + "." + suffix);
397     }
398
399     public static File getTemporaryDirectory(String directory) {
400         File sub = new File(getTemporaryDirectory(), directory);
401         sub.mkdirs();
402         return sub;
403     }
404
405     public static File getTemporaryDirectory() {
406         File workspace = Platform.getLocation().toFile();
407         File temp = new File(workspace, "tempFiles");
408         temp.mkdirs();
409         return temp;
410     }
411
412     public static TempFiles getTempFiles() {
413         return TEMP_FILES;
414     }
415
416     private static class TempFilesImpl implements TempFiles {
417         private final TempFilesImpl parent;
418         private final String prefix;
419         private final String fullPrefix;
420
421         private TempFilesImpl(TempFilesImpl parent, String directory) {
422             this.parent = parent;
423             this.prefix = directory;
424             this.fullPrefix = getPrefix(new StringBuilder()).toString();
425         }
426
427         private StringBuilder getPrefix(StringBuilder sb) {
428             if (parent != null)
429                 parent.getPrefix(sb);
430             if (prefix != null && !prefix.isEmpty())
431                 sb.append(prefix).append(File.separatorChar);
432             return sb;
433         }
434
435         @Override
436         public File getRoot() {
437             return Simantics.getTemporaryDirectory(fullPrefix);
438         }
439
440         @Override
441         public File getTempfile(String directory, String suffix) {
442             return Simantics.getTempfile(fullPrefix.isEmpty() ? directory : fullPrefix + directory, suffix);
443         }
444
445         @Override
446         public TempFiles subdirectory(String directory) {
447             return new TempFilesImpl(this, directory);
448         }
449     }
450
451     public static TempFiles TEMP_FILES = new TempFilesImpl(null, null);
452
453     public static void flushIndexCaches(IProgressMonitor progress, Session session) {
454         try {
455             IndexUtils.flushIndexCaches(progress, session);
456         } catch (Exception e) {
457             LOGGER.error("Flushing index caches failed.", e);
458         }
459     }
460
461
462     @SuppressWarnings({ "unchecked", "rawtypes" })
463     public static <T> T applySCL(String module, String function, Object ... args) throws DatabaseException {
464         try {
465             T t = (T)((Function)SCLOsgi.MODULE_REPOSITORY.getValue(module, function)).applyArray(args);
466             return t;
467         } catch (ValueNotFound e) {
468             throw new DatabaseException("SCL Value not found: " + e.name);
469         } catch (Throwable t) {
470             throw new DatabaseException(t);
471         }
472     }
473
474     @SuppressWarnings({ "unchecked", "rawtypes" })
475     public static <T> T applySCL(String module, String function, ReadGraph graph, Object ... args) throws DatabaseException {
476         SCLContext sclContext = SCLContext.getCurrent();
477         Object oldGraph = sclContext.put("graph", graph);
478         try {
479             return applySCL(module, function, args);
480         } catch (DatabaseException dbe) {
481             throw dbe;
482         } catch (Throwable t) {
483             throw new DatabaseException(t);
484         } finally {
485             sclContext.put("graph", oldGraph);
486         }
487     }
488
489     @SuppressWarnings("unchecked")
490     public static <T> T applySCLWrite(WriteGraph graph, @SuppressWarnings("rawtypes") Function f, Object ... args) throws DatabaseException {
491         SCLContext sclContext = SCLContext.getCurrent();
492         Object oldGraph = sclContext.put("graph", graph);
493         try {
494             return (T)f.applyArray(args);
495         } catch (Throwable t) {
496             throw new DatabaseException(t);
497         } finally {
498             sclContext.put("graph", oldGraph);
499         }
500     }
501
502     @SuppressWarnings("unchecked")
503     public static <T> T applySCLRead(ReadGraph graph, @SuppressWarnings("rawtypes") Function f, Object ... args) throws DatabaseException {
504         SCLContext sclContext = SCLContext.getCurrent();
505         Object oldGraph = sclContext.put("graph", graph);
506         try {
507             return (T)f.applyArray(args);
508         } catch (Throwable t) {
509             throw new DatabaseException(t);
510         } finally {
511             sclContext.put("graph", oldGraph);
512         }
513     }
514     
515     public static <P0,R> R applySCLWrite(WriteGraph graph, Function1<P0,R> function, P0 p0) throws DatabaseException {
516         SCLContext sclContext = SCLContext.getCurrent();
517         Object oldGraph = sclContext.put("graph", graph);
518         try {
519             return function.apply(p0);
520         } catch (Throwable t) {
521             throw new DatabaseException(t);
522         } finally {
523             sclContext.put("graph", oldGraph);
524         }
525     }
526
527     public static <P0,R> R applySCLRead(ReadGraph graph, Function1<P0,R> function, P0 p0) throws DatabaseException {
528         SCLContext sclContext = SCLContext.getCurrent();
529         Object oldGraph = sclContext.put("graph", graph);
530         try {
531             return function.apply(p0);
532         } catch (Throwable t) {
533             throw new DatabaseException(t);
534         } finally {
535             sclContext.put("graph", oldGraph);
536         }
537     }
538
539     public static <P0,P1,R> R applySCLRead(ReadGraph graph, Function2<P0,P1,R> function, P0 p0, P1 p1) throws DatabaseException {
540         SCLContext sclContext = SCLContext.getCurrent();
541         Object oldGraph = sclContext.put("graph", graph);
542         try {
543             return function.apply(p0, p1);
544         } catch (Throwable t) {
545             throw new DatabaseException(t);
546         } finally {
547             sclContext.put("graph", oldGraph);
548         }
549     }
550
551     public static <P0,R> R invokeSCLWrite(WriteGraph graph, Variable property, P0 p0) throws DatabaseException {
552         Function1<P0,R> fn = property.getPossibleValue(graph);
553         if(fn == null) throw new DatabaseException("No function for " + property.getURI(graph));
554         return Simantics.applySCLWrite(graph, fn, p0);
555     }
556
557     public static <P0,R> R invokeSCL(ReadGraph graph, Variable property, P0 p0) throws DatabaseException {
558         Function1<P0,R> fn = property.getPossibleValue(graph);
559         if(fn == null) throw new DatabaseException("No function for " + property.getURI(graph));
560         return Simantics.applySCLRead(graph, fn, p0);
561     }
562
563     public static <P0,P1,R> R invokeSCL(ReadGraph graph, Variable property, P0 p0, P1 p1) throws DatabaseException {
564         Function2<P0,P1,R> fn = property.getPossibleValue(graph);
565         if(fn == null) throw new DatabaseException("No function for " + property.getURI(graph));
566         return Simantics.applySCLRead(graph, fn, p0, p1);
567     }
568
569     public static <P0,R> R invokeSCLWrite(WriteGraph graph, Resource entity, Resource property, P0 p0) throws DatabaseException {
570         return invokeSCLWrite(graph, getProperty(graph, entity, property), p0);
571     }
572
573     public static <P0,R> R invokeSCL(ReadGraph graph, Resource entity, Resource property, P0 p0) throws DatabaseException {
574         return invokeSCL(graph, getProperty(graph, entity, property), p0);
575     }
576
577     public static <P0,P1,R> R invokeSCL(ReadGraph graph, Resource entity, Resource property, P0 p0, P1 p1) throws DatabaseException {
578         return invokeSCL(graph, getProperty(graph, entity, property), p0, p1);
579     }
580
581         public static <P0,R> R tryInvokeSCL(ReadGraph graph, Resource entity, Resource property, P0 p0) throws DatabaseException {
582         Variable p = Variables.tryGetProperty(graph, entity, property);
583         if (p == null)
584                 return null;
585         return invokeSCL(graph, p, p0);
586     }
587
588         public static <P0,P1,R> R tryInvokeSCL(ReadGraph graph, Resource entity, Resource property, P0 p0, P1 p1) throws DatabaseException {
589         Variable p = Variables.tryGetProperty(graph, entity, property);
590         if (p == null)
591                 return null;
592         return invokeSCL(graph, p, p0, p1);
593     }
594
595         private static Variable getProperty(ReadGraph graph, Resource entity, Resource property) throws DatabaseException {
596         return Variables.getVariable(graph, entity).getProperty(graph, property);
597     }
598
599     public static boolean ensureMemoryBytes(long bytes) {
600
601         Runtime runtime = Runtime.getRuntime();
602         long consumedMemory = runtime.totalMemory() - runtime.freeMemory();
603         long available = runtime.maxMemory() - consumedMemory;
604
605         return available > bytes;
606
607     }
608
609     public static long getDiskBytes() {
610
611         File ws = new File(Platform.getInstanceLocation().getURL().getFile());
612         return ws.getUsableSpace();
613
614     }
615
616     /**
617      * @return a service for dealing with recurring file system handling cases
618      */
619     public static FileService getFileService() {
620         FileService fs = fileService;
621         if (fs == null) {
622             synchronized (Simantics.class) {
623                 fs = fileService;
624                 if (fs == null)
625                     fs = fileService = new FileServiceImpl();
626             }
627         }
628         return fs;
629     }
630
631 }