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