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