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.procedure.adapter.ProcedureAdapter;
31 import org.simantics.db.exception.DatabaseException;
32 import org.simantics.db.exception.RuntimeDatabaseException;
33 import org.simantics.db.indexing.IndexUtils;
34 import org.simantics.db.layer0.util.SimanticsClipboard;
35 import org.simantics.db.layer0.util.SimanticsKeys;
36 import org.simantics.db.layer0.variable.Variable;
37 import org.simantics.db.layer0.variable.Variables;
38 import org.simantics.db.management.ISessionContext;
39 import org.simantics.db.management.ISessionContextProvider;
40 import org.simantics.db.management.ISessionContextProviderSource;
41 import org.simantics.db.management.SessionContextProvider;
42 import org.simantics.db.management.SingleSessionContextProviderSource;
43 import org.simantics.db.request.ReadInterface;
44 import org.simantics.db.request.WriteInterface;
45 import org.simantics.internal.FileServiceImpl;
46 import org.simantics.layer0.Layer0;
47 import org.simantics.project.IProject;
48 import org.simantics.project.ProjectKeys;
49 import org.simantics.scl.compiler.top.ValueNotFound;
50 import org.simantics.scl.osgi.SCLOsgi;
51 import org.simantics.scl.runtime.SCLContext;
52 import org.simantics.scl.runtime.function.Function;
53 import org.simantics.scl.runtime.function.Function1;
54 import org.simantics.scl.runtime.function.Function2;
55 import org.simantics.utils.FileService;
56 import org.simantics.utils.FileUtils;
57 import org.simantics.utils.TempFiles;
58 import org.simantics.utils.threads.ThreadUtils;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
63 * A facade for accessing basic Simantics platform services. Usable without a
64 * graphical UI, i.e. in headless contexts.
66 * TODO: in time, move headless functionality of SimanticsUI into this class but
67 * originals as delegates in SimanticsUI.
69 * TODO: duplicate of org.simantics.db.layer0.util.Simantics, do something about this!!
71 public class Simantics {
72 private static final Logger LOGGER = LoggerFactory.getLogger(Simantics.class);
75 * Default database driver ID
77 private static final String DEFAULT_DATABASE_DRIVER_ID = "acorn";
79 private static String defaultDatabaseDriverId = DEFAULT_DATABASE_DRIVER_ID;
81 private static ISessionContextProviderSource providerSource = null;
82 private static volatile FileServiceImpl fileService = null;
85 * Sets the database driver to be used by the platform. To have any effect,
86 * this must be set before platform startup.
90 public static void setDefaultDatabaseDriver(String id) {
91 defaultDatabaseDriverId = id;
95 * Returns currently set default database driver id.
97 public static String getDefaultDatabaseDriver() {
98 return defaultDatabaseDriverId;
105 * @throws PlatformException
107 public static ISessionContext startUpHeadless(IArguments args, IProgressMonitor progress) throws PlatformException {
108 if (SimanticsPlatform.INSTANCE.sessionContext != null) {
109 throw new RuntimeDatabaseException("Simantics is already up and running.");
112 RecoveryPolicy workspacePolicy = Platform.inDevelopmentMode() ? RecoveryPolicy.FixError : RecoveryPolicy.ThrowError;
113 OntologyRecoveryPolicy ontologyPolicy = Platform.inDevelopmentMode() ? OntologyRecoveryPolicy.Merge : OntologyRecoveryPolicy.ThrowError;
115 if (args.contains(SimanticsArguments.RECOVERY_POLICY_FIX_ERRORS)) {
116 workspacePolicy = RecoveryPolicy.FixError;
117 ontologyPolicy = OntologyRecoveryPolicy.Merge;
120 if (args.contains(SimanticsArguments.ONTOLOGY_RECOVERY_POLICY_REINSTALL)) {
121 ontologyPolicy = OntologyRecoveryPolicy.ReinstallDatabase;
124 if (args.contains(SimanticsArguments.ONTOLOGY_RECOVERY_POLICY_REINSTALL)) {
125 ontologyPolicy = OntologyRecoveryPolicy.ReinstallDatabase;
129 if (args.contains(SimanticsArguments.LOCAL_SERVER_PORT)) {
131 localPort = args.get(SimanticsArguments.LOCAL_SERVER_PORT);
132 } catch (IllegalArgumentException e) {
133 throw new PlatformException("Failed to open database session", e);
137 // ServerAddress remoteDatabase = null;
138 // if (args.contains(SimanticsArguments.SERVER)) {
139 // String serverAddress = args.get(SimanticsArguments.SERVER);
141 // remoteDatabase = new ServerAddress(serverAddress);
142 // } catch (IllegalArgumentException e) {
143 // throw new PlatformException("Failed to open database session", e);
147 return startUpHeadless(progress, workspacePolicy, ontologyPolicy, localPort /*, remoteDatabase*/);
152 * @param workspacePolicy
153 * @param ontologyPolicy
155 * @param remoteDatabase
157 * @throws PlatformException
159 public static ISessionContext startUpHeadless(IProgressMonitor progress, RecoveryPolicy workspacePolicy, OntologyRecoveryPolicy ontologyPolicy, int localPort) throws PlatformException {
160 if (SimanticsPlatform.INSTANCE.sessionContext != null) {
161 throw new RuntimeDatabaseException("Simantics is already up and running.");
164 // Set session context provider.
165 final ISessionContextProvider provider = new SessionContextProvider(null);
166 ISessionContextProviderSource source = new SingleSessionContextProviderSource(provider);
167 setSessionContextProviderSource(source);
168 org.simantics.db.layer0.internal.SimanticsInternal.setSessionContextProviderSource(source);
170 if (progress == null)
171 progress = new NullProgressMonitor();
172 return SimanticsPlatform.INSTANCE.startUp(defaultDatabaseDriverId, progress, workspacePolicy, ontologyPolicy, true, new ConsoleUserAgent());
177 * @throws PlatformException
179 public static void shutdown(IProgressMonitor progress) throws PlatformException {
180 SimanticsPlatform.INSTANCE.shutdown(progress);
184 * Queue execution of a runnable.
188 public static void async(Runnable runnable) {
189 ThreadUtils.getBlockingWorkExecutor().execute(runnable);
192 public static void async(Runnable runnable, int delay, TimeUnit unit) {
193 ThreadUtils.getTimer().schedule(runnable, delay, unit);
196 public static ScheduledFuture<?> scheduleAtFixedRate(Runnable runnable, int initialDelay, int period, TimeUnit unit) {
197 return ThreadUtils.getTimer().scheduleAtFixedRate(runnable, initialDelay, period, unit);
201 * Queue execution of a non-blocking runnable. Use this method with caution.
202 * A non-blocking runnable nevers locks anything, No Locks, No semaphores,
203 * No Object.wait(), No synchronized() {} blocks.
205 * @param runnable a non-blocking runnable
207 public static void asyncNonblocking(Runnable runnable) {
208 ThreadUtils.getNonBlockingWorkExecutor().execute(runnable);
212 * Schedule execution of a non-blocking runnable. Use this method with caution.
213 * A non-blocking runnable never locks anything, No Locks, No semaphores,
214 * No Object,wait(), No synchronized() {} blocks.
216 * @param runnable a non-blocking runnable
217 * @param initialDelay
220 public static void asyncNonblocking(Runnable runnable, int initialDelay, int period) {
221 ThreadUtils.getNonBlockingWorkExecutor().scheduleAtFixedRate(runnable, initialDelay, period, TimeUnit.MILLISECONDS);
224 public static synchronized ISessionContext setSessionContext(ISessionContext ctx) {
225 return getSessionContextProvider().setSessionContext(ctx);
228 public static void setSessionContextProviderSource(ISessionContextProviderSource source) {
230 throw new IllegalArgumentException("null provider source");
231 providerSource = source;
234 public static ISessionContextProviderSource getProviderSource() {
235 if (providerSource == null)
236 throw new IllegalStateException(
237 "providerSource must be initialized by the application before using class Simantics");
238 return providerSource;
241 public static ISessionContextProvider getSessionContextProvider() {
242 return getProviderSource().getActive();
246 * Returns the database session context associated with the currently active
247 * context. This method should be used to retrieve session contexts only
248 * when the client is sure that the correct context is active.
250 * @return the session context associated with the currently active context
251 * or <code>null</code> if the context has no session context
253 public static ISessionContext getSessionContext() {
254 ISessionContextProvider provider = getSessionContextProvider();
255 return provider != null ? provider.getSessionContext() : null;
259 * Returns the database Session bound to the currently active context.
262 * The method always returns a non-null Session or produces an
263 * IllegalStateException if a Session was not attainable.
266 * @return the Session bound to the currently active workbench window
267 * @throws IllegalStateException if no Session was available
269 public static Session getSession() {
270 ISessionContext ctx = getSessionContext();
272 throw new IllegalStateException("Session unavailable, no database session open");
273 return ctx.getSession();
277 * Returns the database Session bound to the currently active context.
278 * Differently from {@link #getSession()}, this method returns
279 * <code>null</code> if there is no current Session available.
282 * @return the Session bound to the currently active context or
285 public static Session peekSession() {
286 ISessionContext ctx = getSessionContext();
287 return ctx == null ? null : ctx.peekSession();
291 * @return the currently open and active project as a Resource
292 * @throws IllegalStateException if there is no currently active database
293 * session, which also means there is no active project at the
296 public static Resource getProjectResource() {
297 ISessionContext ctx = getSessionContext();
299 throw new IllegalStateException("No current database session");
300 Resource project = ctx.getHint(SimanticsKeys.KEY_PROJECT);
302 throw new IllegalStateException("No current project resource in session context " + ctx);
307 * @return the currently open and active project as a {@link Resource}
309 public static Resource peekProjectResource() {
310 ISessionContext ctx = getSessionContext();
311 return ctx != null ? ctx.<Resource>getHint(SimanticsKeys.KEY_PROJECT) : null;
315 * @return the currently open and active project as an {@link IProject}
316 * @throws IllegalStateException if there is no currently active database
317 * session, which also means there is no active project at the
320 public static IProject getProject() {
321 ISessionContext ctx = getSessionContext();
323 throw new IllegalStateException("No current database session");
324 IProject project = ctx.getHint(ProjectKeys.KEY_PROJECT);
326 throw new IllegalStateException("No current project in session context " + ctx);
331 * @return the currently open and active project as an {@link IProject} or
332 * <code>null</code> if there is no active session or project
334 public static IProject peekProject() {
335 ISessionContext ctx = getSessionContext();
336 return ctx == null ? null : ctx.<IProject>getHint(ProjectKeys.KEY_PROJECT);
339 // FIXME: once org.simantics.db.layer0.util.Simantics is gone, re-enable this
340 // private static SimanticsClipboard clipboard = SimanticsClipboard.EMPTY;
345 public static void setClipboard(SimanticsClipboard content) {
346 // FIXME: once org.simantics.db.layer0.util.Simantics is gone, re-enable this
347 // if (content == null)
348 // throw new NullPointerException("null clipboard content");
349 // clipboard = content;
350 org.simantics.db.layer0.internal.SimanticsInternal.setClipboard(content);
353 public static SimanticsClipboard getClipboard() {
354 // FIXME: once org.simantics.db.layer0.util.Simantics is gone, re-enable this
356 return org.simantics.db.layer0.internal.SimanticsInternal.getClipboard();
359 public static Layer0 getLayer0() throws DatabaseException {
360 return Layer0.getInstance(getSession());
363 public static <T> T sync(ReadInterface<T> r) throws DatabaseException {
364 return getSession().sync(r);
367 public static <T> T sync(WriteInterface<T> r) throws DatabaseException {
368 return getSession().sync(r);
371 public static <T> void async(ReadInterface<T> r) {
372 getSession().async(r, new ProcedureAdapter<T>());
375 public static <T> void async(WriteInterface<T> r) {
376 getSession().async(r);
379 public static void clearTemporaryDirectory() {
380 FileUtils.deleteDir(getTemporaryDirectory());
383 public static File getTempfile(String directory, String suffix) {
384 File dir = getTemporaryDirectory(directory);
385 return new File(dir, UUID.randomUUID().toString() + "." + suffix);
388 public static File getTemporaryDirectory(String directory) {
389 File sub = new File(getTemporaryDirectory(), directory);
394 public static File getTemporaryDirectory() {
395 File workspace = Platform.getLocation().toFile();
396 File temp = new File(workspace, "tempFiles");
401 public static TempFiles getTempFiles() {
405 private static class TempFilesImpl implements TempFiles {
406 private final TempFilesImpl parent;
407 private final String prefix;
408 private final String fullPrefix;
410 private TempFilesImpl(TempFilesImpl parent, String directory) {
411 this.parent = parent;
412 this.prefix = directory;
413 this.fullPrefix = getPrefix(new StringBuilder()).toString();
416 private StringBuilder getPrefix(StringBuilder sb) {
418 parent.getPrefix(sb);
419 if (prefix != null && !prefix.isEmpty())
420 sb.append(prefix).append(File.separatorChar);
425 public File getRoot() {
426 return Simantics.getTemporaryDirectory(fullPrefix);
430 public File getTempfile(String directory, String suffix) {
431 return Simantics.getTempfile(fullPrefix.isEmpty() ? directory : fullPrefix + directory, suffix);
435 public TempFiles subdirectory(String directory) {
436 return new TempFilesImpl(this, directory);
440 public static TempFiles TEMP_FILES = new TempFilesImpl(null, null);
442 public static void flushIndexCaches(IProgressMonitor progress, Session session) {
444 IndexUtils.flushIndexCaches(progress, session);
445 } catch (Exception e) {
446 LOGGER.error("Flushing index caches failed.", e);
451 @SuppressWarnings({ "unchecked", "rawtypes" })
452 public static <T> T applySCL(String module, String function, ReadGraph graph, Object ... args) throws DatabaseException {
453 SCLContext sclContext = SCLContext.getCurrent();
454 Object oldGraph = sclContext.put("graph", graph);
456 T t = (T)((Function)SCLOsgi.MODULE_REPOSITORY.getValue(module, function)).applyArray(args);
458 } catch (ValueNotFound e) {
459 throw new DatabaseException("SCL Value not found: " + e.name);
460 } catch (Throwable t) {
461 throw new DatabaseException(t);
463 sclContext.put("graph", oldGraph);
468 @SuppressWarnings("unchecked")
469 public static <T> T applySCLWrite(WriteGraph graph, @SuppressWarnings("rawtypes") Function f, Object ... args) throws DatabaseException {
470 SCLContext sclContext = SCLContext.getCurrent();
471 Object oldGraph = sclContext.put("graph", graph);
473 return (T)f.applyArray(args);
474 } catch (Throwable t) {
475 throw new DatabaseException(t);
477 sclContext.put("graph", oldGraph);
481 @SuppressWarnings("unchecked")
482 public static <T> T applySCLRead(ReadGraph graph, @SuppressWarnings("rawtypes") Function f, Object ... args) throws DatabaseException {
483 SCLContext sclContext = SCLContext.getCurrent();
484 Object oldGraph = sclContext.put("graph", graph);
486 return (T)f.applyArray(args);
487 } catch (Throwable t) {
488 throw new DatabaseException(t);
490 sclContext.put("graph", oldGraph);
494 public static <P0,R> R applySCLWrite(WriteGraph graph, Function1<P0,R> function, P0 p0) throws DatabaseException {
495 SCLContext sclContext = SCLContext.getCurrent();
496 Object oldGraph = sclContext.put("graph", graph);
498 return function.apply(p0);
499 } catch (Throwable t) {
500 throw new DatabaseException(t);
502 sclContext.put("graph", oldGraph);
506 public static <P0,R> R applySCLRead(ReadGraph graph, Function1<P0,R> function, P0 p0) throws DatabaseException {
507 SCLContext sclContext = SCLContext.getCurrent();
508 Object oldGraph = sclContext.put("graph", graph);
510 return function.apply(p0);
511 } catch (Throwable t) {
512 throw new DatabaseException(t);
514 sclContext.put("graph", oldGraph);
518 public static <P0,P1,R> R applySCLRead(ReadGraph graph, Function2<P0,P1,R> function, P0 p0, P1 p1) throws DatabaseException {
519 SCLContext sclContext = SCLContext.getCurrent();
520 Object oldGraph = sclContext.put("graph", graph);
522 return function.apply(p0, p1);
523 } catch (Throwable t) {
524 throw new DatabaseException(t);
526 sclContext.put("graph", oldGraph);
530 public static <P0,R> R invokeSCLWrite(WriteGraph graph, Variable property, P0 p0) throws DatabaseException {
531 Function1<P0,R> fn = property.getPossibleValue(graph);
532 if(fn == null) throw new DatabaseException("No function for " + property.getURI(graph));
533 return Simantics.applySCLWrite(graph, fn, p0);
536 public static <P0,R> R invokeSCL(ReadGraph graph, Variable property, P0 p0) throws DatabaseException {
537 Function1<P0,R> fn = property.getPossibleValue(graph);
538 if(fn == null) throw new DatabaseException("No function for " + property.getURI(graph));
539 return Simantics.applySCLRead(graph, fn, p0);
542 public static <P0,P1,R> R invokeSCL(ReadGraph graph, Variable property, P0 p0, P1 p1) throws DatabaseException {
543 Function2<P0,P1,R> fn = property.getPossibleValue(graph);
544 if(fn == null) throw new DatabaseException("No function for " + property.getURI(graph));
545 return Simantics.applySCLRead(graph, fn, p0, p1);
548 public static <P0,R> R invokeSCLWrite(WriteGraph graph, Resource entity, Resource property, P0 p0) throws DatabaseException {
549 return invokeSCLWrite(graph, getProperty(graph, entity, property), p0);
552 public static <P0,R> R invokeSCL(ReadGraph graph, Resource entity, Resource property, P0 p0) throws DatabaseException {
553 return invokeSCL(graph, getProperty(graph, entity, property), p0);
556 public static <P0,P1,R> R invokeSCL(ReadGraph graph, Resource entity, Resource property, P0 p0, P1 p1) throws DatabaseException {
557 return invokeSCL(graph, getProperty(graph, entity, property), p0, p1);
560 public static <P0,R> R tryInvokeSCL(ReadGraph graph, Resource entity, Resource property, P0 p0) throws DatabaseException {
561 Variable p = Variables.tryGetProperty(graph, entity, property);
564 return invokeSCL(graph, p, p0);
567 public static <P0,P1,R> R tryInvokeSCL(ReadGraph graph, Resource entity, Resource property, P0 p0, P1 p1) throws DatabaseException {
568 Variable p = Variables.tryGetProperty(graph, entity, property);
571 return invokeSCL(graph, p, p0, p1);
574 private static Variable getProperty(ReadGraph graph, Resource entity, Resource property) throws DatabaseException {
575 return Variables.getVariable(graph, entity).getProperty(graph, property);
578 public static boolean ensureMemoryBytes(long bytes) {
580 Runtime runtime = Runtime.getRuntime();
581 long consumedMemory = runtime.totalMemory() - runtime.freeMemory();
582 long available = runtime.maxMemory() - consumedMemory;
584 return available > bytes;
588 public static long getDiskBytes() {
590 File ws = new File(Platform.getInstanceLocation().getURL().getFile());
591 return ws.getUsableSpace();
596 * @return a service for dealing with recurring file system handling cases
598 public static FileService getFileService() {
599 FileService fs = fileService;
601 synchronized (Simantics.class) {
604 fs = fileService = new FileServiceImpl();