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