]> gerrit.simantics Code Review - simantics/platform.git/blobdiff - bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/sharedontology/wizard/SharedOntologyImportWizard.java
Improved error handling in shared library import wizard
[simantics/platform.git] / bundles / org.simantics.modeling.ui / src / org / simantics / modeling / ui / sharedontology / wizard / SharedOntologyImportWizard.java
index a0ca44f64c2a73e9a910eef46f28eaa8e1f7692f..95beaad384a7eb6f8a543d6aaf48030c54e6bf7c 100644 (file)
-/*******************************************************************************\r
- * Copyright (c) 2012 Association for Decentralized Information Management in\r
- * Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- *     VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.modeling.ui.sharedontology.wizard;\r
-\r
-import java.io.File;\r
-import java.io.IOException;\r
-import java.lang.reflect.InvocationTargetException;\r
-import java.util.Deque;\r
-import java.util.HashMap;\r
-\r
-import org.eclipse.core.runtime.IProgressMonitor;\r
-import org.eclipse.core.runtime.preferences.InstanceScope;\r
-import org.eclipse.jface.operation.IRunnableWithProgress;\r
-import org.eclipse.jface.preference.IPersistentPreferenceStore;\r
-import org.eclipse.jface.preference.IPreferenceStore;\r
-import org.eclipse.jface.viewers.IStructuredSelection;\r
-import org.eclipse.jface.wizard.Wizard;\r
-import org.eclipse.jface.wizard.WizardPage;\r
-import org.eclipse.ui.IImportWizard;\r
-import org.eclipse.ui.IWorkbench;\r
-import org.eclipse.ui.preferences.ScopedPreferenceStore;\r
-import org.simantics.Simantics;\r
-import org.simantics.databoard.binding.Binding;\r
-import org.simantics.databoard.binding.mutable.Variant;\r
-import org.simantics.databoard.container.DataContainer;\r
-import org.simantics.databoard.container.DataContainers;\r
-import org.simantics.databoard.container.DataFormatException;\r
-import org.simantics.databoard.container.FormatHandler;\r
-import org.simantics.databoard.serialization.SerializationException;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.migration.MigrationUtils;\r
-import org.simantics.db.layer0.util.DraftStatusBean;\r
-import org.simantics.db.management.ISessionContext;\r
-import org.simantics.graph.db.MissingDependencyException;\r
-import org.simantics.graph.representation.TransferableGraph1;\r
-import org.simantics.modeling.ui.Activator;\r
-import org.simantics.modeling.ui.utils.NoProjectPage;\r
-import org.simantics.project.IProject;\r
-import org.simantics.project.ProjectKeys;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.utils.ResourceAdaptionUtils;\r
-import org.simantics.utils.ui.ErrorLogger;\r
-import org.simantics.utils.ui.ExceptionUtils;\r
-\r
-/**\r
- * @author Tuukka Lehtonen\r
- */\r
-public class SharedOntologyImportWizard extends Wizard implements IImportWizard {\r
-\r
-    private static final int MAX_RECENT_IMPORT_PATHS = 10;\r
-\r
-    ImportPlan        importModel;\r
-\r
-    private boolean readPreferences(IStructuredSelection selection) {\r
-        IPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);\r
-\r
-        String recentPathsPref = store.getString(Preferences.RECENT_SHARED_LIBRARY_IMPORT_LOCATIONS);\r
-        Deque<String> recentImportPaths = Preferences.decodePaths(recentPathsPref);\r
-\r
-        ISessionContext ctx = SimanticsUI.getSessionContext();\r
-        if (ctx == null)\r
-            return false;\r
-        IProject project = ctx.getHint(ProjectKeys.KEY_PROJECT);\r
-        if (project == null)\r
-            return false;\r
-\r
-        importModel = new ImportPlan(ctx, recentImportPaths);\r
-        importModel.project = project;\r
-        importModel.selection = selection.getFirstElement();\r
-\r
-        return true;\r
-    }\r
-\r
-    private void writePreferences() throws IOException {\r
-        IPersistentPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);\r
-\r
-        store.putValue(Preferences.RECENT_SHARED_LIBRARY_IMPORT_LOCATIONS, Preferences.encodePaths(importModel.recentLocations));\r
-\r
-        if (store.needsSaving())\r
-            store.save();\r
-    }\r
-\r
-    public SharedOntologyImportWizard() {\r
-        setWindowTitle("Import Shared Library");\r
-        setNeedsProgressMonitor(true);\r
-    }\r
-\r
-    @Override\r
-    public void init(IWorkbench workbench, IStructuredSelection selection) {\r
-        readPreferences(selection);\r
-    }\r
-\r
-    @Override\r
-    public void addPages() {\r
-        super.addPages();\r
-        if (importModel != null) {\r
-            addPage(new SharedOntologyImportPage(importModel));\r
-        } else {\r
-            addPage(new NoProjectPage("Import Shared Library"));\r
-        }\r
-    }\r
-\r
-    @Override\r
-    public boolean performFinish() {\r
-        try {\r
-               importModel.recentLocations.addFirst(importModel.importLocation.getAbsolutePath());\r
-            Preferences.removeDuplicates(importModel.recentLocations);\r
-            if (importModel.recentLocations.size() > MAX_RECENT_IMPORT_PATHS)\r
-               importModel.recentLocations.pollLast();\r
-\r
-            writePreferences();\r
-        } catch (IOException e) {\r
-            ErrorLogger.defaultLogError("Failed to write preferences", e);\r
-        }\r
-\r
-        try {\r
-            getContainer().run(true, true, new IRunnableWithProgress() {\r
-                @Override\r
-                public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {\r
-                    try {\r
-                       Resource target = ResourceAdaptionUtils.toSingleResource(importModel.selection);\r
-                       importModel.sessionContext.getSession().markUndoPoint();\r
-                        doImport(monitor, importModel.importLocation, importModel.sessionContext.getSession(), target);\r
-                    } catch (Exception e) {\r
-                        throw new InvocationTargetException(e);\r
-                    }\r
-                }\r
-            });\r
-        } catch (InvocationTargetException e) {\r
-            Throwable t = e.getTargetException();\r
-            WizardPage cp = (WizardPage) getContainer().getCurrentPage();\r
-            if (t instanceof IOException) {\r
-                cp.setErrorMessage("An I/O problem occurred while importing shared library.\n\nMessage: " + e.getMessage());\r
-            }\r
-            ErrorLogger.defaultLogError(t);\r
-            return false;\r
-        } catch (InterruptedException e) {\r
-            ExceptionUtils.logAndShowError(e);\r
-            return false;\r
-        }\r
-\r
-        return true;\r
-    }\r
-\r
-    public static void doImport(final IProgressMonitor monitor, File modelFile, final Session session, final Resource target)\r
-    throws IOException, SerializationException, DatabaseException {\r
-       \r
-        try {\r
-               \r
-            monitor.beginTask("Loading shared library from disk", 1000);\r
-            try {\r
-                FormatHandler<Object> handler1 = new FormatHandler<Object>() {\r
-                    @Override\r
-                    public Binding getBinding() {\r
-                        return TransferableGraph1.BINDING;\r
-                    }\r
-\r
-                    @Override\r
-                    public Object process(DataContainer container) throws Exception {\r
-                        monitor.worked(100);\r
-                        monitor.setTaskName("Importing shared library into database");\r
-                       Variant draftStatus = container.metadata.get(DraftStatusBean.EXTENSION_KEY);\r
-                        TransferableGraph1 tg = (TransferableGraph1)container.content.getValue();\r
-                        MigrationUtils.importSharedOntology(session, tg, draftStatus == null);\r
-                        monitor.worked(850);\r
-                        return null;\r
-                    }\r
-                    \r
-                };\r
-\r
-                HashMap<String, FormatHandler<Object>> handlers = new HashMap<String, FormatHandler<Object>>();\r
-                handlers.put(Constants.SHARED_LIBRARY_FORMAT_V1, handler1);\r
-\r
-                try {\r
-                    DataContainers.readFile(modelFile, handlers);\r
-                } catch(DataFormatException e) {\r
-                    throw new IOException(e);\r
-                } catch(IOException e) {\r
-                    throw e;\r
-                } catch (MissingDependencyException e) {\r
-                    ExceptionUtils.logAndShowError(e.getShortExplanation(), e.getMessage() + "\n\n", e);\r
-                    ErrorLogger.defaultLogError("Shared Library import failed, see exception for details", e);\r
-                } catch(Exception e) {\r
-                    if(e instanceof RuntimeException)\r
-                        throw (RuntimeException)e;\r
-                    else\r
-                        throw new RuntimeException(e);\r
-                }\r
-            } catch(IOException e) {\r
-            }\r
-\r
-            monitor.setTaskName("Postprocessing");\r
-            monitor.worked(50);\r
-\r
-        } catch (Throwable t) {\r
-            t.printStackTrace();\r
-        } finally {\r
-            monitor.done();\r
-        }\r
-    }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2012 Association for Decentralized Information Management in
+ * Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ *     VTT Technical Research Centre of Finland - initial API and implementation
+ *******************************************************************************/
+package org.simantics.modeling.ui.sharedontology.wizard;
+
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.SubMonitor;
+import org.eclipse.core.runtime.preferences.InstanceScope;
+import org.eclipse.jface.operation.IRunnableWithProgress;
+import org.eclipse.jface.preference.IPersistentPreferenceStore;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.wizard.Wizard;
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.ui.IImportWizard;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.preferences.ScopedPreferenceStore;
+import org.simantics.databoard.binding.Binding;
+import org.simantics.databoard.binding.mutable.Variant;
+import org.simantics.databoard.container.DataContainer;
+import org.simantics.databoard.container.DataContainers;
+import org.simantics.databoard.container.FormatHandler;
+import org.simantics.db.Resource;
+import org.simantics.db.Session;
+import org.simantics.db.layer0.migration.MigrationUtils;
+import org.simantics.db.layer0.util.DraftStatusBean;
+import org.simantics.db.management.ISessionContext;
+import org.simantics.graph.db.MissingDependencyException;
+import org.simantics.graph.representation.TransferableGraph1;
+import org.simantics.modeling.ui.Activator;
+import org.simantics.modeling.ui.utils.NoProjectPage;
+import org.simantics.project.IProject;
+import org.simantics.project.ProjectKeys;
+import org.simantics.ui.SimanticsUI;
+import org.simantics.ui.utils.ResourceAdaptionUtils;
+import org.simantics.utils.ui.ErrorLogger;
+import org.simantics.utils.ui.ExceptionUtils;
+
+/**
+ * @author Tuukka Lehtonen
+ */
+public class SharedOntologyImportWizard extends Wizard implements IImportWizard {
+
+    private static final int MAX_RECENT_IMPORT_PATHS = 10;
+
+    ImportPlan        importModel;
+
+    private boolean readPreferences(IStructuredSelection selection) {
+        IPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);
+
+        String recentPathsPref = store.getString(Preferences.RECENT_SHARED_LIBRARY_IMPORT_LOCATIONS);
+        Deque<String> recentImportPaths = Preferences.decodePaths(recentPathsPref);
+
+        ISessionContext ctx = SimanticsUI.getSessionContext();
+        if (ctx == null)
+            return false;
+        IProject project = ctx.getHint(ProjectKeys.KEY_PROJECT);
+        if (project == null)
+            return false;
+
+        importModel = new ImportPlan(ctx, recentImportPaths);
+        importModel.project = project;
+        importModel.selection = selection.getFirstElement();
+
+        return true;
+    }
+
+    private void writePreferences() throws IOException {
+        IPersistentPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);
+
+        store.putValue(Preferences.RECENT_SHARED_LIBRARY_IMPORT_LOCATIONS, Preferences.encodePaths(importModel.recentLocations));
+
+        if (store.needsSaving())
+            store.save();
+    }
+
+    public SharedOntologyImportWizard() {
+        setWindowTitle("Import Shared Library");
+        setNeedsProgressMonitor(true);
+    }
+
+    @Override
+    public void init(IWorkbench workbench, IStructuredSelection selection) {
+        readPreferences(selection);
+    }
+
+    @Override
+    public void addPages() {
+        super.addPages();
+        if (importModel != null) {
+            addPage(new SharedOntologyImportPage(importModel));
+        } else {
+            addPage(new NoProjectPage("Import Shared Library"));
+        }
+    }
+
+    @Override
+    public boolean performFinish() {
+        try {
+            importModel.recentLocations.addFirst(importModel.importLocation.getAbsolutePath());
+            Preferences.removeDuplicates(importModel.recentLocations);
+            if (importModel.recentLocations.size() > MAX_RECENT_IMPORT_PATHS)
+                importModel.recentLocations.pollLast();
+
+            writePreferences();
+        } catch (IOException e) {
+            ErrorLogger.defaultLogError("Failed to write preferences", e);
+        }
+
+        try {
+            getContainer().run(true, true, new IRunnableWithProgress() {
+                @Override
+                public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
+                    try {
+                        Resource target = ResourceAdaptionUtils.toSingleResource(importModel.selection);
+                        importModel.sessionContext.getSession().markUndoPoint();
+                        doImport(monitor, importModel.importLocation, importModel.sessionContext.getSession(), target);
+                    } catch (Exception e) {
+                        throw new InvocationTargetException(e);
+                    } finally {
+                        monitor.done();
+                    }
+                }
+            });
+        } catch (InvocationTargetException e) {
+            Throwable cause = e.getCause();
+            WizardPage cp = (WizardPage) getContainer().getCurrentPage();
+            if (cause instanceof MissingDependencyException) {
+                cp.setErrorMessage("Failed to import shared library due to missing dependencies.\n" + cause.getMessage());
+                ErrorLogger.defaultLogError("Shared Library " + importModel.importLocation + " import failed due to missing database dependencies. See exception for details.", cause);
+                ExceptionUtils.showError("Failed to import shared library due to missing dependencies.\n\n" + cause.getMessage(), null);
+            } else {
+                cp.setErrorMessage("Unexpected problem importing shared library.\nMessage: " + cause.getMessage());
+                ErrorLogger.defaultLogError("Shared Library " + importModel.importLocation + " import failed unexpectedly. See exception for details.", cause);
+                ExceptionUtils.showError("Unexpected problem importing shared library.\n\n" + cause.getMessage(), cause);
+            }
+            return false;
+        } catch (InterruptedException e) {
+            WizardPage cp = (WizardPage) getContainer().getCurrentPage();
+            cp.setErrorMessage("Import interrupted.\nMessage: " + e.getMessage());
+            ErrorLogger.defaultLogError("Shared Library " + importModel.importLocation + " import interrupted.", e);
+            ExceptionUtils.showError("Shared library import was interrupted.", e);
+            return false;
+        }
+
+        return true;
+    }
+
+    public static void doImport(IProgressMonitor monitor, File modelFile, Session session, Resource target)
+            throws Exception
+    {
+        SubMonitor mon = SubMonitor.convert(monitor);
+        mon.beginTask("Loading shared library from disk", 1000);
+
+        FormatHandler<Object> handler1 = new FormatHandler<Object>() {
+            @Override
+            public Binding getBinding() {
+                return TransferableGraph1.BINDING;
+            }
+
+            @Override
+            public Object process(DataContainer container) throws Exception {
+                mon.worked(100);
+                mon.setTaskName("Importing shared library into database");
+                Variant draftStatus = container.metadata.get(DraftStatusBean.EXTENSION_KEY);
+                TransferableGraph1 tg = (TransferableGraph1) container.content.getValue();
+                MigrationUtils.importSharedOntology(mon.newChild(850, SubMonitor.SUPPRESS_NONE), session, tg, draftStatus == null);
+                return null;
+            }
+        };
+
+        Map<String, FormatHandler<Object>> handlers = new HashMap<>();
+        handlers.put(Constants.SHARED_LIBRARY_FORMAT_V1, handler1);
+
+        DataContainers.readFile(modelFile, handlers);
+
+        mon.setTaskName("Postprocessing");
+        mon.subTask("");
+        mon.newChild(50).done();
+    }
+
+}