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.Resource;
28 import org.simantics.db.Session;
29 import org.simantics.db.WriteGraph;
30 import org.simantics.db.common.Indexing;
31 import org.simantics.db.common.procedure.adapter.ProcedureAdapter;
32 import org.simantics.db.exception.DatabaseException;
33 import org.simantics.db.exception.RuntimeDatabaseException;
34 import org.simantics.db.indexing.IndexUtils;
35 import org.simantics.db.layer0.util.SimanticsClipboard;
36 import org.simantics.db.layer0.util.SimanticsKeys;
37 import org.simantics.db.layer0.variable.Variable;
38 import org.simantics.db.layer0.variable.Variables;
39 import org.simantics.db.management.ISessionContext;
40 import org.simantics.db.management.ISessionContextProvider;
41 import org.simantics.db.management.ISessionContextProviderSource;
42 import org.simantics.db.management.SessionContextProvider;
43 import org.simantics.db.management.SingleSessionContextProviderSource;
44 import org.simantics.db.request.ReadInterface;
45 import org.simantics.db.request.WriteInterface;
46 import org.simantics.internal.FileServiceImpl;
47 import org.simantics.layer0.Layer0;
48 import org.simantics.project.IProject;
49 import org.simantics.project.ProjectKeys;
50 import org.simantics.scl.compiler.top.ValueNotFound;
51 import org.simantics.scl.osgi.SCLOsgi;
52 import org.simantics.scl.runtime.SCLContext;
53 import org.simantics.scl.runtime.function.Function;
54 import org.simantics.scl.runtime.function.Function1;
55 import org.simantics.scl.runtime.function.Function2;
56 import org.simantics.utils.FileService;
57 import org.simantics.utils.FileUtils;
58 import org.simantics.utils.TempFiles;
59 import org.simantics.utils.threads.ThreadUtils;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
64 * A facade for accessing basic Simantics platform services. Usable without a
65 * graphical UI, i.e. in headless contexts.
67 * TODO: in time, move headless functionality of SimanticsUI into this class but
68 * originals as delegates in SimanticsUI.
70 * TODO: duplicate of org.simantics.db.layer0.util.Simantics, do something about this!!
72 public class Simantics {
73 private static final Logger LOGGER = LoggerFactory.getLogger(Simantics.class);
76 * Default database driver ID
78 private static final String DEFAULT_DATABASE_DRIVER_ID = "acorn";
80 private static String defaultDatabaseDriverId = DEFAULT_DATABASE_DRIVER_ID;
82 private static ISessionContextProviderSource providerSource = null;
83 private static volatile FileServiceImpl fileService = null;
86 * Sets the database driver to be used by the platform. To have any effect,
87 * this must be set before platform startup.
91 public static void setDefaultDatabaseDriver(String id) {
92 defaultDatabaseDriverId = id;
96 * Returns currently set default database driver id.
98 public static String getDefaultDatabaseDriver() {
99 return defaultDatabaseDriverId;
106 * @throws PlatformException
108 public static ISessionContext startUpHeadless(IArguments args, IProgressMonitor progress) throws PlatformException {
109 if (SimanticsPlatform.INSTANCE.sessionContext != null) {
110 throw new RuntimeDatabaseException("Simantics is already up and running.");
113 RecoveryPolicy workspacePolicy = Platform.inDevelopmentMode() ? RecoveryPolicy.FixError : RecoveryPolicy.ThrowError;
114 OntologyRecoveryPolicy ontologyPolicy = Platform.inDevelopmentMode() ? OntologyRecoveryPolicy.Merge : OntologyRecoveryPolicy.ThrowError;
116 if (args.contains(SimanticsArguments.RECOVERY_POLICY_FIX_ERRORS)) {
117 workspacePolicy = RecoveryPolicy.FixError;
118 ontologyPolicy = OntologyRecoveryPolicy.Merge;
121 if (args.contains(SimanticsArguments.ONTOLOGY_RECOVERY_POLICY_REINSTALL)) {
122 ontologyPolicy = OntologyRecoveryPolicy.ReinstallDatabase;
125 if (args.contains(SimanticsArguments.ONTOLOGY_RECOVERY_POLICY_REINSTALL)) {
126 ontologyPolicy = OntologyRecoveryPolicy.ReinstallDatabase;
129 if (args.contains(SimanticsArguments.DISABLE_INDEX)) {
130 Indexing.setDefaultDependenciesIndexingEnabled(false);
133 String databaseDriverId = defaultDatabaseDriverId;
134 if (args.contains(SimanticsArguments.DATABASE_ID)) {
135 databaseDriverId = args.get(SimanticsArguments.DATABASE_ID);
136 Simantics.setDefaultDatabaseDriver(databaseDriverId);
140 if (args.contains(SimanticsArguments.LOCAL_SERVER_PORT)) {
142 localPort = args.get(SimanticsArguments.LOCAL_SERVER_PORT);
143 } catch (IllegalArgumentException e) {
144 throw new PlatformException("Failed to open database session", e);
148 // ServerAddress remoteDatabase = null;
149 // if (args.contains(SimanticsArguments.SERVER)) {
150 // String serverAddress = args.get(SimanticsArguments.SERVER);
152 // remoteDatabase = new ServerAddress(serverAddress);
153 // } catch (IllegalArgumentException e) {
154 // throw new PlatformException("Failed to open database session", e);
158 return startUpHeadless(progress, workspacePolicy, ontologyPolicy, localPort, databaseDriverId /*, remoteDatabase*/);
163 * @param workspacePolicy
164 * @param ontologyPolicy
166 * @param remoteDatabase
168 * @throws PlatformException
170 public static ISessionContext startUpHeadless(IProgressMonitor progress, RecoveryPolicy workspacePolicy, OntologyRecoveryPolicy ontologyPolicy, int localPort, String databaseDriverId) throws PlatformException {
171 if (SimanticsPlatform.INSTANCE.sessionContext != null) {
172 throw new RuntimeDatabaseException("Simantics is already up and running.");
175 // Set session context provider.
176 final ISessionContextProvider provider = new SessionContextProvider(null);
177 ISessionContextProviderSource source = new SingleSessionContextProviderSource(provider);
178 setSessionContextProviderSource(source);
179 org.simantics.db.layer0.internal.SimanticsInternal.setSessionContextProviderSource(source);
181 if (progress == null)
182 progress = new NullProgressMonitor();
183 return SimanticsPlatform.INSTANCE.startUp(databaseDriverId, progress, workspacePolicy, ontologyPolicy, true, new ConsoleUserAgent());
188 * @throws PlatformException
190 public static void shutdown(IProgressMonitor progress) throws PlatformException {
191 SimanticsPlatform.INSTANCE.shutdown(progress);
195 * Queue execution of a runnable.
199 public static void async(Runnable runnable) {
200 ThreadUtils.getBlockingWorkExecutor().execute(runnable);
203 public static void async(Runnable runnable, int delay, TimeUnit unit) {
204 ThreadUtils.getTimer().schedule(runnable, delay, unit);
207 public static ScheduledFuture<?> scheduleAtFixedRate(Runnable runnable, int initialDelay, int period, TimeUnit unit) {
208 return ThreadUtils.getTimer().scheduleAtFixedRate(runnable, initialDelay, period, unit);
212 * Queue execution of a non-blocking runnable. Use this method with caution.
213 * A non-blocking runnable nevers locks anything, No Locks, No semaphores,
214 * No Object.wait(), No synchronized() {} blocks.
216 * @param runnable a non-blocking runnable
218 public static void asyncNonblocking(Runnable runnable) {
219 ThreadUtils.getNonBlockingWorkExecutor().execute(runnable);
223 * Schedule execution of a non-blocking runnable. Use this method with caution.
224 * A non-blocking runnable never locks anything, No Locks, No semaphores,
225 * No Object,wait(), No synchronized() {} blocks.
227 * @param runnable a non-blocking runnable
228 * @param initialDelay
231 public static void asyncNonblocking(Runnable runnable, int initialDelay, int period) {
232 ThreadUtils.getNonBlockingWorkExecutor().scheduleAtFixedRate(runnable, initialDelay, period, TimeUnit.MILLISECONDS);
235 public static synchronized ISessionContext setSessionContext(ISessionContext ctx) {
236 return getSessionContextProvider().setSessionContext(ctx);
239 public static void setSessionContextProviderSource(ISessionContextProviderSource source) {
241 throw new IllegalArgumentException("null provider source");
242 providerSource = source;
245 public static ISessionContextProviderSource getProviderSource() {
246 if (providerSource == null)
247 throw new IllegalStateException(
248 "providerSource must be initialized by the application before using class Simantics");
249 return providerSource;
252 public static ISessionContextProvider getSessionContextProvider() {
253 return getProviderSource().getActive();
257 * Returns the database session context associated with the currently active
258 * context. This method should be used to retrieve session contexts only
259 * when the client is sure that the correct context is active.
261 * @return the session context associated with the currently active context
262 * or <code>null</code> if the context has no session context
264 public static ISessionContext getSessionContext() {
265 ISessionContextProvider provider = getSessionContextProvider();
266 return provider != null ? provider.getSessionContext() : null;
270 * Returns the database Session bound to the currently active context.
273 * The method always returns a non-null Session or produces an
274 * IllegalStateException if a Session was not attainable.
277 * @return the Session bound to the currently active workbench window
278 * @throws IllegalStateException if no Session was available
280 public static Session getSession() {
281 ISessionContext ctx = getSessionContext();
283 throw new IllegalStateException("Session unavailable, no database session open");
284 return ctx.getSession();
288 * Returns the database Session bound to the currently active context.
289 * Differently from {@link #getSession()}, this method returns
290 * <code>null</code> if there is no current Session available.
293 * @return the Session bound to the currently active context or
296 public static Session peekSession() {
297 ISessionContext ctx = getSessionContext();
298 return ctx == null ? null : ctx.peekSession();
302 * @return the currently open and active project as a Resource
303 * @throws IllegalStateException if there is no currently active database
304 * session, which also means there is no active project at the
307 public static Resource getProjectResource() {
308 ISessionContext ctx = getSessionContext();
310 throw new IllegalStateException("No current database session");
311 Resource project = ctx.getHint(SimanticsKeys.KEY_PROJECT);
313 throw new IllegalStateException("No current project resource in session context " + ctx);
318 * @return the currently open and active project as a {@link Resource}
320 public static Resource peekProjectResource() {
321 ISessionContext ctx = getSessionContext();
322 return ctx != null ? ctx.<Resource>getHint(SimanticsKeys.KEY_PROJECT) : null;
326 * @return the currently open and active project as an {@link IProject}
327 * @throws IllegalStateException if there is no currently active database
328 * session, which also means there is no active project at the
331 public static IProject getProject() {
332 ISessionContext ctx = getSessionContext();
334 throw new IllegalStateException("No current database session");
335 IProject project = ctx.getHint(ProjectKeys.KEY_PROJECT);
337 throw new IllegalStateException("No current project in session context " + ctx);
342 * @return the currently open and active project as an {@link IProject} or
343 * <code>null</code> if there is no active session or project
345 public static IProject peekProject() {
346 ISessionContext ctx = getSessionContext();
347 return ctx == null ? null : ctx.<IProject>getHint(ProjectKeys.KEY_PROJECT);
350 // FIXME: once org.simantics.db.layer0.util.Simantics is gone, re-enable this
351 // private static SimanticsClipboard clipboard = SimanticsClipboard.EMPTY;
356 public static void setClipboard(SimanticsClipboard content) {
357 // FIXME: once org.simantics.db.layer0.util.Simantics is gone, re-enable this
358 // if (content == null)
359 // throw new NullPointerException("null clipboard content");
360 // clipboard = content;
361 org.simantics.db.layer0.internal.SimanticsInternal.setClipboard(content);
364 public static SimanticsClipboard getClipboard() {
365 // FIXME: once org.simantics.db.layer0.util.Simantics is gone, re-enable this
367 return org.simantics.db.layer0.internal.SimanticsInternal.getClipboard();
370 public static Layer0 getLayer0() throws DatabaseException {
371 return Layer0.getInstance(getSession());
374 public static <T> T sync(ReadInterface<T> r) throws DatabaseException {
375 return getSession().sync(r);
378 public static <T> T sync(WriteInterface<T> r) throws DatabaseException {
379 return getSession().sync(r);
382 public static <T> void async(ReadInterface<T> r) {
383 getSession().async(r, new ProcedureAdapter<T>());
386 public static <T> void async(WriteInterface<T> r) {
387 getSession().async(r);
390 public static void clearTemporaryDirectory() {
391 FileUtils.deleteDir(getTemporaryDirectory());
394 public static File getTempfile(String directory, String suffix) {
395 File dir = getTemporaryDirectory(directory);
396 return new File(dir, UUID.randomUUID().toString() + "." + suffix);
399 public static File getTemporaryDirectory(String directory) {
400 File sub = new File(getTemporaryDirectory(), directory);
405 public static File getTemporaryDirectory() {
406 File workspace = Platform.getLocation().toFile();
407 File temp = new File(workspace, "tempFiles");
412 public static TempFiles getTempFiles() {
416 private static class TempFilesImpl implements TempFiles {
417 private final TempFilesImpl parent;
418 private final String prefix;
419 private final String fullPrefix;
421 private TempFilesImpl(TempFilesImpl parent, String directory) {
422 this.parent = parent;
423 this.prefix = directory;
424 this.fullPrefix = getPrefix(new StringBuilder()).toString();
427 private StringBuilder getPrefix(StringBuilder sb) {
429 parent.getPrefix(sb);
430 if (prefix != null && !prefix.isEmpty())
431 sb.append(prefix).append(File.separatorChar);
436 public File getRoot() {
437 return Simantics.getTemporaryDirectory(fullPrefix);
441 public File getTempfile(String directory, String suffix) {
442 return Simantics.getTempfile(fullPrefix.isEmpty() ? directory : fullPrefix + directory, suffix);
446 public TempFiles subdirectory(String directory) {
447 return new TempFilesImpl(this, directory);
451 public static TempFiles TEMP_FILES = new TempFilesImpl(null, null);
453 public static void flushIndexCaches(IProgressMonitor progress, Session session) {
455 IndexUtils.flushIndexCaches(progress, session);
456 } catch (Exception e) {
457 LOGGER.error("Flushing index caches failed.", e);
462 @SuppressWarnings({ "unchecked", "rawtypes" })
463 public static <T> T applySCL(String module, String function, ReadGraph graph, Object ... args) throws DatabaseException {
464 SCLContext sclContext = SCLContext.getCurrent();
465 Object oldGraph = sclContext.put("graph", graph);
467 T t = (T)((Function)SCLOsgi.MODULE_REPOSITORY.getValue(module, function)).applyArray(args);
469 } catch (ValueNotFound e) {
470 throw new DatabaseException("SCL Value not found: " + e.name);
471 } catch (Throwable t) {
472 throw new DatabaseException(t);
474 sclContext.put("graph", oldGraph);
479 @SuppressWarnings("unchecked")
480 public static <T> T applySCLWrite(WriteGraph graph, @SuppressWarnings("rawtypes") Function f, Object ... args) throws DatabaseException {
481 SCLContext sclContext = SCLContext.getCurrent();
482 Object oldGraph = sclContext.put("graph", graph);
484 return (T)f.applyArray(args);
485 } catch (Throwable t) {
486 throw new DatabaseException(t);
488 sclContext.put("graph", oldGraph);
492 @SuppressWarnings("unchecked")
493 public static <T> T applySCLRead(ReadGraph graph, @SuppressWarnings("rawtypes") Function f, Object ... args) throws DatabaseException {
494 SCLContext sclContext = SCLContext.getCurrent();
495 Object oldGraph = sclContext.put("graph", graph);
497 return (T)f.applyArray(args);
498 } catch (Throwable t) {
499 throw new DatabaseException(t);
501 sclContext.put("graph", oldGraph);
505 public static <P0,R> R applySCLWrite(WriteGraph graph, Function1<P0,R> function, P0 p0) throws DatabaseException {
506 SCLContext sclContext = SCLContext.getCurrent();
507 Object oldGraph = sclContext.put("graph", graph);
509 return function.apply(p0);
510 } catch (Throwable t) {
511 throw new DatabaseException(t);
513 sclContext.put("graph", oldGraph);
517 public static <P0,R> R applySCLRead(ReadGraph graph, Function1<P0,R> function, P0 p0) throws DatabaseException {
518 SCLContext sclContext = SCLContext.getCurrent();
519 Object oldGraph = sclContext.put("graph", graph);
521 return function.apply(p0);
522 } catch (Throwable t) {
523 throw new DatabaseException(t);
525 sclContext.put("graph", oldGraph);
529 public static <P0,P1,R> R applySCLRead(ReadGraph graph, Function2<P0,P1,R> function, P0 p0, P1 p1) throws DatabaseException {
530 SCLContext sclContext = SCLContext.getCurrent();
531 Object oldGraph = sclContext.put("graph", graph);
533 return function.apply(p0, p1);
534 } catch (Throwable t) {
535 throw new DatabaseException(t);
537 sclContext.put("graph", oldGraph);
541 public static <P0,R> R invokeSCLWrite(WriteGraph graph, Variable property, P0 p0) throws DatabaseException {
542 Function1<P0,R> fn = property.getPossibleValue(graph);
543 if(fn == null) throw new DatabaseException("No function for " + property.getURI(graph));
544 return Simantics.applySCLWrite(graph, fn, p0);
547 public static <P0,R> R invokeSCL(ReadGraph graph, Variable property, P0 p0) throws DatabaseException {
548 Function1<P0,R> fn = property.getPossibleValue(graph);
549 if(fn == null) throw new DatabaseException("No function for " + property.getURI(graph));
550 return Simantics.applySCLRead(graph, fn, p0);
553 public static <P0,P1,R> R invokeSCL(ReadGraph graph, Variable property, P0 p0, P1 p1) throws DatabaseException {
554 Function2<P0,P1,R> fn = property.getPossibleValue(graph);
555 if(fn == null) throw new DatabaseException("No function for " + property.getURI(graph));
556 return Simantics.applySCLRead(graph, fn, p0, p1);
559 public static <P0,R> R invokeSCLWrite(WriteGraph graph, Resource entity, Resource property, P0 p0) throws DatabaseException {
560 return invokeSCLWrite(graph, getProperty(graph, entity, property), p0);
563 public static <P0,R> R invokeSCL(ReadGraph graph, Resource entity, Resource property, P0 p0) throws DatabaseException {
564 return invokeSCL(graph, getProperty(graph, entity, property), p0);
567 public static <P0,P1,R> R invokeSCL(ReadGraph graph, Resource entity, Resource property, P0 p0, P1 p1) throws DatabaseException {
568 return invokeSCL(graph, getProperty(graph, entity, property), p0, p1);
571 public static <P0,R> R tryInvokeSCL(ReadGraph graph, Resource entity, Resource property, P0 p0) throws DatabaseException {
572 Variable p = Variables.tryGetProperty(graph, entity, property);
575 return invokeSCL(graph, p, p0);
578 public static <P0,P1,R> R tryInvokeSCL(ReadGraph graph, Resource entity, Resource property, P0 p0, P1 p1) throws DatabaseException {
579 Variable p = Variables.tryGetProperty(graph, entity, property);
582 return invokeSCL(graph, p, p0, p1);
585 private static Variable getProperty(ReadGraph graph, Resource entity, Resource property) throws DatabaseException {
586 return Variables.getVariable(graph, entity).getProperty(graph, property);
589 public static boolean ensureMemoryBytes(long bytes) {
591 Runtime runtime = Runtime.getRuntime();
592 long consumedMemory = runtime.totalMemory() - runtime.freeMemory();
593 long available = runtime.maxMemory() - consumedMemory;
595 return available > bytes;
599 public static long getDiskBytes() {
601 File ws = new File(Platform.getInstanceLocation().getURL().getFile());
602 return ws.getUsableSpace();
607 * @return a service for dealing with recurring file system handling cases
609 public static FileService getFileService() {
610 FileService fs = fileService;
612 synchronized (Simantics.class) {
615 fs = fileService = new FileServiceImpl();