]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.annotation.ui/src/org/simantics/annotation/ui/wizard/AnnotationTypeImportWizard.java
Fixed all line endings of the repository
[simantics/platform.git] / bundles / org.simantics.annotation.ui / src / org / simantics / annotation / ui / wizard / AnnotationTypeImportWizard.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.annotation.ui.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
20 import org.eclipse.core.runtime.IProgressMonitor;
21 import org.eclipse.core.runtime.preferences.InstanceScope;
22 import org.eclipse.jface.operation.IRunnableWithProgress;
23 import org.eclipse.jface.preference.IPersistentPreferenceStore;
24 import org.eclipse.jface.preference.IPreferenceStore;
25 import org.eclipse.jface.viewers.IStructuredSelection;
26 import org.eclipse.jface.wizard.Wizard;
27 import org.eclipse.jface.wizard.WizardPage;
28 import org.eclipse.ui.IImportWizard;
29 import org.eclipse.ui.IWorkbench;
30 import org.eclipse.ui.preferences.ScopedPreferenceStore;
31 import org.simantics.annotation.ui.Activator;
32 import org.simantics.databoard.binding.Binding;
33 import org.simantics.databoard.container.DataContainer;
34 import org.simantics.databoard.container.DataContainers;
35 import org.simantics.databoard.container.DataFormatException;
36 import org.simantics.databoard.container.FormatHandler;
37 import org.simantics.databoard.serialization.SerializationException;
38 import org.simantics.db.ReadGraph;
39 import org.simantics.db.Resource;
40 import org.simantics.db.Session;
41 import org.simantics.db.exception.DatabaseException;
42 import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;
43 import org.simantics.db.management.ISessionContext;
44 import org.simantics.graph.db.TransferableGraphs;
45 import org.simantics.graph.representation.TransferableGraph1;
46 import org.simantics.modeling.ui.utils.NoProjectPage;
47 import org.simantics.project.IProject;
48 import org.simantics.project.ProjectKeys;
49 import org.simantics.ui.SimanticsUI;
50 import org.simantics.ui.utils.ResourceAdaptionUtils;
51 import org.simantics.utils.ui.ErrorLogger;
52 import org.simantics.utils.ui.ExceptionUtils;
53
54 /**
55  * @author Tuukka Lehtonen
56  */
57 public class AnnotationTypeImportWizard extends Wizard implements IImportWizard {
58
59     private static final int MAX_RECENT_IMPORT_PATHS = 10;
60
61     ImportPlan        importModel;
62
63     private boolean readPreferences(IStructuredSelection selection) {
64         IPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);
65
66         String recentPathsPref = store.getString(Preferences.RECENT_ANNOTATION_TYPE_IMPORT_LOCATIONS);
67         Deque<String> recentImportPaths = Preferences.decodePaths(recentPathsPref);
68
69         ISessionContext ctx = SimanticsUI.getSessionContext();
70         if (ctx == null)
71             return false;
72         IProject project = ctx.getHint(ProjectKeys.KEY_PROJECT);
73         if (project == null)
74             return false;
75
76         importModel = new ImportPlan(ctx, recentImportPaths);
77         importModel.project = project;
78         importModel.selection = selection.getFirstElement();
79
80         return true;
81     }
82
83     private void writePreferences() throws IOException {
84         IPersistentPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID);
85
86         store.putValue(Preferences.RECENT_ANNOTATION_TYPE_IMPORT_LOCATIONS, Preferences.encodePaths(importModel.recentLocations));
87
88         if (store.needsSaving())
89             store.save();
90     }
91
92     public AnnotationTypeImportWizard() {
93         setWindowTitle("Import Annotation Type");
94         setNeedsProgressMonitor(true);
95     }
96
97     @Override
98     public void init(IWorkbench workbench, IStructuredSelection selection) {
99         readPreferences(selection);
100     }
101
102     @Override
103     public void addPages() {
104         super.addPages();
105         if (importModel != null) {
106             addPage(new AnnotationTypeImportPage(importModel));
107         } else {
108             addPage(new NoProjectPage("Import Annotation Type"));
109         }
110     }
111
112     @Override
113     public boolean performFinish() {
114         try {
115                 importModel.recentLocations.addFirst(importModel.importLocation.getAbsolutePath());
116             Preferences.removeDuplicates(importModel.recentLocations);
117             if (importModel.recentLocations.size() > MAX_RECENT_IMPORT_PATHS)
118                 importModel.recentLocations.pollLast();
119
120             writePreferences();
121         } catch (IOException e) {
122             ErrorLogger.defaultLogError("Failed to write preferences", e);
123         }
124
125         try {
126             getContainer().run(true, true, new IRunnableWithProgress() {
127                 @Override
128                 public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
129                     try {
130                         Resource target = ResourceAdaptionUtils.toSingleResource(importModel.selection);
131                         doImport(monitor, importModel.importLocation, importModel.sessionContext.getSession(), target);
132                     } catch (Exception e) {
133                         throw new InvocationTargetException(e);
134                     }
135                 }
136             });
137         } catch (InvocationTargetException e) {
138             Throwable t = e.getTargetException();
139             WizardPage cp = (WizardPage) getContainer().getCurrentPage();
140             if (t instanceof IOException) {
141                 cp.setErrorMessage("An I/O problem occurred while importing annotation type.\n\nMessage: " + e.getMessage());
142             }
143             ErrorLogger.defaultLogError(t);
144             return false;
145         } catch (InterruptedException e) {
146             ExceptionUtils.logAndShowError(e);
147             return false;
148         }
149
150         return true;
151     }
152
153
154     public static void doImport(final IProgressMonitor monitor, File modelFile, final Session session, final Resource target)
155     throws IOException, SerializationException, DatabaseException {
156         try {
157             final DefaultPasteImportAdvisor advisor = new DefaultPasteImportAdvisor(target);
158
159             monitor.beginTask("Loading annotation type from disk", 1000);
160             try {
161                 FormatHandler<Object> handler1 = new FormatHandler<Object>() {
162                     @Override
163                     public Binding getBinding() {
164                         return TransferableGraph1.BINDING;
165                     }
166
167                     @Override
168                     public Object process(DataContainer container)
169                             throws Exception {
170                         monitor.worked(100);
171                         monitor.setTaskName("Importing annotation type into database");
172                         TransferableGraphs.importGraph1(session, (TransferableGraph1)container.content.getValue(), 
173                                 advisor, null);
174                         monitor.worked(850);
175                         return null;
176                     }
177                 };
178
179                 HashMap<String, FormatHandler<Object>> handlers = new HashMap<String, FormatHandler<Object>>();
180                 handlers.put(Constants.ANNOTATION_TYPE_FORMAT_V1, handler1);
181
182                 try {
183                     DataContainers.readFile(modelFile, handlers);
184                 } catch(DataFormatException e) {
185                     throw new IOException(e);
186                 } catch(IOException e) {
187                     throw e;
188                 } catch(Exception e) {
189                     if(e instanceof RuntimeException)
190                         throw (RuntimeException)e;
191                     else
192                         throw new RuntimeException(e);
193                 }
194             } catch(IOException e) {
195             }
196
197             monitor.setTaskName("Postprocessing");
198             monitor.worked(50);
199
200         } catch (Throwable t) {
201             t.printStackTrace();
202         } finally {
203             monitor.done();
204         }
205     }
206
207 }