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