1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
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
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics;
15 import java.util.UUID;
16 import java.util.concurrent.ScheduledFuture;
17 import java.util.concurrent.TimeUnit;
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;
66 * A facade for accessing basic Simantics platform services. Usable without a
67 * graphical UI, i.e. in headless contexts.
69 * TODO: in time, move headless functionality of SimanticsUI into this class but
70 * originals as delegates in SimanticsUI.
72 * TODO: duplicate of org.simantics.db.layer0.util.Simantics, do something about this!!
74 public class Simantics {
75 private static final Logger LOGGER = LoggerFactory.getLogger(Simantics.class);
78 * Default database driver ID
80 private static final String DEFAULT_DATABASE_DRIVER_ID = "acorn";
82 private static String defaultDatabaseDriverId = DEFAULT_DATABASE_DRIVER_ID;
84 private static ISessionContextProviderSource providerSource = null;
85 private static volatile FileServiceImpl fileService = null;
88 * Sets the database driver to be used by the platform. To have any effect,
89 * this must be set before platform startup.
93 public static void setDefaultDatabaseDriver(String id) {
94 defaultDatabaseDriverId = id;
98 * Returns currently set default database driver id.
100 public static String getDefaultDatabaseDriver() {
101 return defaultDatabaseDriverId;
108 * @throws PlatformException
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.");
115 RecoveryPolicy workspacePolicy = Platform.inDevelopmentMode() ? RecoveryPolicy.FixError : RecoveryPolicy.ThrowError;
116 OntologyRecoveryPolicy ontologyPolicy = Platform.inDevelopmentMode() ? OntologyRecoveryPolicy.Merge : OntologyRecoveryPolicy.ThrowError;
118 if (args.contains(SimanticsArguments.RECOVERY_POLICY_FIX_ERRORS)) {
119 workspacePolicy = RecoveryPolicy.FixError;
120 ontologyPolicy = OntologyRecoveryPolicy.Merge;
123 if (args.contains(SimanticsArguments.ONTOLOGY_RECOVERY_POLICY_REINSTALL)) {
124 ontologyPolicy = OntologyRecoveryPolicy.ReinstallDatabase;
127 if (args.contains(SimanticsArguments.ONTOLOGY_RECOVERY_POLICY_REINSTALL)) {
128 ontologyPolicy = OntologyRecoveryPolicy.ReinstallDatabase;
131 if (args.contains(SimanticsArguments.DISABLE_INDEX)) {
132 Indexing.setDefaultDependenciesIndexingEnabled(false);
135 String databaseDriverId = defaultDatabaseDriverId;
136 if (args.contains(SimanticsArguments.DATABASE_ID)) {
137 databaseDriverId = args.get(SimanticsArguments.DATABASE_ID);
138 Simantics.setDefaultDatabaseDriver(databaseDriverId);
142 if (args.contains(SimanticsArguments.LOCAL_SERVER_PORT)) {
144 localPort = args.get(SimanticsArguments.LOCAL_SERVER_PORT);
145 } catch (IllegalArgumentException e) {
146 throw new PlatformException("Failed to open database session", e);
150 // ServerAddress remoteDatabase = null;
151 // if (args.contains(SimanticsArguments.SERVER)) {
152 // String serverAddress = args.get(SimanticsArguments.SERVER);
154 // remoteDatabase = new ServerAddress(serverAddress);
155 // } catch (IllegalArgumentException e) {
156 // throw new PlatformException("Failed to open database session", e);
160 return startUpHeadless(progress, workspacePolicy, ontologyPolicy, localPort, databaseDriverId /*, remoteDatabase*/);
165 * @param workspacePolicy
166 * @param ontologyPolicy
168 * @param remoteDatabase
170 * @throws PlatformException
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.");
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);
183 if (progress == null)
184 progress = new NullProgressMonitor();
185 return SimanticsPlatform.INSTANCE.startUp(databaseDriverId, progress, workspacePolicy, ontologyPolicy, true, new ConsoleUserAgent());
190 * @throws PlatformException
192 public static void shutdown(IProgressMonitor progress) throws PlatformException {
193 SimanticsPlatform.INSTANCE.shutdown(progress);
197 * Queue execution of a runnable.
201 public static void async(Runnable runnable) {
202 ThreadUtils.getBlockingWorkExecutor().execute(runnable);
205 public static void async(Runnable runnable, int delay, TimeUnit unit) {
206 ThreadUtils.getTimer().schedule(runnable, delay, unit);
209 public static ScheduledFuture<?> scheduleAtFixedRate(Runnable runnable, int initialDelay, int period, TimeUnit unit) {
210 return ThreadUtils.getTimer().scheduleAtFixedRate(runnable, initialDelay, period, unit);
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.
218 * @param runnable a non-blocking runnable
220 public static void asyncNonblocking(Runnable runnable) {
221 ThreadUtils.getNonBlockingWorkExecutor().execute(runnable);
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.
229 * @param runnable a non-blocking runnable
230 * @param initialDelay
233 public static void asyncNonblocking(Runnable runnable, int initialDelay, int period) {
234 ThreadUtils.getNonBlockingWorkExecutor().scheduleAtFixedRate(runnable, initialDelay, period, TimeUnit.MILLISECONDS);
237 public static synchronized ISessionContext setSessionContext(ISessionContext ctx) {
238 return getSessionContextProvider().setSessionContext(ctx);
241 public static void setSessionContextProviderSource(ISessionContextProviderSource source) {
243 throw new IllegalArgumentException("null provider source");
244 providerSource = source;
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;
254 public static ISessionContextProvider getSessionContextProvider() {
255 return getProviderSource().getActive();
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.
263 * @return the session context associated with the currently active context
264 * or <code>null</code> if the context has no session context
266 public static ISessionContext getSessionContext() {
267 ISessionContextProvider provider = getSessionContextProvider();
268 return provider != null ? provider.getSessionContext() : null;
272 * Returns the database Session bound to the currently active context.
275 * The method always returns a non-null Session or produces an
276 * IllegalStateException if a Session was not attainable.
279 * @return the Session bound to the currently active workbench window
280 * @throws IllegalStateException if no Session was available
282 public static Session getSession() {
283 ISessionContext ctx = getSessionContext();
285 throw new IllegalStateException("Session unavailable, no database session open");
286 return ctx.getSession();
289 public static RequestProcessor getAvailableRequestProcessor() {
290 Object graph = SCLContext.getCurrent().get("graph");
291 if(graph instanceof ReadGraph)
292 return (RequestProcessor)graph;
294 return Simantics.getSession();
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.
303 * @return the Session bound to the currently active context or
306 public static Session peekSession() {
307 ISessionContext ctx = getSessionContext();
308 return ctx == null ? null : ctx.peekSession();
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
317 public static Resource getProjectResource() {
318 ISessionContext ctx = getSessionContext();
320 throw new IllegalStateException("No current database session");
321 Resource project = ctx.getHint(SimanticsKeys.KEY_PROJECT);
323 throw new IllegalStateException("No current project resource in session context " + ctx);
328 * @return the currently open and active project as a {@link Resource}
330 public static Resource peekProjectResource() {
331 ISessionContext ctx = getSessionContext();
332 return ctx != null ? ctx.<Resource>getHint(SimanticsKeys.KEY_PROJECT) : null;
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
341 public static IProject getProject() {
342 ISessionContext ctx = getSessionContext();
344 throw new IllegalStateException("No current database session");
345 IProject project = ctx.getHint(ProjectKeys.KEY_PROJECT);
347 throw new IllegalStateException("No current project in session context " + ctx);
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
355 public static IProject peekProject() {
356 ISessionContext ctx = getSessionContext();
357 return ctx == null ? null : ctx.<IProject>getHint(ProjectKeys.KEY_PROJECT);
360 // FIXME: once org.simantics.db.layer0.util.Simantics is gone, re-enable this
361 // private static SimanticsClipboard clipboard = SimanticsClipboard.EMPTY;
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);
374 public static SimanticsClipboard getClipboard() {
375 // FIXME: once org.simantics.db.layer0.util.Simantics is gone, re-enable this
377 return org.simantics.db.layer0.internal.SimanticsInternal.getClipboard();
380 public static Layer0 getLayer0() throws DatabaseException {
381 return Layer0.getInstance(getSession());
384 public static <T> T sync(ReadInterface<T> r) throws DatabaseException {
385 return getSession().sync(r);
388 public static <T> T sync(WriteInterface<T> r) throws DatabaseException {
389 return getSession().sync(r);
392 public static <T> void async(ReadInterface<T> r) {
393 getSession().async(r, new ProcedureAdapter<T>());
396 public static <T> void async(WriteInterface<T> r) {
397 getSession().async(r);
400 public static void clearTemporaryDirectory() {
401 FileUtils.deleteDir(getTemporaryDirectory());
404 public static File getTempfile(String directory, String suffix) {
405 File dir = getTemporaryDirectory(directory);
406 return new File(dir, UUID.randomUUID().toString() + "." + suffix);
409 public static File getTemporaryDirectory(String directory) {
410 File sub = new File(getTemporaryDirectory(), directory);
415 public static File getTemporaryDirectory() {
416 File workspace = Platform.getLocation().toFile();
417 File temp = new File(workspace, "tempFiles");
422 public static TempFiles getTempFiles() {
426 private static class TempFilesImpl implements TempFiles {
427 private final TempFilesImpl parent;
428 private final String prefix;
429 private final String fullPrefix;
431 private TempFilesImpl(TempFilesImpl parent, String directory) {
432 this.parent = parent;
433 this.prefix = directory;
434 this.fullPrefix = getPrefix(new StringBuilder()).toString();
437 private StringBuilder getPrefix(StringBuilder sb) {
439 parent.getPrefix(sb);
440 if (prefix != null && !prefix.isEmpty())
441 sb.append(prefix).append(File.separatorChar);
446 public File getRoot() {
447 return Simantics.getTemporaryDirectory(fullPrefix);
451 public File getTempfile(String directory, String suffix) {
452 return Simantics.getTempfile(fullPrefix.isEmpty() ? directory : fullPrefix + directory, suffix);
456 public TempFiles subdirectory(String directory) {
457 return new TempFilesImpl(this, directory);
461 public static TempFiles TEMP_FILES = new TempFilesImpl(null, null);
463 public static void flushIndexCaches(IProgressMonitor progress, Session session) {
465 IndexUtils.flushIndexCaches(progress, session);
466 } catch (Exception e) {
467 LOGGER.error("Flushing index caches failed.", e);
471 public static void saveQueries(Session session) {
473 XSupport xs = session.getService(XSupport.class);
475 } catch (Exception e) {
476 LOGGER.error("Saving database queries failed.", e);
480 @SuppressWarnings({ "unchecked", "rawtypes" })
481 public static <T> T applySCL(String module, String function, Object ... args) throws DatabaseException {
483 T t = (T)((Function)SCLOsgi.MODULE_REPOSITORY.getValue(module, function)).applyArray(args);
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);
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);
498 return applySCL(module, function, args);
499 } catch (DatabaseException dbe) {
501 } catch (Throwable t) {
502 throw new DatabaseException(t);
504 sclContext.put("graph", oldGraph);
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);
513 return (T)f.applyArray(args);
514 } catch (Throwable t) {
515 if (t instanceof DatabaseException)
516 throw (DatabaseException) t;
517 throw new DatabaseException(t);
519 sclContext.put("graph", oldGraph);
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);
528 return (T)f.applyArray(args);
529 } catch (Throwable t) {
530 if (t instanceof DatabaseException)
531 throw (DatabaseException) t;
532 throw new DatabaseException(t);
534 sclContext.put("graph", oldGraph);
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);
542 return function.apply(p0);
543 } catch (Throwable t) {
544 if (t instanceof DatabaseException)
545 throw (DatabaseException) t;
546 throw new DatabaseException(t);
548 sclContext.put("graph", oldGraph);
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);
556 return function.apply(p0);
557 } catch (Throwable t) {
558 if (t instanceof DatabaseException)
559 throw (DatabaseException) t;
560 throw new DatabaseException(t);
562 sclContext.put("graph", oldGraph);
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);
570 return function.apply(p0, p1);
571 } catch (Throwable t) {
572 if (t instanceof DatabaseException)
573 throw (DatabaseException) t;
574 throw new DatabaseException(t);
576 sclContext.put("graph", oldGraph);
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);
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);
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);
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);
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);
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);
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);
614 return invokeSCL(graph, p, p0);
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);
621 return invokeSCL(graph, p, p0, p1);
624 private static Variable getProperty(ReadGraph graph, Resource entity, Resource property) throws DatabaseException {
625 return Variables.getVariable(graph, entity).getProperty(graph, property);
628 public static boolean ensureMemoryBytes(long bytes) {
630 Runtime runtime = Runtime.getRuntime();
631 long consumedMemory = runtime.totalMemory() - runtime.freeMemory();
632 long available = runtime.maxMemory() - consumedMemory;
634 return available > bytes;
638 public static long getDiskBytes() {
640 File ws = new File(Platform.getInstanceLocation().getURL().getFile());
641 return ws.getUsableSpace();
646 * @return a service for dealing with recurring file system handling cases
648 public static FileService getFileService() {
649 FileService fs = fileService;
651 synchronized (Simantics.class) {
654 fs = fileService = new FileServiceImpl();