/******************************************************************************* * Copyright (c) 2012 Association for Decentralized Information Management in * Industry THTH ry. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * VTT Technical Research Centre of Finland - initial API and implementation *******************************************************************************/ package org.simantics.modeling.ui.sharedontology.wizard; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Deque; import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.preference.IPersistentPreferenceStore; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.ui.IImportWizard; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.preferences.ScopedPreferenceStore; import org.simantics.databoard.binding.Binding; import org.simantics.databoard.binding.mutable.Variant; import org.simantics.databoard.container.DataContainer; import org.simantics.databoard.container.DataContainers; import org.simantics.databoard.container.FormatHandler; import org.simantics.databoard.util.URIStringUtils; import org.simantics.db.Resource; import org.simantics.db.Session; import org.simantics.db.layer0.migration.MigratedImportResult; import org.simantics.db.layer0.migration.MigrationUtils; import org.simantics.db.layer0.util.DraftStatusBean; import org.simantics.db.management.ISessionContext; import org.simantics.graph.db.MissingDependencyException; import org.simantics.graph.representation.TransferableGraph1; import org.simantics.modeling.ui.Activator; import org.simantics.modeling.ui.utils.NoProjectPage; import org.simantics.project.IProject; import org.simantics.project.ProjectKeys; import org.simantics.ui.SimanticsUI; import org.simantics.ui.utils.ResourceAdaptionUtils; import org.simantics.utils.strings.EString; import org.simantics.utils.ui.ErrorLogger; import org.simantics.utils.ui.ExceptionUtils; import org.simantics.utils.ui.dialogs.InfoDialog; /** * @author Tuukka Lehtonen */ public class SharedOntologyImportWizard extends Wizard implements IImportWizard { private static final int MAX_RECENT_IMPORT_PATHS = 10; ImportPlan importModel; private boolean readPreferences(IStructuredSelection selection) { IPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID); String recentPathsPref = store.getString(Preferences.RECENT_SHARED_LIBRARY_IMPORT_LOCATIONS); Deque recentImportPaths = Preferences.decodePaths(recentPathsPref); ISessionContext ctx = SimanticsUI.getSessionContext(); if (ctx == null) return false; IProject project = ctx.getHint(ProjectKeys.KEY_PROJECT); if (project == null) return false; importModel = new ImportPlan(ctx, recentImportPaths); importModel.project = project; importModel.selection = selection.getFirstElement(); return true; } private void writePreferences() throws IOException { IPersistentPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.PLUGIN_ID); store.putValue(Preferences.RECENT_SHARED_LIBRARY_IMPORT_LOCATIONS, Preferences.encodePaths(importModel.recentLocations)); if (store.needsSaving()) store.save(); } public SharedOntologyImportWizard() { setWindowTitle("Import Shared Library"); setNeedsProgressMonitor(true); } @Override public void init(IWorkbench workbench, IStructuredSelection selection) { readPreferences(selection); } @Override public void addPages() { super.addPages(); if (importModel != null) { addPage(new SharedOntologyImportPage(importModel)); } else { addPage(new NoProjectPage("Import Shared Library")); } } @Override public boolean performFinish() { try { importModel.recentLocations.addFirst(importModel.importLocation.getAbsolutePath()); Preferences.removeDuplicates(importModel.recentLocations); if (importModel.recentLocations.size() > MAX_RECENT_IMPORT_PATHS) importModel.recentLocations.pollLast(); writePreferences(); } catch (IOException e) { ErrorLogger.defaultLogError("Failed to write preferences", e); } try { MigratedImportResult[] result = { null }; getContainer().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { Resource target = ResourceAdaptionUtils.toSingleResource(importModel.selection); importModel.sessionContext.getSession().markUndoPoint(); result[0] = doImport(monitor, importModel.importLocation, importModel.sessionContext.getSession(), target); } catch (Exception e) { throw new InvocationTargetException(e); } finally { monitor.done(); } } }); if (result[0].hasMissingExternals()) { InfoDialog.open(getShell(), "Missing Externals Created", "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" + URIStringUtils.unescape(EString.implode(result[0].tgResult.missingExternals)), SWT.SHEET); } } catch (InvocationTargetException e) { Throwable cause = e.getCause(); WizardPage cp = (WizardPage) getContainer().getCurrentPage(); if (cause instanceof MissingDependencyException) { cp.setErrorMessage("Failed to import shared library due to missing dependencies.\n" + cause.getMessage()); ErrorLogger.defaultLogError("Shared Library " + importModel.importLocation + " import failed due to missing database dependencies. See exception for details.", cause); ExceptionUtils.showError("Failed to import shared library due to missing dependencies.\n\n" + cause.getMessage(), null); } else { cp.setErrorMessage("Unexpected problem importing shared library.\nMessage: " + cause.getMessage()); ErrorLogger.defaultLogError("Shared Library " + importModel.importLocation + " import failed unexpectedly. See exception for details.", cause); ExceptionUtils.showError("Unexpected problem importing shared library.\n\n" + cause.getMessage(), cause); } return false; } catch (InterruptedException e) { WizardPage cp = (WizardPage) getContainer().getCurrentPage(); cp.setErrorMessage("Import interrupted.\nMessage: " + e.getMessage()); ErrorLogger.defaultLogError("Shared Library " + importModel.importLocation + " import interrupted.", e); ExceptionUtils.showError("Shared library import was interrupted.", e); return false; } return true; } public static MigratedImportResult doImport(IProgressMonitor monitor, File modelFile, Session session, Resource target) throws Exception { SubMonitor mon = SubMonitor.convert(monitor); mon.beginTask("Loading shared library from disk", 1000); FormatHandler handler1 = new FormatHandler() { @Override public Binding getBinding() { return TransferableGraph1.BINDING; } @Override public MigratedImportResult process(DataContainer container) throws Exception { mon.worked(100); mon.setTaskName("Importing shared library into database"); Variant draftStatus = container.metadata.get(DraftStatusBean.EXTENSION_KEY); TransferableGraph1 tg = (TransferableGraph1) container.content.getValue(); return MigrationUtils.importSharedOntology(mon.newChild(850, SubMonitor.SUPPRESS_NONE), session, tg, draftStatus == null); } }; Map> handlers = new HashMap<>(); handlers.put(Constants.SHARED_LIBRARY_FORMAT_V1, handler1); MigratedImportResult result = DataContainers.readFile(modelFile, handlers); mon.setTaskName("Postprocessing"); mon.subTask(""); mon.newChild(50).done(); return result; } }