]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics/src/org/simantics/Simantics.java
9a1a354f17131b35e1fbfd7bfcc0565645b95616
[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, ReadGraph graph, Object ... args) throws DatabaseException {
464         SCLContext sclContext = SCLContext.getCurrent();
465             Object oldGraph = sclContext.put("graph", graph);
466                 try {
467                         T t = (T)((Function)SCLOsgi.MODULE_REPOSITORY.getValue(module, function)).applyArray(args);
468                         return t;
469                 } catch (ValueNotFound e) {
470                         throw new DatabaseException("SCL Value not found: " + e.name);
471                 } catch (Throwable t) {
472                         throw new DatabaseException(t);
473                 } finally {
474                         sclContext.put("graph", oldGraph);
475                 }
476
477     }
478
479     @SuppressWarnings("unchecked")
480     public static <T> T applySCLWrite(WriteGraph graph, @SuppressWarnings("rawtypes") Function f, Object ... args) throws DatabaseException {
481         SCLContext sclContext = SCLContext.getCurrent();
482         Object oldGraph = sclContext.put("graph", graph);
483         try {
484             return (T)f.applyArray(args);
485         } catch (Throwable t) {
486             throw new DatabaseException(t);
487         } finally {
488             sclContext.put("graph", oldGraph);
489         }
490     }
491
492     @SuppressWarnings("unchecked")
493     public static <T> T applySCLRead(ReadGraph graph, @SuppressWarnings("rawtypes") Function f, Object ... args) throws DatabaseException {
494         SCLContext sclContext = SCLContext.getCurrent();
495         Object oldGraph = sclContext.put("graph", graph);
496         try {
497             return (T)f.applyArray(args);
498         } catch (Throwable t) {
499             throw new DatabaseException(t);
500         } finally {
501             sclContext.put("graph", oldGraph);
502         }
503     }
504     
505     public static <P0,R> R applySCLWrite(WriteGraph graph, Function1<P0,R> function, P0 p0) throws DatabaseException {
506         SCLContext sclContext = SCLContext.getCurrent();
507         Object oldGraph = sclContext.put("graph", graph);
508         try {
509             return function.apply(p0);
510         } catch (Throwable t) {
511             throw new DatabaseException(t);
512         } finally {
513             sclContext.put("graph", oldGraph);
514         }
515     }
516
517     public static <P0,R> R applySCLRead(ReadGraph graph, Function1<P0,R> function, P0 p0) throws DatabaseException {
518         SCLContext sclContext = SCLContext.getCurrent();
519         Object oldGraph = sclContext.put("graph", graph);
520         try {
521             return function.apply(p0);
522         } catch (Throwable t) {
523             throw new DatabaseException(t);
524         } finally {
525             sclContext.put("graph", oldGraph);
526         }
527     }
528
529     public static <P0,P1,R> R applySCLRead(ReadGraph graph, Function2<P0,P1,R> function, P0 p0, P1 p1) throws DatabaseException {
530         SCLContext sclContext = SCLContext.getCurrent();
531         Object oldGraph = sclContext.put("graph", graph);
532         try {
533             return function.apply(p0, p1);
534         } catch (Throwable t) {
535             throw new DatabaseException(t);
536         } finally {
537             sclContext.put("graph", oldGraph);
538         }
539     }
540
541     public static <P0,R> R invokeSCLWrite(WriteGraph graph, Variable property, P0 p0) throws DatabaseException {
542         Function1<P0,R> fn = property.getPossibleValue(graph);
543         if(fn == null) throw new DatabaseException("No function for " + property.getURI(graph));
544         return Simantics.applySCLWrite(graph, fn, p0);
545     }
546
547     public static <P0,R> R invokeSCL(ReadGraph graph, Variable property, P0 p0) throws DatabaseException {
548         Function1<P0,R> fn = property.getPossibleValue(graph);
549         if(fn == null) throw new DatabaseException("No function for " + property.getURI(graph));
550         return Simantics.applySCLRead(graph, fn, p0);
551     }
552
553     public static <P0,P1,R> R invokeSCL(ReadGraph graph, Variable property, P0 p0, P1 p1) throws DatabaseException {
554         Function2<P0,P1,R> fn = property.getPossibleValue(graph);
555         if(fn == null) throw new DatabaseException("No function for " + property.getURI(graph));
556         return Simantics.applySCLRead(graph, fn, p0, p1);
557     }
558
559     public static <P0,R> R invokeSCLWrite(WriteGraph graph, Resource entity, Resource property, P0 p0) throws DatabaseException {
560         return invokeSCLWrite(graph, getProperty(graph, entity, property), p0);
561     }
562
563     public static <P0,R> R invokeSCL(ReadGraph graph, Resource entity, Resource property, P0 p0) throws DatabaseException {
564         return invokeSCL(graph, getProperty(graph, entity, property), p0);
565     }
566
567     public static <P0,P1,R> R invokeSCL(ReadGraph graph, Resource entity, Resource property, P0 p0, P1 p1) throws DatabaseException {
568         return invokeSCL(graph, getProperty(graph, entity, property), p0, p1);
569     }
570
571         public static <P0,R> R tryInvokeSCL(ReadGraph graph, Resource entity, Resource property, P0 p0) throws DatabaseException {
572         Variable p = Variables.tryGetProperty(graph, entity, property);
573         if (p == null)
574                 return null;
575         return invokeSCL(graph, p, p0);
576     }
577
578         public static <P0,P1,R> R tryInvokeSCL(ReadGraph graph, Resource entity, Resource property, P0 p0, P1 p1) throws DatabaseException {
579         Variable p = Variables.tryGetProperty(graph, entity, property);
580         if (p == null)
581                 return null;
582         return invokeSCL(graph, p, p0, p1);
583     }
584
585         private static Variable getProperty(ReadGraph graph, Resource entity, Resource property) throws DatabaseException {
586         return Variables.getVariable(graph, entity).getProperty(graph, property);
587     }
588
589     public static boolean ensureMemoryBytes(long bytes) {
590
591         Runtime runtime = Runtime.getRuntime();
592         long consumedMemory = runtime.totalMemory() - runtime.freeMemory();
593         long available = runtime.maxMemory() - consumedMemory;
594
595         return available > bytes;
596
597     }
598
599     public static long getDiskBytes() {
600
601         File ws = new File(Platform.getInstanceLocation().getURL().getFile());
602         return ws.getUsableSpace();
603
604     }
605
606     /**
607      * @return a service for dealing with recurring file system handling cases
608      */
609     public static FileService getFileService() {
610         FileService fs = fileService;
611         if (fs == null) {
612             synchronized (Simantics.class) {
613                 fs = fileService;
614                 if (fs == null)
615                     fs = fileService = new FileServiceImpl();
616             }
617         }
618         return fs;
619     }
620
621 }