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