]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.workbench/src/org/simantics/workbench/internal/SimanticsWorkbenchApplication.java
Force platform shutdown after some delay when workbench is closed
[simantics/platform.git] / bundles / org.simantics.workbench / src / org / simantics / workbench / internal / SimanticsWorkbenchApplication.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.workbench.internal;
13
14 import java.io.File;
15 import java.io.FileInputStream;
16 import java.io.FileOutputStream;
17 import java.io.IOException;
18 import java.io.OutputStream;
19 import java.net.MalformedURLException;
20 import java.net.URL;
21 import java.util.Map;
22 import java.util.Properties;
23
24 import org.eclipse.core.runtime.IConfigurationElement;
25 import org.eclipse.core.runtime.IExecutableExtension;
26 import org.eclipse.core.runtime.IStatus;
27 import org.eclipse.core.runtime.Platform;
28 import org.eclipse.core.runtime.Status;
29 import org.eclipse.equinox.app.IApplication;
30 import org.eclipse.equinox.app.IApplicationContext;
31 import org.eclipse.jface.dialogs.Dialog;
32 import org.eclipse.jface.dialogs.MessageDialog;
33 import org.eclipse.osgi.service.datalocation.Location;
34 import org.eclipse.osgi.util.NLS;
35 import org.eclipse.swt.SWT;
36 import org.eclipse.swt.widgets.Display;
37 import org.eclipse.swt.widgets.MessageBox;
38 import org.eclipse.swt.widgets.Shell;
39 import org.eclipse.ui.IWorkbench;
40 import org.eclipse.ui.PlatformUI;
41 import org.eclipse.ui.application.WorkbenchAdvisor;
42 import org.eclipse.ui.internal.WorkbenchPlugin;
43 import org.eclipse.ui.internal.ide.ChooseWorkspaceData;
44 import org.eclipse.ui.internal.ide.ChooseWorkspaceDialog;
45 import org.eclipse.ui.internal.ide.IDEWorkbenchMessages;
46 import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
47 import org.eclipse.ui.internal.ide.StatusUtil;
48 import org.simantics.application.arguments.ApplicationUtils;
49 import org.simantics.application.arguments.Arguments;
50 import org.simantics.application.arguments.IArgumentFactory;
51 import org.simantics.application.arguments.IArguments;
52 import org.simantics.application.arguments.SimanticsArguments;
53 import org.simantics.db.management.ISessionContextProvider;
54 import org.simantics.db.management.ISessionContextProviderSource;
55 import org.simantics.db.management.SessionContextProvider;
56 import org.simantics.db.management.SingleSessionContextProviderSource;
57 import org.simantics.ui.SimanticsUI;
58 import org.simantics.utils.ui.BundleUtils;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62
63 /**
64  * The "main program" for the Eclipse IDE.
65  * 
66  * @since 3.0
67  */
68 public class SimanticsWorkbenchApplication implements IApplication, IExecutableExtension {
69
70     private static final Logger LOGGER = LoggerFactory.getLogger(SimanticsWorkbenchApplication.class);
71     /**
72      * The name of the folder containing metadata information for the workspace.
73      */
74     public static final String METADATA_FOLDER = ".metadata"; //$NON-NLS-1$
75
76     private static final String VERSION_FILENAME = "version.ini"; //$NON-NLS-1$
77
78     private static final String WORKSPACE_VERSION_KEY = "org.eclipse.core.runtime"; //$NON-NLS-1$
79
80     private static final String WORKSPACE_VERSION_VALUE = "1"; //$NON-NLS-1$
81
82     private static final String PROP_EXIT_CODE = "eclipse.exitcode"; //$NON-NLS-1$
83     
84     private static final String PROP_SHUTDOWN_GRACE_PERIOD = "simantics.shutdownGracePeriod"; //$NON-NLS-1$
85     private static final long DEFAULT_SHUTDOWN_GRACE_PERIOD = 5000L;
86
87     /**
88      * A special return code that will be recognized by the launcher and used to
89      * restart the workbench.
90      */
91     private static final Integer EXIT_RELAUNCH = new Integer(24);
92
93     /**
94      * A special return code that will be recognized by the PDE launcher and used to
95      * show an error dialog if the workspace is locked.
96      */
97     private static final Integer EXIT_WORKSPACE_LOCKED = new Integer(15);
98
99     /**
100      * Creates a new IDE application.
101      */
102     public SimanticsWorkbenchApplication() {
103         // There is nothing to do for WorkbenchApplication
104     }
105
106     public WorkbenchAdvisor createWorkbenchAdvisor(IArguments args, DelayedEventsProcessor processor) {
107         return new SimanticsWorkbenchAdvisor(args, processor);
108     }
109
110     /* (non-Javadoc)
111      * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext context)
112      */
113     @Override
114     public Object start(IApplicationContext appContext) throws Exception {
115         ApplicationUtils.loadSystemProperties(BundleUtils.find(Activator.PLUGIN_ID, "system.properties"));
116         IArguments args = parseArguments((String[]) appContext.getArguments().get(IApplicationContext.APPLICATION_ARGS));
117
118         Display display = createDisplay();
119         // processor must be created before we start event loop
120         DelayedEventsProcessor processor = new DelayedEventsProcessor(display);
121
122         try {
123             Object argCheck = verifyArguments(args);
124             if (argCheck != null)
125                 return argCheck;
126
127             // look and see if there's a splash shell we can parent off of
128             Shell shell = WorkbenchPlugin.getSplashShell(display);
129             if (shell != null) {
130                 // should should set the icon and message for this shell to be the 
131                 // same as the chooser dialog - this will be the guy that lives in
132                 // the task bar and without these calls you'd have the default icon 
133                 // with no message.
134                 shell.setText(ChooseWorkspaceDialog.getWindowTitle());
135                 shell.setImages(Dialog.getDefaultImages());
136             }
137
138             Object instanceLocationCheck = checkInstanceLocation(shell, appContext.getArguments(), args);
139             if (instanceLocationCheck != null) {
140                 WorkbenchPlugin.unsetSplashShell(display);
141                 Platform.endSplash();
142                 return instanceLocationCheck;
143             }
144
145             final ISessionContextProvider provider = new SessionContextProvider(null);
146             final ISessionContextProviderSource contextProviderSource = new SingleSessionContextProviderSource(provider);
147             //final ISessionContextProviderSource contextProviderSource = new WorkbenchWindowSessionContextProviderSource(PlatformUI.getWorkbench());
148             SimanticsUI.setSessionContextProviderSource(contextProviderSource);
149             org.simantics.db.layer0.internal.SimanticsInternal.setSessionContextProviderSource(contextProviderSource);
150             org.simantics.Simantics.setSessionContextProviderSource(contextProviderSource);
151             
152             // create the workbench with this advisor and run it until it exits
153             // N.B. createWorkbench remembers the advisor, and also registers
154             // the workbench globally so that all UI plug-ins can find it using
155             // PlatformUI.getWorkbench() or AbstractUIPlugin.getWorkbench()
156             int returnCode = PlatformUI.createAndRunWorkbench(display,
157                     createWorkbenchAdvisor(args, processor));
158             
159             Long shutdownGracePeriodPropValue = Long.getLong(PROP_SHUTDOWN_GRACE_PERIOD);
160             long shutdownGracePeriod = shutdownGracePeriodPropValue == null 
161                     ? DEFAULT_SHUTDOWN_GRACE_PERIOD
162                     : shutdownGracePeriodPropValue;
163
164             // the workbench doesn't support relaunch yet (bug 61809) so
165             // for now restart is used, and exit data properties are checked
166             // here to substitute in the relaunch return code if needed
167             if (returnCode != PlatformUI.RETURN_RESTART) {
168                 delayedShutdown(EXIT_OK, shutdownGracePeriod);
169                 return EXIT_OK;
170             }
171
172             // if the exit code property has been set to the relaunch code, then
173             // return that code now, otherwise this is a normal restart
174             int exitCode = EXIT_RELAUNCH.equals(Integer.getInteger(PROP_EXIT_CODE)) ? EXIT_RELAUNCH
175                     : EXIT_RESTART;
176             delayedShutdown(exitCode, shutdownGracePeriod);
177             return exitCode;
178         } finally {
179             if (display != null) {
180                 display.dispose();
181             }
182             Location instanceLoc = Platform.getInstanceLocation();
183             if (instanceLoc != null)
184                 instanceLoc.release();
185         }
186     }
187
188     private void delayedShutdown(int exitCode, long delayMs) {
189         LOGGER.info("Started delayed shutdown with delay {} ms.", delayMs);
190         Thread shutdownThread = new Thread() {
191             @Override
192             public void run() {
193                 try {
194                     Thread.sleep(delayMs);
195                     LOGGER.warn("Delayed shutdown forced the application to exit with code {}.", exitCode);
196                     System.exit(exitCode);
197                 } catch (InterruptedException e) {
198                     e.printStackTrace();
199                 }
200             }
201         };
202         shutdownThread.setDaemon(true);
203         shutdownThread.setName("delayed-shutdown");
204         shutdownThread.start();
205     }
206
207     /*************************************************************************/
208
209     private IArguments parseArguments(String[] args) {
210         IArgumentFactory<?>[] accepted = {
211                 SimanticsArguments.RECOVERY_POLICY_FIX_ERRORS,
212                 SimanticsArguments.ONTOLOGY_RECOVERY_POLICY_REINSTALL,
213                 SimanticsArguments.DEFAULT_WORKSPACE_LOCATION,
214                 SimanticsArguments.WORKSPACE_CHOOSER,
215                 SimanticsArguments.WORKSPACE_NO_REMEMBER,
216                 SimanticsArguments.PERSPECTIVE,
217                 SimanticsArguments.SERVER,
218                 SimanticsArguments.NEW_MODEL,
219                 SimanticsArguments.EXPERIMENT,
220                 SimanticsArguments.DISABLE_INDEX,
221                 SimanticsArguments.DATABASE_ID,
222         };
223         IArguments result = Arguments.parse(args, accepted);
224         return result;
225     }
226
227     private Object verifyArguments(IArguments args) {
228         StringBuilder report = new StringBuilder();
229
230 //        if (args.contains(SimanticsArguments.NEW_PROJECT)) {
231 //            if (args.contains(SimanticsArguments.PROJECT)) {
232 //                exclusiveArguments(report, SimanticsArguments.PROJECT, SimanticsArguments.NEW_PROJECT);
233 //            }
234 //            // Must have a server to checkout from when creating a new
235 //            // project right from the beginning.
236 //            if (!args.contains(SimanticsArguments.SERVER)) {
237 //                missingArgument(report, SimanticsArguments.SERVER);
238 //            }
239 //        } else if (args.contains(SimanticsArguments.PROJECT)) {
240 //            // To load a project, a server must be defined to checkout from
241 //            if (!args.contains(SimanticsArguments.SERVER)) {
242 //                missingArgument(report, SimanticsArguments.SERVER);
243 //            }
244 //        }
245
246         // NEW_MODEL and MODEL arguments are optional
247         // EXPERIMENT argument is optional
248
249         String result = report.toString();
250         boolean valid = result.length() == 0;
251
252         if (!valid) {
253             String msg = NLS.bind(Messages.Application_1, result);
254             MessageDialog.openInformation(null, Messages.Application_2, msg);
255         }
256         return valid ? null : EXIT_OK;
257     }
258
259 //    private void exclusiveArguments(StringBuilder sb, IArgumentFactory<?> arg1, IArgumentFactory<?> arg2) {
260 //        sb.append(NLS.bind(Messages.Application_3, arg1.getArgument(), arg2.getArgument()));
261 //        sb.append('\n');
262 //    }
263 //
264 //    private void missingArgument(StringBuilder sb, IArgumentFactory<?> arg) {
265 //        sb.append(NLS.bind(Messages.Application_0, arg.getArgument()));
266 //        sb.append('\n');
267 //    }
268
269     /*************************************************************************/
270
271     /**
272      * Creates the display used by the application.
273      * 
274      * @return the display used by the application
275      */
276     protected Display createDisplay() {
277         return PlatformUI.createDisplay();
278     }
279
280     /* (non-Javadoc)
281      * @see org.eclipse.core.runtime.IExecutableExtension#setInitializationData(org.eclipse.core.runtime.IConfigurationElement, java.lang.String, java.lang.Object)
282      */
283     @Override
284     public void setInitializationData(IConfigurationElement config,
285             String propertyName, Object data) {
286         // There is nothing to do for ProConfApplication
287     }
288
289     /**
290      * Return true if a valid workspace path has been set and false otherwise.
291      * Prompt for and set the path if possible and required.
292      * @param applicationArguments 
293      * 
294      * @return true if a valid instance location has been set and false
295      *         otherwise
296      */
297     private Object checkInstanceLocation(Shell shell, Map<?,?> applicationArguments, IArguments args) {
298         // -data @none was specified but an ide requires workspace
299         Location instanceLoc = Platform.getInstanceLocation();
300         if (instanceLoc == null) {
301             MessageDialog
302             .openError(
303                     shell,
304                     IDEWorkbenchMessages.IDEApplication_workspaceMandatoryTitle,
305                     IDEWorkbenchMessages.IDEApplication_workspaceMandatoryMessage);
306             return EXIT_OK;
307         }
308
309         // -data "/valid/path", workspace already set
310         // This information is stored in configuration/.settings/org.eclipse.ui.ide.prefs
311         if (instanceLoc.isSet()) {
312             // make sure the meta data version is compatible (or the user has
313             // chosen to overwrite it).
314             if (!checkValidWorkspace(shell, instanceLoc.getURL())) {
315                 return EXIT_OK;
316             }
317
318             // at this point its valid, so try to lock it and update the
319             // metadata version information if successful
320             try {
321                 if (instanceLoc.lock()) {
322                     writeWorkspaceVersion();
323                     return null;
324                 }
325
326                 // we failed to create the directory.
327                 // Two possibilities:
328                 // 1. directory is already in use
329                 // 2. directory could not be created
330                 File workspaceDirectory = new File(instanceLoc.getURL().getFile());
331                 if (workspaceDirectory.exists()) {
332                     if (isDevLaunchMode(applicationArguments)) {
333                         return EXIT_WORKSPACE_LOCKED;
334                     }
335                     MessageDialog.openError(
336                             shell,
337                             IDEWorkbenchMessages.IDEApplication_workspaceCannotLockTitle,
338                             IDEWorkbenchMessages.IDEApplication_workspaceCannotLockMessage);
339                 } else {
340                     MessageDialog.openError(
341                             shell,
342                             IDEWorkbenchMessages.IDEApplication_workspaceCannotBeSetTitle,
343                             IDEWorkbenchMessages.IDEApplication_workspaceCannotBeSetMessage);
344                 }
345             } catch (IOException e) {
346                 IDEWorkbenchPlugin.log("Could not obtain lock for workspace location", //$NON-NLS-1$
347                         e);
348                 MessageDialog
349                 .openError(
350                         shell,
351                         IDEWorkbenchMessages.InternalError,
352                         e.getMessage());
353             }
354             return EXIT_OK;
355         }
356
357         // -data @noDefault or -data not specified, prompt and set
358         ChooseWorkspaceData launchData = null;
359         if (args.contains(SimanticsArguments.DEFAULT_WORKSPACE_LOCATION)) {
360             launchData = new ChooseWorkspaceData(args.get(SimanticsArguments.DEFAULT_WORKSPACE_LOCATION));
361         } else {
362             launchData = new ChooseWorkspaceData(instanceLoc.getDefault());
363         }
364
365         boolean force = args.contains(SimanticsArguments.WORKSPACE_CHOOSER);
366         boolean suppressAskAgain = args.contains(SimanticsArguments.WORKSPACE_NO_REMEMBER);
367
368         while (true) {
369             URL workspaceUrl = promptForWorkspace(shell, launchData, force, suppressAskAgain);
370             if (workspaceUrl == null) {
371                 return EXIT_OK;
372             }
373
374             // if there is an error with the first selection, then force the
375             // dialog to open to give the user a chance to correct
376             force = true;
377
378             try {
379                 // the operation will fail if the url is not a valid
380                 // instance data area, so other checking is unneeded
381                 if (instanceLoc.setURL(workspaceUrl, true)) {
382                     launchData.writePersistedData();
383                     writeWorkspaceVersion();
384                     return null;
385                 }
386             } catch (IllegalStateException e) {
387                 MessageDialog
388                 .openError(
389                         shell,
390                         IDEWorkbenchMessages.IDEApplication_workspaceCannotBeSetTitle,
391                         IDEWorkbenchMessages.IDEApplication_workspaceCannotBeSetMessage);
392                 return EXIT_OK;
393             }
394
395             // by this point it has been determined that the workspace is
396             // already in use -- force the user to choose again
397             MessageDialog.openError(shell, IDEWorkbenchMessages.IDEApplication_workspaceInUseTitle,
398                     IDEWorkbenchMessages.IDEApplication_workspaceInUseMessage);
399         }
400     }
401
402     private static boolean isDevLaunchMode(Map<?,?> args) {
403         // see org.eclipse.pde.internal.core.PluginPathFinder.isDevLaunchMode()
404         if (Boolean.getBoolean("eclipse.pde.launch")) //$NON-NLS-1$
405             return true;
406         return args.containsKey("-pdelaunch"); //$NON-NLS-1$
407     }
408
409     private static class ChooseSimanticsWorkspaceDialog extends ChooseWorkspaceDialog {
410
411         public ChooseSimanticsWorkspaceDialog(Shell parentShell, ChooseWorkspaceData launchData, boolean suppressAskAgain, boolean centerOnMonitor) {
412             super(parentShell, launchData, suppressAskAgain, centerOnMonitor);
413         }
414         
415         @Override
416         protected void configureShell(Shell shell) {
417             super.configureShell(shell);
418             // Use product name in shell title instead of generic "Eclipse Launcher"
419             shell.setText(getWindowTitle());
420         }
421     }
422
423     /**
424      * Open a workspace selection dialog on the argument shell, populating the
425      * argument data with the user's selection. Perform first level validation
426      * on the selection by comparing the version information. This method does
427      * not examine the runtime state (e.g., is the workspace already locked?).
428      * 
429      * @param shell
430      * @param launchData
431      * @param force
432      *            setting to true makes the dialog open regardless of the
433      *            showDialog value
434      * @return An URL storing the selected workspace or null if the user has
435      *         canceled the launch operation.
436      */
437     private URL promptForWorkspace(Shell shell, ChooseWorkspaceData launchData,
438             boolean force, boolean suppressAskAgain) {
439         URL url = null;
440         do {
441             // okay to use the shell now - this is the splash shell
442             new ChooseSimanticsWorkspaceDialog(shell, launchData, suppressAskAgain, true).prompt(force); 
443             
444             String instancePath = launchData.getSelection();
445             if (instancePath == null) {
446                 return null;
447             }
448
449             // the dialog is not forced on the first iteration, but is on every
450             // subsequent one -- if there was an error then the user needs to be
451             // allowed to fix it
452             force = true;
453
454             // 70576: don't accept empty input
455             if (instancePath.length() <= 0) {
456                 MessageDialog
457                 .openError(
458                         shell,
459                         IDEWorkbenchMessages.IDEApplication_workspaceEmptyTitle,
460                         IDEWorkbenchMessages.IDEApplication_workspaceEmptyMessage);
461                 continue;
462             }
463
464             // create the workspace if it does not already exist
465             File workspace = new File(instancePath);
466             if (!workspace.exists()) {
467                 workspace.mkdir();
468             }
469
470             try {
471                 // Don't use File.toURL() since it adds a leading slash that Platform does not
472                 // handle properly.  See bug 54081 for more details.
473                 String path = workspace.getAbsolutePath().replace(
474                         File.separatorChar, '/');
475                 url = new URL("file", null, path); //$NON-NLS-1$
476             } catch (MalformedURLException e) {
477                 MessageDialog
478                 .openError(
479                         shell,
480                         IDEWorkbenchMessages.IDEApplication_workspaceInvalidTitle,
481                         IDEWorkbenchMessages.IDEApplication_workspaceInvalidMessage);
482                 continue;
483             }
484         } while (!checkValidWorkspace(shell, url));
485
486         return url;
487     }
488
489     /**
490      * Return true if the argument directory is ok to use as a workspace and
491      * false otherwise. A version check will be performed, and a confirmation
492      * box may be displayed on the argument shell if an older version is
493      * detected.
494      * 
495      * @return true if the argument URL is ok to use as a workspace and false
496      *         otherwise.
497      */
498     private boolean checkValidWorkspace(Shell shell, URL url) {
499         // a null url is not a valid workspace
500         if (url == null) {
501             return false;
502         }
503
504         String version = readWorkspaceVersion(url);
505
506         // if the version could not be read, then there is not any existing
507         // workspace data to trample, e.g., perhaps its a new directory that
508         // is just starting to be used as a workspace
509         if (version == null) {
510             return true;
511         }
512
513         final int ide_version = Integer.parseInt(WORKSPACE_VERSION_VALUE);
514         int workspace_version = Integer.parseInt(version);
515
516         // equality test is required since any version difference (newer
517         // or older) may result in data being trampled
518         if (workspace_version == ide_version) {
519             return true;
520         }
521
522         // At this point workspace has been detected to be from a version
523         // other than the current ide version -- find out if the user wants
524         // to use it anyhow.
525                 int severity;
526                 String title;
527                 String message;
528                 if (workspace_version < ide_version) {
529                         // Workspace < IDE. Update must be possible without issues,
530                         // so only inform user about it.
531                         severity = MessageDialog.INFORMATION;
532                         title = IDEWorkbenchMessages.IDEApplication_versionTitle_olderWorkspace;
533                         message = NLS.bind(IDEWorkbenchMessages.IDEApplication_versionMessage_olderWorkspace, url.getFile());
534                 } else {
535                         // Workspace > IDE. It must have been opened with a newer IDE version.
536                         // Downgrade might be problematic, so warn user about it.
537                         severity = MessageDialog.WARNING;
538                         title = IDEWorkbenchMessages.IDEApplication_versionTitle_newerWorkspace;
539                         message = NLS.bind(IDEWorkbenchMessages.IDEApplication_versionMessage_newerWorkspace, url.getFile());
540                 }
541
542         MessageBox mbox = new MessageBox(shell, SWT.OK | SWT.CANCEL
543                 | SWT.ICON_WARNING | SWT.APPLICATION_MODAL);
544         mbox.setText(title);
545         mbox.setMessage(message);
546         return mbox.open() == SWT.OK;
547     }
548
549     /**
550      * Look at the argument URL for the workspace's version information. Return
551      * that version if found and null otherwise.
552      */
553     private static String readWorkspaceVersion(URL workspace) {
554         File versionFile = getVersionFile(workspace, false);
555         if (versionFile == null || !versionFile.exists()) {
556             return null;
557         }
558
559         try {
560             // Although the version file is not spec'ed to be a Java properties
561             // file, it happens to follow the same format currently, so using
562             // Properties to read it is convenient.
563             Properties props = new Properties();
564             FileInputStream is = new FileInputStream(versionFile);
565             try {
566                 props.load(is);
567             } finally {
568                 is.close();
569             }
570
571             return props.getProperty(WORKSPACE_VERSION_KEY);
572         } catch (IOException e) {
573             IDEWorkbenchPlugin.log("Could not read version file", new Status( //$NON-NLS-1$
574                     IStatus.ERROR, IDEWorkbenchPlugin.IDE_WORKBENCH,
575                     IStatus.ERROR,
576                     e.getMessage() == null ? "" : e.getMessage(), //$NON-NLS-1$,
577                             e));
578             return null;
579         }
580     }
581
582     /**
583      * Write the version of the metadata into a known file overwriting any
584      * existing file contents. Writing the version file isn't really crucial,
585      * so the function is silent about failure
586      */
587     private static void writeWorkspaceVersion() {
588         Location instanceLoc = Platform.getInstanceLocation();
589         if (instanceLoc == null || instanceLoc.isReadOnly()) {
590             return;
591         }
592
593         File versionFile = getVersionFile(instanceLoc.getURL(), true);
594         if (versionFile == null) {
595             return;
596         }
597
598         OutputStream output = null;
599         try {
600             String versionLine = WORKSPACE_VERSION_KEY + '='
601             + WORKSPACE_VERSION_VALUE;
602
603             output = new FileOutputStream(versionFile);
604             output.write(versionLine.getBytes("UTF-8")); //$NON-NLS-1$
605         } catch (IOException e) {
606             IDEWorkbenchPlugin.log("Could not write version file", //$NON-NLS-1$
607                     StatusUtil.newStatus(IStatus.ERROR, e.getMessage(), e));
608         } finally {
609             try {
610                 if (output != null) {
611                     output.close();
612                 }
613             } catch (IOException e) {
614                 // do nothing
615             }
616         }
617     }
618
619     /**
620      * The version file is stored in the metadata area of the workspace. This
621      * method returns an URL to the file or null if the directory or file does
622      * not exist (and the create parameter is false).
623      * 
624      * @param create
625      *            If the directory and file does not exist this parameter
626      *            controls whether it will be created.
627      * @return An url to the file or null if the version file does not exist or
628      *         could not be created.
629      */
630     private static File getVersionFile(URL workspaceUrl, boolean create) {
631         if (workspaceUrl == null) {
632             return null;
633         }
634
635         try {
636             // make sure the directory exists
637             File metaDir = new File(workspaceUrl.getPath(), METADATA_FOLDER);
638             if (!metaDir.exists() && (!create || !metaDir.mkdir())) {
639                 return null;
640             }
641
642             // make sure the file exists
643             File versionFile = new File(metaDir, VERSION_FILENAME);
644             if (!versionFile.exists()
645                     && (!create || !versionFile.createNewFile())) {
646                 return null;
647             }
648
649             return versionFile;
650         } catch (IOException e) {
651             // cannot log because instance area has not been set
652             return null;
653         }
654     }
655
656     /* (non-Javadoc)
657      * @see org.eclipse.equinox.app.IApplication#stop()
658      */
659     @Override
660     public void stop() {
661         final IWorkbench workbench = PlatformUI.getWorkbench();
662         if (workbench == null)
663             return;
664         final Display display = workbench.getDisplay();
665         display.syncExec(new Runnable() {
666             @Override
667             public void run() {
668                 if (!display.isDisposed())
669                     workbench.close();
670             }
671         });
672     }
673
674 }