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