1 /*******************************************************************************
2 * Copyright (c) 2012 Association for Decentralized Information Management in
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
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.modeling.ui.sharedontology.wizard;
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;
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.common.primitiverequest.PossibleResource;
44 import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;
45 import org.simantics.db.layer0.migration.MigratedImportResult;
46 import org.simantics.db.layer0.migration.MigrationState;
47 import org.simantics.db.layer0.migration.MigrationStateKeys;
48 import org.simantics.db.layer0.migration.MigrationUtils;
49 import org.simantics.db.layer0.util.ModelDependenciesBean;
50 import org.simantics.db.layer0.util.ModelDependency;
51 import org.simantics.db.management.ISessionContext;
52 import org.simantics.graph.db.ImportResult;
53 import org.simantics.graph.db.MissingDependencyException;
54 import org.simantics.graph.representation.TransferableGraph1;
55 import org.simantics.modeling.ui.Activator;
56 import org.simantics.modeling.ui.utils.NoProjectPage;
57 import org.simantics.project.IProject;
58 import org.simantics.project.ProjectKeys;
59 import org.simantics.ui.SimanticsUI;
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;
66 * @author Tuukka Lehtonen
68 public class ModelImportWizard extends Wizard implements IImportWizard {
70 private static final int MAX_RECENT_IMPORT_PATHS = 10;
72 ImportPlan importModel;
74 private boolean readPreferences(IStructuredSelection selection) {
75 IPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);
77 String recentPathsPref = store.getString(Preferences.RECENT_SHARED_LIBRARY_IMPORT_LOCATIONS);
78 Deque<String> recentImportPaths = Preferences.decodePaths(recentPathsPref);
80 ISessionContext ctx = SimanticsUI.getSessionContext();
83 IProject project = ctx.getHint(ProjectKeys.KEY_PROJECT);
87 importModel = new ImportPlan(ctx, recentImportPaths);
88 importModel.project = project;
89 importModel.selection = selection.getFirstElement();
94 private void writePreferences() throws IOException {
95 IPersistentPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);
97 store.putValue(Preferences.RECENT_SHARED_LIBRARY_IMPORT_LOCATIONS, Preferences.encodePaths(importModel.recentLocations));
99 if (store.needsSaving())
103 public ModelImportWizard() {
104 setWindowTitle("Import Model");
105 setNeedsProgressMonitor(true);
109 public void init(IWorkbench workbench, IStructuredSelection selection) {
110 readPreferences(selection);
114 public void addPages() {
116 if (importModel != null) {
117 addPage(new ModelImportPage(importModel));
119 addPage(new NoProjectPage("Import Model"));
124 public boolean performFinish() {
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();
132 } catch (IOException e) {
133 ErrorLogger.defaultLogError("Failed to write preferences", e);
137 MigratedImportResult[] result = { null };
138 getContainer().run(true, true, new IRunnableWithProgress() {
140 public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
142 Resource target = Simantics.getProjectResource();
143 importModel.sessionContext.getSession().markUndoPoint();
144 result[0] = doImport(monitor, importModel.importLocation, importModel.sessionContext.getSession(), target, importModel.includeDependencies);
145 } catch (Exception e) {
146 throw new InvocationTargetException(e);
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 + URIStringUtils.unescape(EString.implode(result[0].tgResult.missingExternals)),
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);
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);
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);
183 public static MigratedImportResult doImport(IProgressMonitor monitor, File modelFile, Session session, Resource target, boolean includeDependencies)
186 SubMonitor mon = SubMonitor.convert(monitor);
187 mon.beginTask("Loading model from disk", 1000);
189 FormatHandler<MigratedImportResult> handler1 = new FormatHandler<MigratedImportResult>() {
191 public Binding getBinding() {
192 return TransferableGraph1.BINDING;
196 public MigratedImportResult process(DataContainer container) throws Exception {
198 mon.setTaskName("Importing model into database");
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);
206 if(includeDependencies) {
207 final ModelDependenciesBean libraryDependenciesBean = ModelDependenciesBean.fromMigrationState(state);
208 if(libraryDependenciesBean != null) {
209 for(ModelDependency dependency : libraryDependenciesBean.dependencies) {
210 Resource existing = session.sync(new PossibleResource(dependency.uri));
211 if(existing == null) {
212 MigrationUtils.importSharedOntology(session, dependency.tg, false);
218 MigrationUtils.importMigrated(monitor, session, modelFile, state, new DefaultPasteImportAdvisor(target), target);
220 Collection<Resource> resultRoots = state.getProperty(MigrationStateKeys.CURRENT_ROOT_RESOURCES);
221 ImportResult result = state.getProperty(MigrationStateKeys.IMPORT_RESULT);
222 return new MigratedImportResult(resultRoots, result);
227 Map<String, FormatHandler<MigratedImportResult>> handlers = new HashMap<>();
228 handlers.put(":1", handler1);
229 handlers.put(Constants.MODEL_FORMAT_V1, handler1);
231 MigratedImportResult result = DataContainers.readFile(modelFile, handlers);
233 mon.setTaskName("Postprocessing");
235 mon.newChild(50).done();