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.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;
65 * A facade for accessing basic Simantics platform services. Usable without a
66 * graphical UI, i.e. in headless contexts.
68 * TODO: in time, move headless functionality of SimanticsUI into this class but
69 * originals as delegates in SimanticsUI.
71 * TODO: duplicate of org.simantics.db.layer0.util.Simantics, do something about this!!
73 public class Simantics {
74 private static final Logger LOGGER = LoggerFactory.getLogger(Simantics.class);
77 * Default database driver ID
79 private static final String DEFAULT_DATABASE_DRIVER_ID = "acorn";
81 private static String defaultDatabaseDriverId = DEFAULT_DATABASE_DRIVER_ID;
83 private static ISessionContextProviderSource providerSource = null;
84 private static volatile FileServiceImpl fileService = null;
87 * Sets the database driver to be used by the platform. To have any effect,
88 * this must be set before platform startup.
92 public static void setDefaultDatabaseDriver(String id) {
93 defaultDatabaseDriverId = id;
97 * Returns currently set default database driver id.
99 public static String getDefaultDatabaseDriver() {
100 return defaultDatabaseDriverId;
107 * @throws PlatformException
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.");
114 RecoveryPolicy workspacePolicy = Platform.inDevelopmentMode() ? RecoveryPolicy.FixError : RecoveryPolicy.ThrowError;
115 OntologyRecoveryPolicy ontologyPolicy = Platform.inDevelopmentMode() ? OntologyRecoveryPolicy.Merge : OntologyRecoveryPolicy.ThrowError;
117 if (args.contains(SimanticsArguments.RECOVERY_POLICY_FIX_ERRORS)) {
118 workspacePolicy = RecoveryPolicy.FixError;
119 ontologyPolicy = OntologyRecoveryPolicy.Merge;
122 if (args.contains(SimanticsArguments.ONTOLOGY_RECOVERY_POLICY_REINSTALL)) {
123 ontologyPolicy = OntologyRecoveryPolicy.ReinstallDatabase;
126 if (args.contains(SimanticsArguments.ONTOLOGY_RECOVERY_POLICY_REINSTALL)) {
127 ontologyPolicy = OntologyRecoveryPolicy.ReinstallDatabase;
130 if (args.contains(SimanticsArguments.DISABLE_INDEX)) {
131 Indexing.setDefaultDependenciesIndexingEnabled(false);
134 String databaseDriverId = defaultDatabaseDriverId;
135 if (args.contains(SimanticsArguments.DATABASE_ID)) {
136 databaseDriverId = args.get(SimanticsArguments.DATABASE_ID);
137 Simantics.setDefaultDatabaseDriver(databaseDriverId);
141 if (args.contains(SimanticsArguments.LOCAL_SERVER_PORT)) {
143 localPort = args.get(SimanticsArguments.LOCAL_SERVER_PORT);
144 } catch (IllegalArgumentException e) {
145 throw new PlatformException("Failed to open database session", e);
149 // ServerAddress remoteDatabase = null;
150 // if (args.contains(SimanticsArguments.SERVER)) {
151 // String serverAddress = args.get(SimanticsArguments.SERVER);
153 // remoteDatabase = new ServerAddress(serverAddress);
154 // } catch (IllegalArgumentException e) {
155 // throw new PlatformException("Failed to open database session", e);
159 return startUpHeadless(progress, workspacePolicy, ontologyPolicy, localPort, databaseDriverId /*, remoteDatabase*/);
164 * @param workspacePolicy
165 * @param ontologyPolicy
167 * @param remoteDatabase
169 * @throws PlatformException
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.");
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);
182 if (progress == null)
183 progress = new NullProgressMonitor();
184 return SimanticsPlatform.INSTANCE.startUp(databaseDriverId, progress, workspacePolicy, ontologyPolicy, true, new ConsoleUserAgent());
189 * @throws PlatformException
191 public static void shutdown(IProgressMonitor progress) throws PlatformException {
192 SimanticsPlatform.INSTANCE.shutdown(progress);
196 * Queue execution of a runnable.
200 public static void async(Runnable runnable) {
201 ThreadUtils.getBlockingWorkExecutor().execute(runnable);
204 public static void async(Runnable runnable, int delay, TimeUnit unit) {
205 ThreadUtils.getTimer().schedule(runnable, delay, unit);
208 public static ScheduledFuture<?> scheduleAtFixedRate(Runnable runnable, int initialDelay, int period, TimeUnit unit) {
209 return ThreadUtils.getTimer().scheduleAtFixedRate(runnable, initialDelay, period, unit);
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.
217 * @param runnable a non-blocking runnable
219 public static void asyncNonblocking(Runnable runnable) {
220 ThreadUtils.getNonBlockingWorkExecutor().execute(runnable);
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.
228 * @param runnable a non-blocking runnable
229 * @param initialDelay
232 public static void asyncNonblocking(Runnable runnable, int initialDelay, int period) {
233 ThreadUtils.getNonBlockingWorkExecutor().scheduleAtFixedRate(runnable, initialDelay, period, TimeUnit.MILLISECONDS);
236 public static synchronized ISessionContext setSessionContext(ISessionContext ctx) {
237 return getSessionContextProvider().setSessionContext(ctx);
240 public static void setSessionContextProviderSource(ISessionContextProviderSource source) {
242 throw new IllegalArgumentException("null provider source");
243 providerSource = source;
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;
253 public static ISessionContextProvider getSessionContextProvider() {
254 return getProviderSource().getActive();
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.
262 * @return the session context associated with the currently active context
263 * or <code>null</code> if the context has no session context
265 public static ISessionContext getSessionContext() {
266 ISessionContextProvider provider = getSessionContextProvider();
267 return provider != null ? provider.getSessionContext() : null;
271 * Returns the database Session bound to the currently active context.
274 * The method always returns a non-null Session or produces an
275 * IllegalStateException if a Session was not attainable.
278 * @return the Session bound to the currently active workbench window
279 * @throws IllegalStateException if no Session was available
281 public static Session getSession() {
282 ISessionContext ctx = getSessionContext();
284 throw new IllegalStateException("Session unavailable, no database session open");
285 return ctx.getSession();
288 public static RequestProcessor getAvailableRequestProcessor() {
289 Object graph = SCLContext.getCurrent().get("graph");
290 if(graph instanceof ReadGraph)
291 return (RequestProcessor)graph;
293 return Simantics.getSession();
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.
302 * @return the Session bound to the currently active context or
305 public static Session peekSession() {
306 ISessionContext ctx = getSessionContext();
307 return ctx == null ? null : ctx.peekSession();
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
316 public static Resource getProjectResource() {
317 ISessionContext ctx = getSessionContext();
319 throw new IllegalStateException("No current database session");
320 Resource project = ctx.getHint(SimanticsKeys.KEY_PROJECT);
322 throw new IllegalStateException("No current project resource in session context " + ctx);
327 * @return the currently open and active project as a {@link Resource}
329 public static Resource peekProjectResource() {
330 ISessionContext ctx = getSessionContext();
331 return ctx != null ? ctx.<Resource>getHint(SimanticsKeys.KEY_PROJECT) : null;
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
340 public static IProject getProject() {
341 ISessionContext ctx = getSessionContext();
343 throw new IllegalStateException("No current database session");
344 IProject project = ctx.getHint(ProjectKeys.KEY_PROJECT);
346 throw new IllegalStateException("No current project in session context " + ctx);
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
354 public static IProject peekProject() {
355 ISessionContext ctx = getSessionContext();
356 return ctx == null ? null : ctx.<IProject>getHint(ProjectKeys.KEY_PROJECT);
359 // FIXME: once org.simantics.db.layer0.util.Simantics is gone, re-enable this
360 // private static SimanticsClipboard clipboard = SimanticsClipboard.EMPTY;
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);
373 public static SimanticsClipboard getClipboard() {
374 // FIXME: once org.simantics.db.layer0.util.Simantics is gone, re-enable this
376 return org.simantics.db.layer0.internal.SimanticsInternal.getClipboard();
379 public static Layer0 getLayer0() throws DatabaseException {
380 return Layer0.getInstance(getSession());
383 public static <T> T sync(ReadInterface<T> r) throws DatabaseException {
384 return getSession().sync(r);
387 public static <T> T sync(WriteInterface<T> r) throws DatabaseException {
388 return getSession().sync(r);
391 public static <T> void async(ReadInterface<T> r) {
392 getSession().async(r, new ProcedureAdapter<T>());
395 public static <T> void async(WriteInterface<T> r) {
396 getSession().async(r);
399 public static void clearTemporaryDirectory() {
400 FileUtils.deleteDir(getTemporaryDirectory());
403 public static File getTempfile(String directory, String suffix) {
404 File dir = getTemporaryDirectory(directory);
405 return new File(dir, UUID.randomUUID().toString() + "." + suffix);
408 public static File getTemporaryDirectory(String directory) {
409 File sub = new File(getTemporaryDirectory(), directory);
414 public static File getTemporaryDirectory() {
415 File workspace = Platform.getLocation().toFile();
416 File temp = new File(workspace, "tempFiles");
421 public static TempFiles getTempFiles() {
425 private static class TempFilesImpl implements TempFiles {
426 private final TempFilesImpl parent;
427 private final String prefix;
428 private final String fullPrefix;
430 private TempFilesImpl(TempFilesImpl parent, String directory) {
431 this.parent = parent;
432 this.prefix = directory;
433 this.fullPrefix = getPrefix(new StringBuilder()).toString();
436 private StringBuilder getPrefix(StringBuilder sb) {
438 parent.getPrefix(sb);
439 if (prefix != null && !prefix.isEmpty())
440 sb.append(prefix).append(File.separatorChar);
445 public File getRoot() {
446 return Simantics.getTemporaryDirectory(fullPrefix);
450 public File getTempfile(String directory, String suffix) {
451 return Simantics.getTempfile(fullPrefix.isEmpty() ? directory : fullPrefix + directory, suffix);
455 public TempFiles subdirectory(String directory) {
456 return new TempFilesImpl(this, directory);
460 public static TempFiles TEMP_FILES = new TempFilesImpl(null, null);
462 public static void flushIndexCaches(IProgressMonitor progress, Session session) {
464 IndexUtils.flushIndexCaches(progress, session);
465 } catch (Exception e) {
466 LOGGER.error("Flushing index caches failed.", e);
471 @SuppressWarnings({ "unchecked", "rawtypes" })
472 public static <T> T applySCL(String module, String function, Object ... args) throws DatabaseException {
474 T t = (T)((Function)SCLOsgi.MODULE_REPOSITORY.getValue(module, function)).applyArray(args);
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);
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);
489 return applySCL(module, function, args);
490 } catch (DatabaseException dbe) {
492 } catch (Throwable t) {
493 throw new DatabaseException(t);
495 sclContext.put("graph", oldGraph);
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);
504 return (T)f.applyArray(args);
505 } catch (Throwable t) {
506 if (t instanceof DatabaseException)
507 throw (DatabaseException) t;
508 throw new DatabaseException(t);
510 sclContext.put("graph", oldGraph);
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);
519 return (T)f.applyArray(args);
520 } catch (Throwable t) {
521 if (t instanceof DatabaseException)
522 throw (DatabaseException) t;
523 throw new DatabaseException(t);
525 sclContext.put("graph", oldGraph);
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);
533 return function.apply(p0);
534 } catch (Throwable t) {
535 if (t instanceof DatabaseException)
536 throw (DatabaseException) t;
537 throw new DatabaseException(t);
539 sclContext.put("graph", oldGraph);
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);
547 return function.apply(p0);
548 } catch (Throwable t) {
549 if (t instanceof DatabaseException)
550 throw (DatabaseException) t;
551 throw new DatabaseException(t);
553 sclContext.put("graph", oldGraph);
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);
561 return function.apply(p0, p1);
562 } catch (Throwable t) {
563 if (t instanceof DatabaseException)
564 throw (DatabaseException) t;
565 throw new DatabaseException(t);
567 sclContext.put("graph", oldGraph);
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);
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);
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);
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);
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);
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);
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);
605 return invokeSCL(graph, p, p0);
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);
612 return invokeSCL(graph, p, p0, p1);
615 private static Variable getProperty(ReadGraph graph, Resource entity, Resource property) throws DatabaseException {
616 return Variables.getVariable(graph, entity).getProperty(graph, property);
619 public static boolean ensureMemoryBytes(long bytes) {
621 Runtime runtime = Runtime.getRuntime();
622 long consumedMemory = runtime.totalMemory() - runtime.freeMemory();
623 long available = runtime.maxMemory() - consumedMemory;
625 return available > bytes;
629 public static long getDiskBytes() {
631 File ws = new File(Platform.getInstanceLocation().getURL().getFile());
632 return ws.getUsableSpace();
637 * @return a service for dealing with recurring file system handling cases
639 public static FileService getFileService() {
640 FileService fs = fileService;
642 synchronized (Simantics.class) {
645 fs = fileService = new FileServiceImpl();