]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics/src/org/simantics/SimanticsPlatform.java
Merge branch 'feature/funcwrite'
[simantics/platform.git] / bundles / org.simantics / src / org / simantics / SimanticsPlatform.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 static org.simantics.db.common.utils.Transaction.commit;
15 import static org.simantics.db.common.utils.Transaction.endTransaction;
16 import static org.simantics.db.common.utils.Transaction.readGraph;
17 import static org.simantics.db.common.utils.Transaction.startTransaction;
18 import static org.simantics.db.common.utils.Transaction.writeGraph;
19
20 import java.io.File;
21 import java.io.IOException;
22 import java.nio.file.Files;
23 import java.nio.file.Path;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Map.Entry;
30 import java.util.Properties;
31 import java.util.Set;
32 import java.util.TreeMap;
33 import java.util.UUID;
34
35 import org.eclipse.core.runtime.ILog;
36 import org.eclipse.core.runtime.IProduct;
37 import org.eclipse.core.runtime.IProgressMonitor;
38 import org.eclipse.core.runtime.IStatus;
39 import org.eclipse.core.runtime.NullProgressMonitor;
40 import org.eclipse.core.runtime.Platform;
41 import org.eclipse.core.runtime.Status;
42 import org.eclipse.core.runtime.SubMonitor;
43 import org.eclipse.osgi.service.resolver.BundleDescription;
44 import org.ini4j.Ini;
45 import org.ini4j.InvalidFileFormatException;
46 import org.simantics.databoard.Bindings;
47 import org.simantics.databoard.Databoard;
48 import org.simantics.datatypes.literal.Font;
49 import org.simantics.datatypes.literal.RGB;
50 import org.simantics.db.Driver;
51 import org.simantics.db.Driver.Management;
52 import org.simantics.db.Manager;
53 import org.simantics.db.ReadGraph;
54 import org.simantics.db.Resource;
55 import org.simantics.db.Session;
56 import org.simantics.db.SessionModel;
57 import org.simantics.db.UndoContext;
58 import org.simantics.db.VirtualGraph;
59 import org.simantics.db.WriteGraph;
60 import org.simantics.db.common.request.ObjectsWithType;
61 import org.simantics.db.common.request.Queries;
62 import org.simantics.db.common.request.WriteRequest;
63 import org.simantics.db.common.request.WriteResultRequest;
64 import org.simantics.db.common.utils.Transaction;
65 import org.simantics.db.exception.ClusterSetExistException;
66 import org.simantics.db.exception.DatabaseException;
67 import org.simantics.db.exception.ResourceNotFoundException;
68 import org.simantics.db.indexing.DatabaseIndexing;
69 import org.simantics.db.layer0.genericrelation.DependenciesRelation;
70 import org.simantics.db.layer0.util.SimanticsClipboardImpl;
71 import org.simantics.db.layer0.util.SimanticsKeys;
72 import org.simantics.db.layer0.util.TGTransferableGraphSource;
73 import org.simantics.db.layer0.variable.VariableRepository;
74 import org.simantics.db.management.SessionContext;
75 import org.simantics.db.request.Read;
76 import org.simantics.db.service.LifecycleSupport.LifecycleListener;
77 import org.simantics.db.service.LifecycleSupport.LifecycleState;
78 import org.simantics.db.service.QueryControl;
79 import org.simantics.db.service.UndoRedoSupport;
80 import org.simantics.db.service.VirtualGraphSupport;
81 import org.simantics.db.service.XSupport;
82 import org.simantics.graph.db.GraphDependencyAnalyzer;
83 import org.simantics.graph.db.GraphDependencyAnalyzer.IU;
84 import org.simantics.graph.db.GraphDependencyAnalyzer.IdentityNode;
85 import org.simantics.graph.db.IImportAdvisor;
86 import org.simantics.graph.db.ImportResult;
87 import org.simantics.graph.db.TransferableGraphs;
88 import org.simantics.graph.diff.Diff;
89 import org.simantics.graph.diff.TransferableGraphDelta1;
90 import org.simantics.internal.Activator;
91 import org.simantics.internal.startup.StartupExtensions;
92 import org.simantics.layer0.Layer0;
93 import org.simantics.operation.Layer0X;
94 import org.simantics.project.IProject;
95 import org.simantics.project.ProjectFeatures;
96 import org.simantics.project.ProjectKeys;
97 import org.simantics.project.Projects;
98 import org.simantics.project.exception.ProjectException;
99 import org.simantics.project.features.registry.GroupReference;
100 import org.simantics.project.management.DatabaseManagement;
101 import org.simantics.project.management.GraphBundle;
102 import org.simantics.project.management.GraphBundleEx;
103 import org.simantics.project.management.GraphBundleRef;
104 import org.simantics.project.management.PlatformUtil;
105 import org.simantics.project.management.ServerManager;
106 import org.simantics.project.management.ServerManagerFactory;
107 import org.simantics.project.management.WorkspaceUtil;
108 import org.simantics.utils.FileUtils;
109 import org.simantics.utils.datastructures.Pair;
110 import org.simantics.utils.logging.TimeLogger;
111 import org.simantics.utils.strings.EString;
112 import org.slf4j.Logger;
113 import org.slf4j.LoggerFactory;
114
115 /**
116  * SimanticsPlatform performs procedures required in order to get simantics
117  * workbench into operational state. This consists of the following steps:
118  * <ul>
119  *     <li> Asserting there is Database
120  *     </li>
121  *     <li> Starting Database process
122  *     </li>
123  *     <li> Opening a session to Database process
124  *     </li>
125  *     <li> Asserting required ontologies or other transferable graphs are installed in the database
126  *     </li>
127  *     <li> Asserting required project is installed in the database
128  *     </li>
129  *     <li> Asserting Simantics Features are installed in the database
130  *     </li>
131  *     <li> Asserting Simantics Features are installed to the project
132  *     </li>
133  *     <li> Shutdown: Save Session, Close session, Kill Database process
134  *     </li>
135  * </ul>
136  *
137  * @author Toni Kalajainen <toni.kalajainen@vtt.fi>
138  */
139 public class SimanticsPlatform implements LifecycleListener {
140
141     private static final Logger LOGGER = LoggerFactory.getLogger(SimanticsPlatform.class);
142     
143     /**
144      * The policy is relevant when developing Simantics from Eclipse IDE.
145      * It is applied when the ontology in the database of a workspace doesn't match
146      * a newer ontology in the Eclipse workspace.
147      */
148     public static enum OntologyRecoveryPolicy { ThrowError, Merge, ReinstallDatabase }
149
150     /**
151      * This policy dictates how the Simantics platform startup should react if
152      * the started workspace is not set up properly. The alternatives are to
153      * just throw an error and fail or to attempt all possible measures to fix
154      * the encountered problems.
155      */
156     public static enum RecoveryPolicy { ThrowError, FixError }
157
158     /** Singleton instance, started in SimanticsWorkbenchAdvisor */
159     public static final SimanticsPlatform INSTANCE = new SimanticsPlatform();
160
161     /** Set to true when the Simantics Platform is in good-and-go condition */
162     public boolean running;
163
164     /** ID of the database driver that the platform is currently using */
165     private String currentDatabaseDriver;
166
167     /** Database Session */
168     public Session session;
169     private Management databasebManagement;
170
171     /** Database session context */
172     public SessionContext sessionContext;
173
174     /** Project identifier in Database */
175     public String projectURI;
176
177     /** Project name */
178     public String projectName;
179
180     /** Project resource */
181     public Resource projectResource;
182
183     /** Session specific bindings */
184     public SimanticsBindings simanticsBindings;
185     public SimanticsBindings simanticsBindings2;
186
187     public Thread mainThread;
188
189     /**
190      * The {@link IProject} activated by
191      * {@link #startUp(IProgressMonitor, RecoveryPolicy, OntologyRecoveryPolicy, ServerAddress, PlatformUserAgent)}
192      */
193     private IProject project;
194
195     protected ILog log;
196
197     /**
198      * Create a new simantics plaform manager in uninitialized state and
199      * with default policies. <p>
200      */
201     public SimanticsPlatform() {
202         log = Platform.getLog(Activator.getBundleContext().getBundle());
203         mainThread = Thread.currentThread();
204     }
205
206     public String getApplicationClientId() {
207         IProduct product = Platform.getProduct();
208         if(product == null) return "noProduct";//UUID.randomUUID().toString();
209         String application = product.getApplication();
210         return application != null ? application : UUID.randomUUID().toString();
211     }
212
213     private Session setupDatabase(String databaseDriverId, IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy, PlatformUserAgent userAgent) throws PlatformException {
214         if (progressMonitor == null)
215             progressMonitor = new NullProgressMonitor();
216         Path workspaceLocation = Platform.getLocation().toFile().toPath();
217         Path dbLocation = workspaceLocation.resolve("db");
218         Path dbIniPath = workspaceLocation.resolve("db.ini");
219         // The driver file overrides any command line arguments to prevent
220         // using the wrong driver for an existing database directory.
221         ServerManager serverManager;
222         try {
223             Ini dbIni = loadOrCreateDatabaseIni(dbIniPath, databaseDriverId);
224             databaseDriverId = dbIni.get("driver", "id");
225             serverManager = ServerManagerFactory.create(databaseDriverId, dbLocation.toAbsolutePath().toString());
226         } catch (DatabaseException | IOException e) {
227             throw new PlatformException("Failed to initialize database ServerManager with driver " + databaseDriverId, e);
228         }
229         progressMonitor.beginTask("Setting up Simantics Database", 100);
230         progressMonitor.setTaskName("Asserting Database is installed.");
231         String msg = "Failed to initialize Simantics database.";
232         try {
233             // Create database
234             log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Initializing database at " + dbLocation + " with driver " + databaseDriverId));
235             progressMonitor.setTaskName("Creating database at " + dbLocation);
236             databasebManagement = serverManager.getManagement(dbLocation.toFile());
237             databasebManagement.create();
238             currentDatabaseDriver = databaseDriverId;
239             // Create layer0.
240             return serverManager.createDatabase(dbLocation.toFile());
241         } catch (DatabaseException e) {
242             throw new PlatformException(msg, e);
243         } catch (Throwable e) {
244             throw new PlatformException(msg, e);
245         } finally {
246             progressMonitor.worked(20);
247         }
248     }
249
250     public void synchronizeOntologies(IProgressMonitor progressMonitor, OntologyRecoveryPolicy ontologyPolicy, boolean requireSynchronize) throws PlatformException {
251
252         if (progressMonitor == null) progressMonitor = new NullProgressMonitor();
253
254         final DatabaseManagement mgmt = new DatabaseManagement();
255
256         PlatformUtil.compileAllDynamicOntologies();
257
258         progressMonitor.setTaskName("Asserting all ontologies are installed");
259         final Map<GraphBundleRef, GraphBundleEx> platformTGs = new HashMap<GraphBundleRef, GraphBundleEx>();
260         try {
261
262             // Get a list of bundles installed into the database
263             progressMonitor.subTask("find installed bundles from database");
264             Map<GraphBundleRef, GraphBundleEx> installedTGs = new HashMap<GraphBundleRef, GraphBundleEx>();
265             for (GraphBundle b : session.syncRequest( mgmt.GraphBundleQuery )) {
266                 installedTGs.put(GraphBundleRef.of(b), GraphBundleEx.extend(b));
267             }
268
269             if(!requireSynchronize && installedTGs.size() > 1 && !Platform.inDevelopmentMode()) return;
270 //            if(installedTGs.size() > 1) return;
271
272             // Get a list of all bundles in the platform (Bundle Context)
273             List<GraphBundle> tgs = new ArrayList<GraphBundle>();
274             progressMonitor.subTask("load all transferable graphs from platform");
275             PlatformUtil.getAllGraphs(tgs);
276             progressMonitor.subTask("extend bundles to compile versions");
277             for (GraphBundle b : tgs) {
278                 GraphBundleEx gbe = GraphBundleEx.extend(b);
279                 gbe.build();
280                 platformTGs.put(GraphBundleRef.of(b), gbe);
281             }
282
283             // Compile a list of TGs that need to be installed or reinstalled in the database
284             progressMonitor.subTask("check bundle reinstallation demand");
285             List<GraphBundleEx> installTGs = new ArrayList<GraphBundleEx>();
286             // Create list of TGs to update, <newTg, oldTg>
287             Map<GraphBundleEx,GraphBundleEx> reinstallTGs = new TreeMap<GraphBundleEx,GraphBundleEx>();
288             for (Entry<GraphBundleRef, GraphBundleEx> e : platformTGs.entrySet()) {
289                 GraphBundleRef key = e.getKey();
290                 GraphBundleEx platformBundle = e.getValue();
291                 GraphBundleEx existingBundle = installedTGs.get(key);
292                 
293 //                System.out.println("GraphBundleRef key=" + key.toString());
294                 
295                 if (existingBundle == null) {
296                     // Bundle did not exist in the database, put it into list of bundles to install
297                     installTGs.add(platformBundle);
298                 }
299                 else {
300                     // Bundle exists in the database
301                     boolean platformBundleIsNewer = existingBundle.getVersion().compareTo(platformBundle.getVersion())<0;
302                     if (!platformBundleIsNewer)
303                         continue;
304                     // Check hash of transferable graph to know whether to update or not.
305                     if (platformBundle.getHashcode() == existingBundle.getHashcode())
306                         continue;
307                     //System.out.println("Ontology hashcodes do not match: platform bundle="
308                     //        + platformBundle.getVersionedId() + ", hash=" + platformBundle.getHashcode()
309                     //        + "; existing bundle=" + existingBundle.getVersionedId() + ", hash=" + existingBundle.getHashcode());
310                     reinstallTGs.put(platformBundle, existingBundle);
311                 }
312             }
313             // INSTALL
314             // Database is missing graphs
315             if (!installTGs.isEmpty() || !reinstallTGs.isEmpty()) {
316                 session.getService(XSupport.class).setServiceMode(true, true);
317
318                 // Throw error
319                 if (ontologyPolicy == OntologyRecoveryPolicy.ThrowError) {
320                     StringBuilder sb = new StringBuilder("The following graphs are not installed in the database: ");
321                     if (!installTGs.isEmpty()) {
322                         int i = 0;
323                         for (GraphBundleEx e : installTGs) {
324                             if (i>0) sb.append(", ");
325                             i++;
326                             sb.append(e.toString());
327                         }
328                         sb.append(" is missing from the database.\n");
329                     }
330                     if (!reinstallTGs.isEmpty()) {
331                         int i = 0;
332                         for (Entry<GraphBundleEx, GraphBundleEx> e : reinstallTGs.entrySet()) {
333                             if (i>0) sb.append(", ");
334                             i++;
335                             sb.append(e.getKey().toString());
336                         }
337                         sb.append(" Database/Platform Bundle version mismatch.\n");
338                     }
339                     sb.append("Hint: Use -fixErrors to install the graphs.");
340                     throw new PlatformException(sb.toString());
341                 }
342                 // Reinstall database
343                 if (ontologyPolicy == OntologyRecoveryPolicy.ReinstallDatabase) {
344                     log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Reinstalling the database."));
345                     // TODO Install DB
346                     // Stop Session
347                     // Kill Process
348                     // Delete Database
349                     // Create Database
350                     // Start Database
351                     // Open Session
352                     // Install TGs
353                     throw new PlatformException("Reinstalling Database, NOT IMPLEMENTED");
354                 }
355
356                 if (ontologyPolicy == OntologyRecoveryPolicy.Merge) {
357                     progressMonitor.subTask("Merging ontology changes");
358                     // Sort missing TGs into install order
359                     GraphDependencyAnalyzer<GraphBundle> analyzer = new GraphDependencyAnalyzer<GraphBundle>();
360                     for(GraphBundle tg : installTGs) analyzer.addGraph(tg, tg.getGraph());
361                     for(GraphBundle tg : reinstallTGs.keySet()) analyzer.addGraph(tg, tg.getGraph());
362                     if(!analyzer.analyzeDependency()) {
363                         Collection<Pair<GraphBundle, GraphBundle>> problems = analyzer.getConflicts();
364                         StringBuilder sb = new StringBuilder();
365                         for (Pair<GraphBundle, GraphBundle> problem : problems) {
366                             sb.append("Conflict with "+problem.first+" and "+problem.second+".\n");
367                         }
368                         throw new PlatformException(sb.toString());
369                     }
370                     else if(!session.syncRequest( analyzer.queryExternalDependenciesSatisfied )) {
371                         Collection<IdentityNode> unsatisfiedDependencies = analyzer.getUnsatisfiedDependencies();
372                         StringBuilder sb = new StringBuilder();
373                         for (IdentityNode dep: unsatisfiedDependencies) {
374                             sb.append("Unsatisfied Dependency "+dep+". Required by\n");
375                             for(IU iu : GraphDependencyAnalyzer.toCollection(dep.getRequires())) {
376                                 sb.append("    " + ((GraphBundle)iu.getId()).getId() + "\n");
377                             }
378                         }
379                         throw new PlatformException(sb.toString());
380                     }
381                     
382                     List<GraphBundle> sortedBundles = analyzer.getSortedGraphs();
383                     if(!sortedBundles.isEmpty()) {
384                         
385                         session.syncRequest(new WriteRequest() {
386                             @Override
387                             public void perform(WriteGraph graph) throws DatabaseException {
388                                 try {
389                                     graph.newClusterSet(graph.getRootLibrary());
390                                 } catch (ClusterSetExistException e) {
391                                     // Cluster set exist already, no problem.
392                                 }
393                                 graph.setClusterSet4NewResource(graph.getRootLibrary());
394                                 graph.flushCluster();
395                             }
396                         });
397
398                         boolean mergedOntologies = false;
399
400                         // Install TGs
401                         for(final GraphBundle tg : sortedBundles) {
402
403                                 final IImportAdvisor advisor = new OntologyImportAdvisor(tg, mgmt);
404                                 final GraphBundle oldTG = reinstallTGs.get(tg);
405
406                                 if (oldTG==null) {
407                                         
408                                         boolean createImmutable = tg.getImmutable();
409                                 session.getService(XSupport.class).setServiceMode(true, createImmutable);
410
411                                         // Install TG
412                                         log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Installing "+tg.toString()+" - "+tg.getName()));
413                                         ImportResult result = TransferableGraphs.importGraph1(session, new TGTransferableGraphSource(tg.getGraph()), advisor, null);
414                                         if (!result.missingExternals.isEmpty()) {
415                                                 log.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import of " + tg.toString() + " was missing the following external entities:\n" + EString.implode(result.missingExternals)));
416                                         }
417                                 } else {
418                                         // Merge TG
419                                         startTransaction(session, false);
420                                         TransferableGraphDelta1 delta = new Diff(oldTG.getGraph(), tg.getGraph()).diff();
421                                         final long[] oldResources = oldTG.getResourceArray();
422                                         boolean changes = TransferableGraphs.hasChanges(readGraph(), oldResources, delta);
423                                         endTransaction();
424                                         if (!changes) {
425                                             //log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Nothing to merge for "+tg.toString()));
426                                             continue;
427                                         }
428
429                                 log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, "Merging new version of "+tg.toString()));
430
431                                         startTransaction(session, true);
432                                         
433                                         //delta.print();
434                                         try {
435                                                 
436                                                 
437                                                 long[] resourceArray = TransferableGraphs.applyDelta(writeGraph(), oldResources, delta);
438                                                 tg.setResourceArray(resourceArray);
439                                                 mgmt.setGraphBundleEntry(tg);
440                                                 commit();
441                                                 mergedOntologies = true;
442                                         } catch (Throwable t) {
443                                                 throw new PlatformException(t);
444                                         } finally {
445                                                 endTransaction();
446                                         }
447                                 }
448                         }
449                         
450                         session.syncRequest(new WriteRequest() {
451                             @Override
452                             public void perform(WriteGraph graph) throws DatabaseException {
453                                 graph.setClusterSet4NewResource(graph.getRootLibrary());
454                                 graph.flushCluster();
455                             }
456                         });
457
458                         if (mergedOntologies)
459                             DatabaseIndexing.deleteAllIndexes();
460                     }
461
462                     TimeLogger.log("Ontologies synchronized.");
463                     
464                 }
465                 session.getService(XSupport.class).setServiceMode(false, false);
466             }
467             progressMonitor.worked(20);
468         } catch (IOException e) {
469             throw new PlatformException(e);
470         } catch (DatabaseException e) {
471             throw new PlatformException(e);
472         }
473
474     }
475
476     public boolean assertConfiguration(IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy) throws PlatformException {
477
478         if (progressMonitor == null) progressMonitor = new NullProgressMonitor();
479
480         File workspaceLocation = Platform.getLocation().toFile();
481
482         boolean installProject = false;
483         progressMonitor.setTaskName("Asserting simantics.cfg is installed");
484         try {
485             File propertyFile = new File(workspaceLocation, "simantics.cfg");
486             Properties properties;
487             try {
488                 properties = WorkspaceUtil.readProperties(propertyFile);
489             } catch (IOException e) {
490                 if (workspacePolicy == RecoveryPolicy.ThrowError) throw new PlatformException("Could not load "+propertyFile);
491
492                 // Create a project and write Property file
493                 properties = new Properties();
494                 properties.setProperty("project_uri", "http://Projects/Development%20Project");
495                 properties.setProperty("project_name", "Development Project");
496                 WorkspaceUtil.writeProperties(propertyFile, properties);
497                 installProject |= true;
498             }
499             projectURI = properties.getProperty("project_uri");
500             projectName = properties.getProperty("project_name");
501             progressMonitor.worked(10);
502         } catch (IOException e) {
503             throw new PlatformException(e);
504         }
505
506         return installProject;
507
508     }
509
510     public boolean assertProject(IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy, boolean installProject) throws PlatformException {
511
512         if (progressMonitor == null) progressMonitor = new NullProgressMonitor();
513
514         final DatabaseManagement mgmt = new DatabaseManagement();
515
516         progressMonitor.setTaskName("Asserting project resource exists in the database");
517         try {
518             projectResource = session.syncRequest( Queries.resource( projectURI ) );
519         } catch (ResourceNotFoundException nfe) {
520             // Project was not found
521             if (workspacePolicy == RecoveryPolicy.ThrowError)
522                 throw new PlatformException("Project Resource "+projectURI+" is not found in the database.");
523             // Create empty project with no features
524             try {
525                 Transaction.startTransaction(session, true);
526                 try {
527                     // The project needs to be created mutable.
528                     session.getService(XSupport.class).setServiceMode(true, false);
529
530                     ArrayList<String> empty = new ArrayList<String>();
531                     projectResource = mgmt.createProject(projectName, empty);
532                     installProject |= true;
533
534                     session.getService(XSupport.class).setServiceMode(false, false);
535                     Transaction.commit();
536                 } finally {
537                     Transaction.endTransaction();
538                 }
539                 //session.getService( LifecycleSupport.class ).save();
540             } catch (DatabaseException e) {
541                 throw new PlatformException("Failed to create "+projectURI, e);
542             }
543         } catch (DatabaseException e) {
544             throw new PlatformException("Failed to create "+projectURI, e);
545         }
546         progressMonitor.worked(10);
547
548         return installProject;
549
550     }
551
552     public void updateInstalledGroups(IProgressMonitor progressMonitor, boolean installProject) throws PlatformException {
553
554         if (installProject)
555         {
556             // Attach all feature groups available in platform to created project
557             progressMonitor.setTaskName("Install all features");
558             Set<GroupReference> publishedFeatureGroups = ProjectFeatures.getInstallGroupsOfPublishedFeatures();
559             Collection<GroupReference> groupsWithoutVersion = GroupReference.stripVersions(publishedFeatureGroups);
560
561     //        final List<String> Platform_Features = new ArrayList<String>();
562     //
563     //        // Convert graph instances
564     //        Collection<TransferableGraph1> platformGraphs = new ArrayList<TransferableGraph1>();
565     //        for (GraphBundleEx e : platformTGs.values()) platformGraphs.add( e.getGraph() );
566     //        IGraph graph = Graphs.createGraph(platformGraphs);
567     //
568     //        Res    PublishedProjectFeatures = UriUtils.uriToPath( ProjectResource.URIs.PublishedProjectFeatures );
569     //        Path   HasFeature = UriUtils.uriToPath( ProjectResource.URIs.HasFeature );
570     //        for(Res feature : graph.getObjects(PublishedProjectFeatures, HasFeature)) {
571     //            System.out.println("Installing Project Feature: "+feature.toString());
572     //            Platform_Features.add( feature.toString() );
573     //        }
574
575             try {
576                 Transaction.startTransaction(session, true);
577                 try {
578     //                for (String feature : Platform_Features) {
579     //                    try {
580     //                        getResource(feature);
581     //                    } catch(ResourceNotFoundException e) {
582     //                        System.out.println(feature+" not found");
583     //                    }
584     //                    mgmt.installFeature(projectResource, feature);
585     //                }
586                     Projects.setProjectInstalledGroups(writeGraph(), projectResource, groupsWithoutVersion);
587                     Transaction.commit();
588                 } finally {
589                     Transaction.endTransaction();
590                 }
591                 //session.getService( LifecycleSupport.class ).save();
592             } catch(DatabaseException ae) {
593                 throw new PlatformException("Failed to install features", ae);
594             }
595             progressMonitor.worked(10);
596         }
597
598     }
599
600     public void assertSessionModel(IProgressMonitor progressMonitor) throws PlatformException {
601
602         Properties properties = session.getService(Properties.class);
603         final String clientId = properties.getProperty("clientId");
604
605         try {
606
607             // Currently this needs to be done before data becomes available
608             VirtualGraphSupport support = session.getService(VirtualGraphSupport.class);
609             VirtualGraph activations = support.getWorkspacePersistent("activations");
610
611             Resource sessionModel = session.syncRequest(new Read<Resource>() {
612
613                 @Override
614                 public Resource perform(ReadGraph graph) throws DatabaseException {
615
616                     Layer0X L0X = Layer0X.getInstance(graph);
617                     for(Resource sessionModel : graph.syncRequest(new ObjectsWithType(graph.getRootLibrary(), L0X.HasSession, L0X.Session))) {
618                         String id = graph.getPossibleRelatedValue(sessionModel, L0X.Session_HasClientId);
619                         if(id != null && id.equals(clientId)) return sessionModel;
620                     }
621                     return null;
622
623                 }
624
625             });
626
627             if(sessionModel == null) {
628
629                 sessionModel = session.syncRequest(new WriteResultRequest<Resource>(activations) {
630
631                     @Override
632                     public Resource perform(WriteGraph graph) throws DatabaseException {
633                         Layer0 L0 = Layer0.getInstance(graph);
634                         Layer0X L0X = Layer0X.getInstance(graph);
635                         Resource session = graph.newResource();
636                         graph.claim(session, L0.InstanceOf, null, L0X.Session);
637                         graph.claim(session, L0X.Session_HasUser, null, graph.getResource("http://Users/AdminUser"));
638                         graph.addLiteral(session, L0X.Session_HasClientId, L0X.Session_HasClientId_Inverse, clientId, Bindings.STRING);
639                         graph.claim(graph.getRootLibrary(), L0X.HasSession, session);
640                         return session;
641                     }
642                 });
643
644             }
645
646             session.registerService(SessionModel.class, new PlatformSessionModel(sessionModel));
647         } catch (DatabaseException e) {
648             throw new PlatformException(e);
649         }
650
651     }
652
653     static class PlatformSessionModel implements SessionModel {
654         private final Resource sessionModel;
655
656         public PlatformSessionModel(Resource model) {
657             this.sessionModel = model;
658         }
659
660         @Override
661         public Resource getResource() {
662             return sessionModel;
663         }
664     }
665
666     public void resetDatabase(IProgressMonitor monitor) throws PlatformException {
667         File dbLocation = Platform.getLocation().append("db").toFile();
668         if(!dbLocation.exists()) return;
669         try { // Load driver
670             Driver driver = Manager.getDriver("procore");
671             Management management = driver.getManagement(dbLocation.getAbsolutePath(), null);
672             management.delete();
673         } catch (DatabaseException e) {
674             throw new PlatformException("Failed to remove database at " + dbLocation.getAbsolutePath(), e);
675         }
676         // We have created extra files to database folder which have to be deleted also.
677         // This is an awful idea! Do not create extra files to database folder!
678         Throwable t = null;
679         for (int i=0; i<10; ++i) {
680             try {
681                 FileUtils.deleteAll(dbLocation);
682                 t = null;
683                 break;
684             } catch (IOException e) {
685                 // Assuming this has been thrown because delete file/folder failed.
686                 t = e;
687             }
688             try {
689                 Thread.sleep(200);
690             } catch (InterruptedException e) {
691                 // Ignoring interrupted exception.
692             }
693         }
694         if (null != t)
695             throw new PlatformException("Failed to remove database folder at " + dbLocation.getAbsolutePath(), t);
696     }
697     public void resetWorkspace(IProgressMonitor monitor, ArrayList<String> fileFilter) throws PlatformException, IllegalStateException, IOException {
698         File file = Platform.getLocation().toFile();
699         if (null != fileFilter)
700             FileUtils.deleteAllWithFilter(file , fileFilter);
701         resetDatabase(monitor);
702     }
703
704     /**
705      * Start-up the platform. The procedure consists of 8 steps. Once everything
706      * is up and running, all fields are set property.
707      * <p>
708      *
709      * If workspacePolicy is FixErrors, there is an attempt to fix unexpected
710      * errors. It includes installing database files, installing ontologies, and
711      * installing project features.
712      * <p>
713      *
714      * In SWB this is handled in SimanticsWorkbenchAdvisor#openWindows().
715      * <p>
716      *
717      * If remote server is given, simantics plaform takes connection there
718      * instead of local server at "db/".
719      *
720      * @param workspacePolicy action to take on workspace/database related
721      *        errors
722      * @param ontologyPolicy action to take on ontology mismatch
723      * @param progressMonitor optional progress monitor
724      * @param userAgent interface for resorting to user feedback during platform
725      *        startup or <code>null</code> to resort to default measures
726      * @throws PlatformException
727      */
728     public SessionContext startUp(String databaseDriverId, IProgressMonitor progressMonitor, RecoveryPolicy workspacePolicy,
729             OntologyRecoveryPolicy ontologyPolicy, boolean requireSynchronize, PlatformUserAgent userAgent)
730     throws PlatformException
731     {
732
733         assert(!running);
734         TimeLogger.log("Beginning of SimanticsPlatform.startUp");
735
736         LOGGER.info("Beginning of SimanticsPlatform.startUp");
737         
738         if (progressMonitor == null) progressMonitor = new NullProgressMonitor();
739
740         // For debugging on what kind of platform automatic tests are running in
741         // case there are problems.
742         if ("true".equals(System.getProperty("org.simantics.dumpBundleState")))
743             dumpPlatformBundleState();
744
745         // 0. Consult all startup extensions before doing anything with the workspace.
746         StartupExtensions.consultStartupExtensions();
747         TimeLogger.log("Consulted platform pre-startup extensions");
748
749         // 0.1. Clear all temporary files
750         Simantics.clearTemporaryDirectory();
751         TimeLogger.log("Cleared temporary directory");
752
753         // 0.2 Clear VariableRepository.repository static map which holds references to SessionImplDb
754         VariableRepository.clear();
755         
756         // 1. Assert there is a database at <workspace>/db
757         session = setupDatabase(databaseDriverId, progressMonitor, workspacePolicy, userAgent);
758         TimeLogger.log("Database setup complete");
759         
760         // 1.1 
761         XSupport support = session.getService(XSupport.class);
762         if (support.rolledback()) {
763             try {
764                 DatabaseIndexing.deleteAllIndexes();
765             } catch (IOException e) {
766                 throw new PlatformException(e);
767             }
768         }
769         
770         // 2. Assert all graphs, and correct versions, are installed to the database
771         synchronizeOntologies(progressMonitor, ontologyPolicy, requireSynchronize);
772         TimeLogger.log("Synchronized ontologies");
773
774         // 4. Assert simantics.cfg exists
775         boolean installProject = assertConfiguration(progressMonitor,workspacePolicy);
776
777         // 5. Assert Project Resource is installed in the database
778         installProject = assertProject(progressMonitor, workspacePolicy, installProject);
779
780         // 6. Install all features into project, if in debug mode
781         updateInstalledGroups(progressMonitor, installProject);
782         TimeLogger.log("Installed all features into project");
783
784         // 7. Assert L0.Session in database for this session
785         assertSessionModel(progressMonitor);
786
787         session.getService(XSupport.class).setServiceMode(false, false);
788
789         try {
790             session.sync(new WriteRequest() {
791
792                 @Override
793                 public void perform(WriteGraph graph) throws DatabaseException {
794                     QueryControl qc = graph.getService(QueryControl.class);
795                     qc.flush(graph);
796                 }
797
798             });
799             TimeLogger.log("Flushed queries");
800         } catch (DatabaseException e) {
801             LOGGER.error("Flushing queries failed.", e);
802         }
803         boolean loadProject = true;
804         try {
805
806                 sessionContext = SimanticsPlatform.INSTANCE.createSessionContext(true);
807                 // This must be before setSessionContext since some listeners might query this
808             sessionContext.setHint(SimanticsKeys.KEY_PROJECT, SimanticsPlatform.INSTANCE.projectResource);
809
810             Simantics.setSessionContext(sessionContext);
811
812             // 1. Put ResourceBinding that throws an exception to General Bindings
813             simanticsBindings = new SimanticsBindings( null );
814             Bindings.classBindingFactory.addFactory( simanticsBindings );
815
816
817             // 2. Create session-specific second Binding context (Databoard) and
818             //    put that to Session as a service
819             Session session = sessionContext.getSession();
820             Databoard sessionDataboard = new Databoard();
821             session.registerService(Databoard.class, sessionDataboard);
822             simanticsBindings2 = new SimanticsBindings( session );
823             sessionDataboard.classBindingFactory.addFactory( simanticsBindings2 );
824
825             // Register datatype bindings
826             Bindings.defaultBindingFactory.getRepository().put(RGB.Integer.BINDING.type(), RGB.Integer.BINDING);
827             Bindings.defaultBindingFactory.getRepository().put(Font.BINDING.type(), Font.BINDING);
828
829             if(loadProject) {
830
831                 TimeLogger.log("Load projects");
832                 project = Projects.loadProject(sessionContext.getSession(), SimanticsPlatform.INSTANCE.projectResource);
833
834                 sessionContext.setHint(ProjectKeys.KEY_PROJECT, project);
835                 TimeLogger.log("Loading projects complete");
836
837                 project.activate();
838                 TimeLogger.log("Project activated");
839             }
840
841         } catch (DatabaseException e) {
842             LOGGER.error("Platform startup failed.", e);
843             throw new PlatformException(e);
844         } catch (ProjectException e) {
845             boolean hasStackTrace = e.getStackTrace().length > 0;
846             if (!hasStackTrace)
847                 throw new PlatformException(e.getMessage(), hasStackTrace);
848             throw new PlatformException(e, hasStackTrace);
849         }
850
851         running = true;
852
853         return sessionContext;
854
855     }
856
857     public SessionContext createSessionContext(boolean init) throws PlatformException {
858         try {
859             // Construct and initialize SessionContext from Session.
860             SessionContext sessionContext = SessionContext.create(session, init);
861             if (init)
862                 sessionContext.registerServices();
863             return sessionContext;
864         } catch (DatabaseException e) {
865             throw new PlatformException(e);
866         }
867     }
868
869 //    private static File getIgnorePrerequisitesFile(URL workspaceUrl) {
870 //        if (workspaceUrl == null)
871 //            return null;
872 //        return new File(workspaceUrl.getPath(), ".ignorePrerequisites");
873 //    }
874 //
875 //    private void ensurePrerequisites(IProgressMonitor progressMonitor, PlatformUserAgent userAgent) throws PlatformException {
876 //        Location loc = Platform.getInstanceLocation();
877 //        File ignorePrerequisites = getIgnorePrerequisitesFile(loc.getURL());
878 //        if (loc.isSet() && ignorePrerequisites != null) {
879 //            if (ignorePrerequisites.exists() || ignorePrerequisites.isFile())
880 //                return;
881 //        }
882 //
883 //        try {
884 //            ServerEnvironment.ensureServerDependenciesMet();
885 //        } catch (ExecutionEnvironmentException e) {
886 //            // Not installed properly, ask user whether to try installation.
887 //            try {
888 //                StringBuilder msg = new StringBuilder();
889 //                msg.append("Your system seems to be missing the following prerequisites for running this application:\n\n");
890 //                for (Product product : e.requiredProducts)
891 //                    msg.append("\t" + product.getDescription() + "\n");
892 //                msg.append("\nYou can either install the missing components now or ignore and attempt to start the application without them. Ignore Always will ignore this question for this workspace.");
893 //                msg.append("\n\nSelecting Cancel will close the application.");
894 //
895 //                int selection = 0;
896 //                if (userAgent != null) {
897 //                    selection = userAgent.showPrompt("Missing Prerequisites", msg.toString(), new String[] {
898 //                        "Install Pre-requisites",
899 //                        "Ignore Now",
900 //                        "Ignore Always",
901 //                        "Cancel"
902 //                    }, selection);
903 //                }
904 //                boolean tryInstall = false;
905 //                switch (selection) {
906 //                    case 0:
907 //                        tryInstall = true;
908 //                        break;
909 //                    case 2:
910 //                        ignorePrerequisites.createNewFile();
911 //                    case 1:
912 //                        break;
913 //                    case 3:
914 //                    case -1:
915 //                        throw new CancelStartupException();
916 //                }
917 //
918 //                if (tryInstall) {
919 //                    // Try to install it and check for success afterwards.
920 //                    ServerEnvironment.tryInstallDependencies(progressMonitor);
921 //                    ServerEnvironment.ensureServerDependenciesMet();
922 //                }
923 //            } catch (InstallException ie) {
924 //                throw new PlatformException(ie);
925 //            } catch (ExecutionEnvironmentException eee) {
926 //                throw new PlatformException(eee);
927 //            } catch (IOException ie) {
928 //                throw new PlatformException(ie);
929 //            }
930 //        }
931 //    }
932
933     /**
934      * Shutdown Simantics Platform.
935      *
936      * In SWB this is handled in SimanticsWorkbenchAdvisor#disconnectFromWorkspace.
937      *
938      * @param progressMonitor optional progress monitor
939      * @throws PlatformException
940      */
941     public void shutdown(IProgressMonitor progressMonitor) throws PlatformException
942     {
943         SubMonitor progress = SubMonitor.convert(progressMonitor, 100);
944         PlatformException platformException = null;
945         try {
946             progress.subTask("Close Project");
947             if (project != null) {
948                 project.safeDispose();
949             }
950             progress.worked(10);
951
952             running = false;
953             progress.subTask("Close Database Session");
954             Databoard databoard = null;
955             if (sessionContext != null) {
956                 Session s = sessionContext.peekSession();
957                 if (s != null) {
958                     databoard = s.peekService(Databoard.class);
959
960                     progress.subTask("Flushing Index Caches");
961                     try {
962                         Simantics.flushIndexCaches(progress.newChild(20), s);
963                     } catch (Throwable t) {
964                         LOGGER.error("Failed to flush index caches.", t);
965                     }
966                 }
967
968                 progress.subTask("Close Database Session");
969                 sessionContext.safeDispose();
970                 sessionContext = null;
971                 Simantics.setSessionContext(null);
972             }
973             if (simanticsBindings != null) {
974                 Bindings.classBindingFactory.removeFactory( simanticsBindings );
975                 simanticsBindings = null;
976             }
977             if (databoard != null) {
978                 if (simanticsBindings2 != null) {
979                         databoard.classBindingFactory.removeFactory( simanticsBindings2 );
980                         simanticsBindings2 = null;
981                 }
982                 databoard.clear();
983             }
984
985             // Make sure Simantics clipboard doesn't store unwanted session data references.
986             Simantics.setClipboard(new SimanticsClipboardImpl());
987
988             progress.worked(30);
989
990             session = null;
991             projectResource = null;
992             currentDatabaseDriver = null;
993
994             DependenciesRelation.assertFinishedTracking();
995
996         } catch (Exception e) {
997             platformException = new PlatformException("Failed to shutdown Simantics Platform", e);
998         }
999
1000         progress.worked(10);
1001         progress.subTask("Shutting down database");
1002         try {
1003             if (null != databasebManagement)
1004                 databasebManagement.shutdown();
1005         } catch (Throwable t) {
1006             LOGGER.error("Database shutdown failed.", t);
1007         }
1008         progress.worked(10);
1009
1010         progress.subTask("Clearing Workspace Temporary Directory");
1011         try {
1012             Simantics.clearTemporaryDirectory();
1013         } catch (Throwable t) {
1014             LOGGER.error("Failed to clear the temporary directory.", t);
1015         }
1016         progress.worked(10);
1017         if (null != platformException)
1018             throw platformException;
1019     }
1020
1021     // TODO: consider removing this in the future ??
1022     @Override
1023     public void stateChanged(LifecycleState newState) {
1024         if(newState == LifecycleState.CLOSED) {
1025             if(running) {
1026                 if(Platform.isRunning()) {
1027                     mainThread.interrupt();
1028                 }
1029             }
1030         }
1031     }
1032
1033     /**
1034      * @return <code>true</code> if discard was successful, <code>false</code>
1035      *         if there was no session, {@link UndoRedoSupport} or
1036      *         {@link UndoContext} to discard through
1037      */
1038     public boolean discardSessionUndoHistory() {
1039         Session s = session;
1040         if (s != null) {
1041             UndoRedoSupport urs = s.peekService(UndoRedoSupport.class);
1042             if (urs != null) {
1043                 UndoContext uc = urs.getUndoContext(s);
1044                 if (uc != null) {
1045                     uc.clear();
1046                     return true;
1047                 }
1048             }
1049         }
1050         return false;
1051     }
1052
1053     public void reconnect(String databaseDriverId) throws Exception {
1054         // Starts database server.
1055         if (currentDatabaseDriver != null)
1056             databaseDriverId = currentDatabaseDriver;
1057         SimanticsPlatform.INSTANCE.startUp(databaseDriverId, null, RecoveryPolicy.ThrowError, OntologyRecoveryPolicy.ThrowError, true, null);
1058     }
1059
1060     private void dumpPlatformBundleState() {
1061         BundleDescription[] bs = Platform.getPlatformAdmin().getState().getBundles();
1062         System.out.println("Total bundles: " + bs.length);
1063         for (BundleDescription b : bs) {
1064             System.out.format("%-80s @ %s\n", b.toString(), b.getLocation());
1065         }
1066     }
1067
1068     private Ini loadOrCreateDatabaseIni(Path path, String databaseDriverId)
1069             throws InvalidFileFormatException, IOException
1070     {
1071         File f = path.toFile();
1072         Ini dbIni = Files.isRegularFile(path) ? new Ini(f) : new Ini();
1073         String iniId = dbIni != null ? dbIni.get("driver", "id") : null;
1074         if (iniId == null) {
1075             dbIni.put("driver", "id", databaseDriverId);
1076             dbIni.store(f);
1077         }
1078         return dbIni;
1079     }
1080
1081 }