]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.workbench/src/org/simantics/workbench/internal/SimanticsWorkbenchApplication.java
50e8aada7b3f4cd3c14acdeee796427123db7dab
[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                     // Method halt is used instead of System.exit, because running
197                     // of shutdown hooks hangs the application in some cases.
198                     Runtime.getRuntime().halt(exitCode);
199                 } catch (InterruptedException e) {
200                     e.printStackTrace();
201                 }
202             }
203         };
204         shutdownThread.setDaemon(true);
205         shutdownThread.setName("delayed-shutdown");
206         shutdownThread.start();
207     }
208
209     /*************************************************************************/
210
211     private IArguments parseArguments(String[] args) {
212         IArgumentFactory<?>[] accepted = {
213                 SimanticsArguments.RECOVERY_POLICY_FIX_ERRORS,
214                 SimanticsArguments.ONTOLOGY_RECOVERY_POLICY_REINSTALL,
215                 SimanticsArguments.DEFAULT_WORKSPACE_LOCATION,
216                 SimanticsArguments.WORKSPACE_CHOOSER,
217                 SimanticsArguments.WORKSPACE_NO_REMEMBER,
218                 SimanticsArguments.PERSPECTIVE,
219                 SimanticsArguments.SERVER,
220                 SimanticsArguments.NEW_MODEL,
221                 SimanticsArguments.EXPERIMENT,
222                 SimanticsArguments.DISABLE_INDEX,
223                 SimanticsArguments.DATABASE_ID,
224         };
225         IArguments result = Arguments.parse(args, accepted);
226         return result;
227     }
228
229     private Object verifyArguments(IArguments args) {
230         StringBuilder report = new StringBuilder();
231
232 //        if (args.contains(SimanticsArguments.NEW_PROJECT)) {
233 //            if (args.contains(SimanticsArguments.PROJECT)) {
234 //                exclusiveArguments(report, SimanticsArguments.PROJECT, SimanticsArguments.NEW_PROJECT);
235 //            }
236 //            // Must have a server to checkout from when creating a new
237 //            // project right from the beginning.
238 //            if (!args.contains(SimanticsArguments.SERVER)) {
239 //                missingArgument(report, SimanticsArguments.SERVER);
240 //            }
241 //        } else if (args.contains(SimanticsArguments.PROJECT)) {
242 //            // To load a project, a server must be defined to checkout from
243 //            if (!args.contains(SimanticsArguments.SERVER)) {
244 //                missingArgument(report, SimanticsArguments.SERVER);
245 //            }
246 //        }
247
248         // NEW_MODEL and MODEL arguments are optional
249         // EXPERIMENT argument is optional
250
251         String result = report.toString();
252         boolean valid = result.length() == 0;
253
254         if (!valid) {
255             String msg = NLS.bind(Messages.Application_1, result);
256             MessageDialog.openInformation(null, Messages.Application_2, msg);
257         }
258         return valid ? null : EXIT_OK;
259     }
260
261 //    private void exclusiveArguments(StringBuilder sb, IArgumentFactory<?> arg1, IArgumentFactory<?> arg2) {
262 //        sb.append(NLS.bind(Messages.Application_3, arg1.getArgument(), arg2.getArgument()));
263 //        sb.append('\n');
264 //    }
265 //
266 //    private void missingArgument(StringBuilder sb, IArgumentFactory<?> arg) {
267 //        sb.append(NLS.bind(Messages.Application_0, arg.getArgument()));
268 //        sb.append('\n');
269 //    }
270
271     /*************************************************************************/
272
273     /**
274      * Creates the display used by the application.
275      * 
276      * @return the display used by the application
277      */
278     protected Display createDisplay() {
279         return PlatformUI.createDisplay();
280     }
281
282     /* (non-Javadoc)
283      * @see org.eclipse.core.runtime.IExecutableExtension#setInitializationData(org.eclipse.core.runtime.IConfigurationElement, java.lang.String, java.lang.Object)
284      */
285     @Override
286     public void setInitializationData(IConfigurationElement config,
287             String propertyName, Object data) {
288         // There is nothing to do for ProConfApplication
289     }
290
291     /**
292      * Return true if a valid workspace path has been set and false otherwise.
293      * Prompt for and set the path if possible and required.
294      * @param applicationArguments 
295      * 
296      * @return true if a valid instance location has been set and false
297      *         otherwise
298      */
299     private Object checkInstanceLocation(Shell shell, Map<?,?> applicationArguments, IArguments args) {
300         // -data @none was specified but an ide requires workspace
301         Location instanceLoc = Platform.getInstanceLocation();
302         if (instanceLoc == null) {
303             MessageDialog
304             .openError(
305                     shell,
306                     IDEWorkbenchMessages.IDEApplication_workspaceMandatoryTitle,
307                     IDEWorkbenchMessages.IDEApplication_workspaceMandatoryMessage);
308             return EXIT_OK;
309         }
310
311         // -data "/valid/path", workspace already set
312         // This information is stored in configuration/.settings/org.eclipse.ui.ide.prefs
313         if (instanceLoc.isSet()) {
314             // make sure the meta data version is compatible (or the user has
315             // chosen to overwrite it).
316             if (!checkValidWorkspace(shell, instanceLoc.getURL())) {
317                 return EXIT_OK;
318             }
319
320             // at this point its valid, so try to lock it and update the
321             // metadata version information if successful
322             try {
323                 if (instanceLoc.lock()) {
324                     writeWorkspaceVersion();
325                     return null;
326                 }
327
328                 // we failed to create the directory.
329                 // Two possibilities:
330                 // 1. directory is already in use
331                 // 2. directory could not be created
332                 File workspaceDirectory = new File(instanceLoc.getURL().getFile());
333                 if (workspaceDirectory.exists()) {
334                     if (isDevLaunchMode(applicationArguments)) {
335                         return EXIT_WORKSPACE_LOCKED;
336                     }
337                     MessageDialog.openError(
338                             shell,
339                             IDEWorkbenchMessages.IDEApplication_workspaceCannotLockTitle,
340                             IDEWorkbenchMessages.IDEApplication_workspaceCannotLockMessage);
341                 } else {
342                     MessageDialog.openError(
343                             shell,
344                             IDEWorkbenchMessages.IDEApplication_workspaceCannotBeSetTitle,
345                             IDEWorkbenchMessages.IDEApplication_workspaceCannotBeSetMessage);
346                 }
347             } catch (IOException e) {
348                 IDEWorkbenchPlugin.log("Could not obtain lock for workspace location", //$NON-NLS-1$
349                         e);
350                 MessageDialog
351                 .openError(
352                         shell,
353                         IDEWorkbenchMessages.InternalError,
354                         e.getMessage());
355             }
356             return EXIT_OK;
357         }
358
359         // -data @noDefault or -data not specified, prompt and set
360         ChooseWorkspaceData launchData = null;
361         if (args.contains(SimanticsArguments.DEFAULT_WORKSPACE_LOCATION)) {
362             launchData = new ChooseWorkspaceData(args.get(SimanticsArguments.DEFAULT_WORKSPACE_LOCATION));
363         } else {
364             launchData = new ChooseWorkspaceData(instanceLoc.getDefault());
365         }
366
367         boolean force = args.contains(SimanticsArguments.WORKSPACE_CHOOSER);
368         boolean suppressAskAgain = args.contains(SimanticsArguments.WORKSPACE_NO_REMEMBER);
369
370         while (true) {
371             URL workspaceUrl = promptForWorkspace(shell, launchData, force, suppressAskAgain);
372             if (workspaceUrl == null) {
373                 return EXIT_OK;
374             }
375
376             // if there is an error with the first selection, then force the
377             // dialog to open to give the user a chance to correct
378             force = true;
379
380             try {
381                 // the operation will fail if the url is not a valid
382                 // instance data area, so other checking is unneeded
383                 if (instanceLoc.setURL(workspaceUrl, true)) {
384                     launchData.writePersistedData();
385                     writeWorkspaceVersion();
386                     return null;
387                 }
388             } catch (IllegalStateException e) {
389                 MessageDialog
390                 .openError(
391                         shell,
392                         IDEWorkbenchMessages.IDEApplication_workspaceCannotBeSetTitle,
393                         IDEWorkbenchMessages.IDEApplication_workspaceCannotBeSetMessage);
394                 return EXIT_OK;
395             }
396
397             // by this point it has been determined that the workspace is
398             // already in use -- force the user to choose again
399             MessageDialog.openError(shell, IDEWorkbenchMessages.IDEApplication_workspaceInUseTitle,
400                     IDEWorkbenchMessages.IDEApplication_workspaceInUseMessage);
401         }
402     }
403
404     private static boolean isDevLaunchMode(Map<?,?> args) {
405         // see org.eclipse.pde.internal.core.PluginPathFinder.isDevLaunchMode()
406         if (Boolean.getBoolean("eclipse.pde.launch")) //$NON-NLS-1$
407             return true;
408         return args.containsKey("-pdelaunch"); //$NON-NLS-1$
409     }
410
411     private static class ChooseSimanticsWorkspaceDialog extends ChooseWorkspaceDialog {
412
413         public ChooseSimanticsWorkspaceDialog(Shell parentShell, ChooseWorkspaceData launchData, boolean suppressAskAgain, boolean centerOnMonitor) {
414             super(parentShell, launchData, suppressAskAgain, centerOnMonitor);
415         }
416         
417         @Override
418         protected void configureShell(Shell shell) {
419             super.configureShell(shell);
420             // Use product name in shell title instead of generic "Eclipse Launcher"
421             shell.setText(getWindowTitle());
422         }
423     }
424
425     /**
426      * Open a workspace selection dialog on the argument shell, populating the
427      * argument data with the user's selection. Perform first level validation
428      * on the selection by comparing the version information. This method does
429      * not examine the runtime state (e.g., is the workspace already locked?).
430      * 
431      * @param shell
432      * @param launchData
433      * @param force
434      *            setting to true makes the dialog open regardless of the
435      *            showDialog value
436      * @return An URL storing the selected workspace or null if the user has
437      *         canceled the launch operation.
438      */
439     private URL promptForWorkspace(Shell shell, ChooseWorkspaceData launchData,
440             boolean force, boolean suppressAskAgain) {
441         URL url = null;
442         do {
443             // okay to use the shell now - this is the splash shell
444             new ChooseSimanticsWorkspaceDialog(shell, launchData, suppressAskAgain, true).prompt(force); 
445             
446             String instancePath = launchData.getSelection();
447             if (instancePath == null) {
448                 return null;
449             }
450
451             // the dialog is not forced on the first iteration, but is on every
452             // subsequent one -- if there was an error then the user needs to be
453             // allowed to fix it
454             force = true;
455
456             // 70576: don't accept empty input
457             if (instancePath.length() <= 0) {
458                 MessageDialog
459                 .openError(
460                         shell,
461                         IDEWorkbenchMessages.IDEApplication_workspaceEmptyTitle,
462                         IDEWorkbenchMessages.IDEApplication_workspaceEmptyMessage);
463                 continue;
464             }
465
466             // create the workspace if it does not already exist
467             File workspace = new File(instancePath);
468             if (!workspace.exists()) {
469                 workspace.mkdir();
470             }
471
472             try {
473                 // Don't use File.toURL() since it adds a leading slash that Platform does not
474                 // handle properly.  See bug 54081 for more details.
475                 String path = workspace.getAbsolutePath().replace(
476                         File.separatorChar, '/');
477                 url = new URL("file", null, path); //$NON-NLS-1$
478             } catch (MalformedURLException e) {
479                 MessageDialog
480                 .openError(
481                         shell,
482                         IDEWorkbenchMessages.IDEApplication_workspaceInvalidTitle,
483                         IDEWorkbenchMessages.IDEApplication_workspaceInvalidMessage);
484                 continue;
485             }
486         } while (!checkValidWorkspace(shell, url));
487
488         return url;
489     }
490
491     /**
492      * Return true if the argument directory is ok to use as a workspace and
493      * false otherwise. A version check will be performed, and a confirmation
494      * box may be displayed on the argument shell if an older version is
495      * detected.
496      * 
497      * @return true if the argument URL is ok to use as a workspace and false
498      *         otherwise.
499      */
500     private boolean checkValidWorkspace(Shell shell, URL url) {
501         // a null url is not a valid workspace
502         if (url == null) {
503             return false;
504         }
505
506         String version = readWorkspaceVersion(url);
507
508         // if the version could not be read, then there is not any existing
509         // workspace data to trample, e.g., perhaps its a new directory that
510         // is just starting to be used as a workspace
511         if (version == null) {
512             return true;
513         }
514
515         final int ide_version = Integer.parseInt(WORKSPACE_VERSION_VALUE);
516         int workspace_version = Integer.parseInt(version);
517
518         // equality test is required since any version difference (newer
519         // or older) may result in data being trampled
520         if (workspace_version == ide_version) {
521             return true;
522         }
523
524         // At this point workspace has been detected to be from a version
525         // other than the current ide version -- find out if the user wants
526         // to use it anyhow.
527                 int severity;
528                 String title;
529                 String message;
530                 if (workspace_version < ide_version) {
531                         // Workspace < IDE. Update must be possible without issues,
532                         // so only inform user about it.
533                         severity = MessageDialog.INFORMATION;
534                         title = IDEWorkbenchMessages.IDEApplication_versionTitle_olderWorkspace;
535                         message = NLS.bind(IDEWorkbenchMessages.IDEApplication_versionMessage_olderWorkspace, url.getFile());
536                 } else {
537                         // Workspace > IDE. It must have been opened with a newer IDE version.
538                         // Downgrade might be problematic, so warn user about it.
539                         severity = MessageDialog.WARNING;
540                         title = IDEWorkbenchMessages.IDEApplication_versionTitle_newerWorkspace;
541                         message = NLS.bind(IDEWorkbenchMessages.IDEApplication_versionMessage_newerWorkspace, url.getFile());
542                 }
543
544         MessageBox mbox = new MessageBox(shell, SWT.OK | SWT.CANCEL
545                 | SWT.ICON_WARNING | SWT.APPLICATION_MODAL);
546         mbox.setText(title);
547         mbox.setMessage(message);
548         return mbox.open() == SWT.OK;
549     }
550
551     /**
552      * Look at the argument URL for the workspace's version information. Return
553      * that version if found and null otherwise.
554      */
555     private static String readWorkspaceVersion(URL workspace) {
556         File versionFile = getVersionFile(workspace, false);
557         if (versionFile == null || !versionFile.exists()) {
558             return null;
559         }
560
561         try {
562             // Although the version file is not spec'ed to be a Java properties
563             // file, it happens to follow the same format currently, so using
564             // Properties to read it is convenient.
565             Properties props = new Properties();
566             FileInputStream is = new FileInputStream(versionFile);
567             try {
568                 props.load(is);
569             } finally {
570                 is.close();
571             }
572
573             return props.getProperty(WORKSPACE_VERSION_KEY);
574         } catch (IOException e) {
575             IDEWorkbenchPlugin.log("Could not read version file", new Status( //$NON-NLS-1$
576                     IStatus.ERROR, IDEWorkbenchPlugin.IDE_WORKBENCH,
577                     IStatus.ERROR,
578                     e.getMessage() == null ? "" : e.getMessage(), //$NON-NLS-1$,
579                             e));
580             return null;
581         }
582     }
583
584     /**
585      * Write the version of the metadata into a known file overwriting any
586      * existing file contents. Writing the version file isn't really crucial,
587      * so the function is silent about failure
588      */
589     private static void writeWorkspaceVersion() {
590         Location instanceLoc = Platform.getInstanceLocation();
591         if (instanceLoc == null || instanceLoc.isReadOnly()) {
592             return;
593         }
594
595         File versionFile = getVersionFile(instanceLoc.getURL(), true);
596         if (versionFile == null) {
597             return;
598         }
599
600         OutputStream output = null;
601         try {
602             String versionLine = WORKSPACE_VERSION_KEY + '='
603             + WORKSPACE_VERSION_VALUE;
604
605             output = new FileOutputStream(versionFile);
606             output.write(versionLine.getBytes("UTF-8")); //$NON-NLS-1$
607         } catch (IOException e) {
608             IDEWorkbenchPlugin.log("Could not write version file", //$NON-NLS-1$
609                     StatusUtil.newStatus(IStatus.ERROR, e.getMessage(), e));
610         } finally {
611             try {
612                 if (output != null) {
613                     output.close();
614                 }
615             } catch (IOException e) {
616                 // do nothing
617             }
618         }
619     }
620
621     /**
622      * The version file is stored in the metadata area of the workspace. This
623      * method returns an URL to the file or null if the directory or file does
624      * not exist (and the create parameter is false).
625      * 
626      * @param create
627      *            If the directory and file does not exist this parameter
628      *            controls whether it will be created.
629      * @return An url to the file or null if the version file does not exist or
630      *         could not be created.
631      */
632     private static File getVersionFile(URL workspaceUrl, boolean create) {
633         if (workspaceUrl == null) {
634             return null;
635         }
636
637         try {
638             // make sure the directory exists
639             File metaDir = new File(workspaceUrl.getPath(), METADATA_FOLDER);
640             if (!metaDir.exists() && (!create || !metaDir.mkdir())) {
641                 return null;
642             }
643
644             // make sure the file exists
645             File versionFile = new File(metaDir, VERSION_FILENAME);
646             if (!versionFile.exists()
647                     && (!create || !versionFile.createNewFile())) {
648                 return null;
649             }
650
651             return versionFile;
652         } catch (IOException e) {
653             // cannot log because instance area has not been set
654             return null;
655         }
656     }
657
658     /* (non-Javadoc)
659      * @see org.eclipse.equinox.app.IApplication#stop()
660      */
661     @Override
662     public void stop() {
663         final IWorkbench workbench = PlatformUI.getWorkbench();
664         if (workbench == null)
665             return;
666         final Display display = workbench.getDisplay();
667         display.syncExec(new Runnable() {
668             @Override
669             public void run() {
670                 if (!display.isDisposed())
671                     workbench.close();
672             }
673         });
674     }
675
676 }