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