]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/sharedontology/wizard/SharedOntologyImportWizard.java
Import/export changes. A load.
[simantics/platform.git] / bundles / org.simantics.modeling.ui / src / org / simantics / modeling / ui / sharedontology / wizard / SharedOntologyImportWizard.java
1 /*******************************************************************************
2  * Copyright (c) 2012 Association for Decentralized Information Management in
3  * 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.modeling.ui.sharedontology.wizard;
13
14 import java.io.File;
15 import java.io.IOException;
16 import java.lang.reflect.InvocationTargetException;
17 import java.util.Deque;
18 import java.util.HashMap;
19 import java.util.Map;
20
21 import org.eclipse.core.runtime.IProgressMonitor;
22 import org.eclipse.core.runtime.SubMonitor;
23 import org.eclipse.core.runtime.preferences.InstanceScope;
24 import org.eclipse.jface.operation.IRunnableWithProgress;
25 import org.eclipse.jface.preference.IPersistentPreferenceStore;
26 import org.eclipse.jface.preference.IPreferenceStore;
27 import org.eclipse.jface.viewers.IStructuredSelection;
28 import org.eclipse.jface.wizard.Wizard;
29 import org.eclipse.jface.wizard.WizardPage;
30 import org.eclipse.swt.SWT;
31 import org.eclipse.ui.IImportWizard;
32 import org.eclipse.ui.IWorkbench;
33 import org.eclipse.ui.preferences.ScopedPreferenceStore;
34 import org.simantics.databoard.binding.Binding;
35 import org.simantics.databoard.binding.mutable.Variant;
36 import org.simantics.databoard.container.DataContainer;
37 import org.simantics.databoard.container.DataContainers;
38 import org.simantics.databoard.container.FormatHandler;
39 import org.simantics.db.Resource;
40 import org.simantics.db.Session;
41 import org.simantics.db.layer0.migration.MigratedImportResult;
42 import org.simantics.db.layer0.migration.MigrationUtils;
43 import org.simantics.db.layer0.util.DraftStatusBean;
44 import org.simantics.db.management.ISessionContext;
45 import org.simantics.graph.db.MissingDependencyException;
46 import org.simantics.graph.representation.TransferableGraph1;
47 import org.simantics.modeling.ui.Activator;
48 import org.simantics.modeling.ui.utils.NoProjectPage;
49 import org.simantics.project.IProject;
50 import org.simantics.project.ProjectKeys;
51 import org.simantics.ui.SimanticsUI;
52 import org.simantics.ui.utils.ResourceAdaptionUtils;
53 import org.simantics.utils.strings.EString;
54 import org.simantics.utils.ui.ErrorLogger;
55 import org.simantics.utils.ui.ExceptionUtils;
56 import org.simantics.utils.ui.dialogs.InfoDialog;
57
58 /**
59  * @author Tuukka Lehtonen
60  */
61 public class SharedOntologyImportWizard extends Wizard implements IImportWizard {
62
63     private static final int MAX_RECENT_IMPORT_PATHS = 10;
64
65     ImportPlan        importModel;
66
67     private boolean readPreferences(IStructuredSelection selection) {
68         IPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);
69
70         String recentPathsPref = store.getString(Preferences.RECENT_SHARED_LIBRARY_IMPORT_LOCATIONS);
71         Deque<String> recentImportPaths = Preferences.decodePaths(recentPathsPref);
72
73         ISessionContext ctx = SimanticsUI.getSessionContext();
74         if (ctx == null)
75             return false;
76         IProject project = ctx.getHint(ProjectKeys.KEY_PROJECT);
77         if (project == null)
78             return false;
79
80         importModel = new ImportPlan(ctx, recentImportPaths);
81         importModel.project = project;
82         importModel.selection = selection.getFirstElement();
83
84         return true;
85     }
86
87     private void writePreferences() throws IOException {
88         IPersistentPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);
89
90         store.putValue(Preferences.RECENT_SHARED_LIBRARY_IMPORT_LOCATIONS, Preferences.encodePaths(importModel.recentLocations));
91
92         if (store.needsSaving())
93             store.save();
94     }
95
96     public SharedOntologyImportWizard() {
97         setWindowTitle("Import Shared Library");
98         setNeedsProgressMonitor(true);
99     }
100
101     @Override
102     public void init(IWorkbench workbench, IStructuredSelection selection) {
103         readPreferences(selection);
104     }
105
106     @Override
107     public void addPages() {
108         super.addPages();
109         if (importModel != null) {
110             addPage(new SharedOntologyImportPage(importModel));
111         } else {
112             addPage(new NoProjectPage("Import Shared Library"));
113         }
114     }
115
116     @Override
117     public boolean performFinish() {
118         try {
119             importModel.recentLocations.addFirst(importModel.importLocation.getAbsolutePath());
120             Preferences.removeDuplicates(importModel.recentLocations);
121             if (importModel.recentLocations.size() > MAX_RECENT_IMPORT_PATHS)
122                 importModel.recentLocations.pollLast();
123
124             writePreferences();
125         } catch (IOException e) {
126             ErrorLogger.defaultLogError("Failed to write preferences", e);
127         }
128
129         try {
130             MigratedImportResult[] result = { null };
131             getContainer().run(true, true, new IRunnableWithProgress() {
132                 @Override
133                 public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
134                     try {
135                         Resource target = ResourceAdaptionUtils.toSingleResource(importModel.selection);
136                         importModel.sessionContext.getSession().markUndoPoint();
137                         result[0] = doImport(monitor, importModel.importLocation, importModel.sessionContext.getSession(), target);
138                     } catch (Exception e) {
139                         throw new InvocationTargetException(e);
140                     } finally {
141                         monitor.done();
142                     }
143                 }
144             });
145
146             if (result[0].hasMissingExternals()) {
147                 InfoDialog.open(getShell(), "Missing Externals Created",
148                         "The system was unable to find some of the external entities referenced by the imported material. Place-holders have been created for the missing entities.\nThe missing entities are:\n"
149                                 + EString.implode(result[0].tgResult.missingExternals),
150                         SWT.SHEET);
151             }
152         } catch (InvocationTargetException e) {
153             Throwable cause = e.getCause();
154             WizardPage cp = (WizardPage) getContainer().getCurrentPage();
155             if (cause instanceof MissingDependencyException) {
156                 cp.setErrorMessage("Failed to import shared library due to missing dependencies.\n" + cause.getMessage());
157                 ErrorLogger.defaultLogError("Shared Library " + importModel.importLocation + " import failed due to missing database dependencies. See exception for details.", cause);
158                 ExceptionUtils.showError("Failed to import shared library due to missing dependencies.\n\n" + cause.getMessage(), null);
159             } else {
160                 cp.setErrorMessage("Unexpected problem importing shared library.\nMessage: " + cause.getMessage());
161                 ErrorLogger.defaultLogError("Shared Library " + importModel.importLocation + " import failed unexpectedly. See exception for details.", cause);
162                 ExceptionUtils.showError("Unexpected problem importing shared library.\n\n" + cause.getMessage(), cause);
163             }
164             return false;
165         } catch (InterruptedException e) {
166             WizardPage cp = (WizardPage) getContainer().getCurrentPage();
167             cp.setErrorMessage("Import interrupted.\nMessage: " + e.getMessage());
168             ErrorLogger.defaultLogError("Shared Library " + importModel.importLocation + " import interrupted.", e);
169             ExceptionUtils.showError("Shared library import was interrupted.", e);
170             return false;
171         }
172
173         return true;
174     }
175
176     public static MigratedImportResult doImport(IProgressMonitor monitor, File modelFile, Session session, Resource target)
177             throws Exception
178     {
179         SubMonitor mon = SubMonitor.convert(monitor);
180         mon.beginTask("Loading shared library from disk", 1000);
181
182         FormatHandler<MigratedImportResult> handler1 = new FormatHandler<MigratedImportResult>() {
183             @Override
184             public Binding getBinding() {
185                 return TransferableGraph1.BINDING;
186             }
187
188             @Override
189             public MigratedImportResult process(DataContainer container) throws Exception {
190                 mon.worked(100);
191                 mon.setTaskName("Importing shared library into database");
192                 Variant draftStatus = container.metadata.get(DraftStatusBean.EXTENSION_KEY);
193                 TransferableGraph1 tg = (TransferableGraph1) container.content.getValue();
194                 return MigrationUtils.importSharedOntology(mon.newChild(850, SubMonitor.SUPPRESS_NONE), session, tg, draftStatus == null);
195             }
196         };
197
198         Map<String, FormatHandler<MigratedImportResult>> handlers = new HashMap<>();
199         handlers.put(Constants.SHARED_LIBRARY_FORMAT_V1, handler1);
200
201         MigratedImportResult result = DataContainers.readFile(modelFile, handlers);
202
203         mon.setTaskName("Postprocessing");
204         mon.subTask("");
205         mon.newChild(50).done();
206
207         return result;
208     }
209
210 }