]> gerrit.simantics Code Review - simantics/sysdyn.git/commitdiff
Migration for all imports: model, module and function library (fixes #3037)
authorlempinen <lempinen@ac1ea38d-2e2b-0410-8846-a27921b304fc>
Tue, 27 Nov 2012 06:41:35 +0000 (06:41 +0000)
committerlempinen <lempinen@ac1ea38d-2e2b-0410-8846-a27921b304fc>
Tue, 27 Nov 2012 06:41:35 +0000 (06:41 +0000)
git-svn-id: https://www.simantics.org/svn/simantics/sysdyn/trunk@26453 ac1ea38d-2e2b-0410-8846-a27921b304fc

12 files changed:
org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportFunctionLibrary.java
org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModelHandler.java
org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/exports/ExportModuleHandler.java
org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportFunctionLibrary.java
org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportModelHandler.java
org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/handlers/imports/ImportModuleHandler.java
org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/imports/ImportUtils.java [new file with mode: 0644]
org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/imports/SysdynFunctionLibraryImportAdvisor.java [new file with mode: 0644]
org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/imports/SysdynImportFormatHandler.java [new file with mode: 0644]
org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/functions/WizardFunctionsImportPage.java
org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/models/WizardModelsImportPage.java
org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/wizards/modules/WizardModulesImportPage.java

index 0784dd7c6ddeb00cec3f64a4b39bd7c8291be731..5fe78d5925b6210cd574ee0dce49d4619b2b8dd3 100644 (file)
@@ -39,7 +39,7 @@ import org.simantics.db.request.Read;
 import org.simantics.graph.representation.TransferableGraph1;\r
 import org.simantics.layer0.Layer0;\r
 import org.simantics.sysdyn.ui.Activator;\r
-import org.simantics.sysdyn.ui.handlers.imports.ImportFunctionLibrary;\r
+import org.simantics.sysdyn.ui.utils.imports.ImportUtils;\r
 import org.simantics.ui.SimanticsUI;\r
 import org.simantics.ui.utils.ResourceAdaptionUtils;\r
 import org.simantics.utils.datastructures.Pair;\r
@@ -85,7 +85,7 @@ public class ExportFunctionLibrary  extends AbstractHandler {
                FileDialog fd = new FileDialog(shell, SWT.SAVE);\r
                fd.setText("Export Function Library");\r
                fd.setFileName(name);\r
-               String path = Activator.getDefault().getPreferenceStore().getString(ImportFunctionLibrary.IMPORTFUNCTIONLIBRARYPATH);\r
+               String path = Activator.getDefault().getPreferenceStore().getString(ImportUtils.IMPORTFUNCTIONLIBRARYPATH);\r
                if(path.isEmpty() || !(new File(path).exists()))\r
                        path = Platform.getLocation().toOSString();\r
                fd.setFilterPath(path);\r
@@ -95,7 +95,7 @@ public class ExportFunctionLibrary  extends AbstractHandler {
                if(selected == null) return null;\r
                \r
                // Save location to preference store\r
-               Activator.getDefault().getPreferenceStore().setValue(ImportFunctionLibrary.IMPORTFUNCTIONLIBRARYPATH, (new File(selected)).getParent());\r
+               Activator.getDefault().getPreferenceStore().setValue(ImportUtils.IMPORTFUNCTIONLIBRARYPATH, (new File(selected)).getParent());\r
 \r
                // Asynchronously create the file using transferable graph\r
                SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
index f67d85940c647c7781d922c67c11756876f078da..e0040a692a76de2e60a70c23565c7406090136b6 100644 (file)
@@ -35,7 +35,7 @@ import org.simantics.graph.db.TransferableGraphSource;
 import org.simantics.graph.db.TransferableGraphs;\r
 import org.simantics.layer0.Layer0;\r
 import org.simantics.sysdyn.ui.Activator;\r
-import org.simantics.sysdyn.ui.handlers.imports.ImportModelHandler;\r
+import org.simantics.sysdyn.ui.utils.imports.ImportUtils;\r
 import org.simantics.ui.SimanticsUI;\r
 import org.simantics.ui.utils.ResourceAdaptionUtils;\r
 \r
@@ -81,7 +81,7 @@ public class ExportModelHandler extends AbstractHandler {
                FileDialog fd = new FileDialog(shell, SWT.SAVE);\r
                fd.setText("Export Model");\r
                fd.setFileName(name);\r
-               String path = Activator.getDefault().getPreferenceStore().getString(ImportModelHandler.IMPORTMODELTPATH);\r
+               String path = Activator.getDefault().getPreferenceStore().getString(ImportUtils.IMPORTMODELTPATH);\r
                if(path.isEmpty() || !(new File(path).exists()))\r
                        path = Platform.getLocation().toOSString();\r
                fd.setFilterPath(path);\r
@@ -91,7 +91,7 @@ public class ExportModelHandler extends AbstractHandler {
                if(selected == null) return null;\r
 \r
                // Save location to preference store\r
-               Activator.getDefault().getPreferenceStore().setValue(ImportModelHandler.IMPORTMODELTPATH, (new File(selected)).getParent());\r
+               Activator.getDefault().getPreferenceStore().setValue(ImportUtils.IMPORTMODELTPATH, (new File(selected)).getParent());\r
 \r
                // Asynchronously create the file using transferable graph\r
                SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
index 34958a0e82fcad94454adebf741be3bee4a14ef1..84449b769c7893dc0350fa44244612bd2cc37eb5 100644 (file)
@@ -48,7 +48,7 @@ import org.simantics.modeling.ModelingResources;
 import org.simantics.structural.stubs.StructuralResource2;\r
 import org.simantics.sysdyn.SysdynResource;\r
 import org.simantics.sysdyn.ui.Activator;\r
-import org.simantics.sysdyn.ui.handlers.imports.ImportModuleHandler;\r
+import org.simantics.sysdyn.ui.utils.imports.ImportUtils;\r
 import org.simantics.ui.SimanticsUI;\r
 import org.simantics.ui.utils.ResourceAdaptionUtils;\r
 import org.simantics.utils.datastructures.Pair;\r
@@ -151,7 +151,7 @@ public class ExportModuleHandler extends AbstractHandler {
                FileDialog fd = new FileDialog(shell, SWT.SAVE);\r
                fd.setText("Export Module");\r
                fd.setFileName(name);\r
-               String path = Activator.getDefault().getPreferenceStore().getString(ImportModuleHandler.IMPORTMODULETPATH);\r
+               String path = Activator.getDefault().getPreferenceStore().getString(ImportUtils.IMPORTMODULETPATH);\r
                if(path.isEmpty() || !(new File(path).exists()))\r
                        path = Platform.getLocation().toOSString();\r
                fd.setFilterPath(path);\r
@@ -161,7 +161,7 @@ public class ExportModuleHandler extends AbstractHandler {
                if(selected == null) return null;\r
                \r
         // Save location to preference store\r
-               Activator.getDefault().getPreferenceStore().setValue(ImportModuleHandler.IMPORTMODULETPATH, (new File(selected)).getParent());\r
+               Activator.getDefault().getPreferenceStore().setValue(ImportUtils.IMPORTMODULETPATH, (new File(selected)).getParent());\r
                \r
         // Asynchronously create the file using transferable graph\r
                SimanticsUI.getSession().asyncRequest(new ReadRequest() {\r
index 00ad8c362c782bb738efea6d0f15706252dadf93..5eb21b0af3b23a5aa169675faaf2a195897bbab1 100644 (file)
 package org.simantics.sysdyn.ui.handlers.imports;\r
 \r
 import java.io.File;\r
-import java.io.IOException;\r
-import java.util.HashMap;\r
 \r
 import org.eclipse.core.commands.AbstractHandler;\r
 import org.eclipse.core.commands.ExecutionEvent;\r
 import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
 import org.eclipse.core.runtime.Platform;\r
+import org.eclipse.core.runtime.jobs.Job;\r
 import org.eclipse.jface.viewers.ISelection;\r
 import org.eclipse.swt.SWT;\r
 import org.eclipse.swt.widgets.FileDialog;\r
-import org.eclipse.swt.widgets.MessageBox;\r
 import org.eclipse.swt.widgets.Shell;\r
 import org.eclipse.ui.handlers.HandlerUtil;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.databoard.binding.Binding;\r
-import org.simantics.databoard.container.DataContainer;\r
-import org.simantics.databoard.container.DataContainers;\r
-import org.simantics.databoard.container.DataFormatException;\r
-import org.simantics.databoard.container.FormatHandler;\r
-import org.simantics.db.ReadGraph;\r
+import org.simantics.DatabaseJob;\r
 import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.WriteOnlyGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.exception.ResourceNotFoundException;\r
-import org.simantics.db.layer0.adapter.impl.DefaultPasteHandler;\r
-import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.graph.representation.Root;\r
-import org.simantics.graph.representation.TransferableGraph1;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.sysdyn.SysdynResource;\r
 import org.simantics.sysdyn.ui.Activator;\r
 import org.simantics.sysdyn.ui.browser.nodes.FunctionsFolder;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.utils.AdaptionUtils;\r
+import org.simantics.sysdyn.ui.utils.imports.ImportUtils;\r
 import org.simantics.ui.utils.ResourceAdaptionUtils;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
 \r
 /**\r
  * Imports an exported function library (or shared function library) transferable graph. \r
@@ -60,8 +40,6 @@ import org.simantics.ui.utils.ResourceAdaptionUtils;
  */\r
 public class ImportFunctionLibrary  extends AbstractHandler {\r
        \r
-       public static String IMPORTFUNCTIONLIBRARYPATH = "IMPORT_FUNCTION_LIBRARY_PATH";\r
-\r
        /**\r
         * Called from a functions folder node\r
         */\r
@@ -83,203 +61,28 @@ public class ImportFunctionLibrary  extends AbstractHandler {
                FileDialog fd = new FileDialog(shell, SWT.OPEN);\r
                fd.setText("Import Function Library");\r
                \r
-               String path = Activator.getDefault().getPreferenceStore().getString(IMPORTFUNCTIONLIBRARYPATH);\r
+               String path = Activator.getDefault().getPreferenceStore().getString(ImportUtils.IMPORTFUNCTIONLIBRARYPATH);\r
                if(path.isEmpty() || !(new File(path).exists()))\r
-                       path = Platform.getLocation().toOSString();\r
+                   path = Platform.getLocation().toOSString();\r
                fd.setFilterPath(path);\r
                String[] filterExt = {"*.tg"};\r
                fd.setFilterExtensions(filterExt);\r
-               String selected = fd.open();\r
+               final String selected = fd.open();\r
                if(selected == null) return null;\r
 \r
-               Activator.getDefault().getPreferenceStore().setValue(IMPORTFUNCTIONLIBRARYPATH, (new File(selected)).getParent());\r
-               \r
-               // Ensure that shared functions ontology exists\r
-               ensureSharedOntologies();\r
-               \r
-               // Handler for importing function libraries\r
-               HashMap<String, FormatHandler<Object>> handlers = new HashMap<String, FormatHandler<Object>>();\r
-               handlers.put("sysdynFunctionLibrary:1", new FormatHandler<Object>() {\r
-                       @Override\r
-                       public Binding getBinding() {\r
-                               return TransferableGraph1.BINDING;\r
-                       }\r
-\r
-                       @Override\r
-                       public Object process(DataContainer container) throws DataFormatException {\r
-                               SysdynFunctionLibraryImportAdvisor ia = new SysdynFunctionLibraryImportAdvisor(functionLibrary);\r
-                               try {\r
-                                       DefaultPasteHandler.defaultExecute((TransferableGraph1)container.content.getValue(), functionLibrary, ia);\r
-                                       return ia.getRoot();\r
-                               } catch (Exception e) {\r
-                                       e.printStackTrace();\r
-                                       return null;\r
-                               }\r
-                       }\r
-               });\r
-\r
-               // Read function library file\r
-               Object result = null;\r
-               try {\r
-                       File file = new File(selected);\r
-                       if(!file.isFile()) {\r
-                               displayErrorMessage(shell, "File " + selected + " not found");\r
-                               return null;\r
-                       } else {        \r
-                               result = DataContainers.readFile(file, handlers);\r
-                       }\r
-               } catch(DataFormatException e) {\r
-                       e.printStackTrace();\r
-               } catch(IOException e) {\r
-                       e.printStackTrace();\r
-               } catch(Exception e) {\r
-                       if(e instanceof RuntimeException)\r
-                               throw (RuntimeException)e;\r
-                       else\r
-                               throw new RuntimeException(e);\r
-               }\r
-               \r
-               if(result == null || !(result instanceof Resource)) {\r
-                       displayErrorMessage(shell, "Function library could not be imported.");\r
-               } else {\r
-                       final Resource FunctionLibraryRoot = (Resource) result;\r
-                       // Link the imported library to the selected resource (functionLibrary)\r
-                       SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
-                               /**\r
-                                * Link the imported library to the selected resource (functionLibrary)\r
-                                * The imported library can be either SysdynModelicaFunctionLibrary or SysdynFunctionOntology\r
-                                */\r
-                               @Override\r
-                               public void perform(WriteGraph graph) throws DatabaseException {\r
-                                       Layer0 l0 = Layer0.getInstance(graph);\r
-                                       // Case: SharedFunctionOntology. Link to SharedOntologies\r
-                                       if(graph.isInstanceOf(FunctionLibraryRoot, SysdynResource.getInstance(graph).SharedFunctionOntology)) {\r
-                                               Resource library = graph.getResource("http://SharedOntologies");\r
-                                               if(!graph.hasStatement(library, l0.ConsistsOf, FunctionLibraryRoot)) {\r
-                                                       graph.claim(library, l0.ConsistsOf, FunctionLibraryRoot);\r
-                                               }\r
+               Job job = new DatabaseJob("Import function") {\r
 \r
-                                               // Link model to the shared library\r
-                                               SysdynResource sr = SysdynResource.getInstance(graph);\r
-                                               Resource model = functionLibrary;\r
-                                               while(!graph.isInstanceOf(model, sr.SysdynModel) && graph.isInstanceOf(model, l0.Ontology))\r
-                                                       model = graph.getSingleObject(model, l0.PartOf);\r
-                                               if(graph.isInstanceOf(model, sr.SysdynModel)) {\r
-                                                       graph.claim(model, l0.IsLinkedTo, l0.IsLinkedTo_Inverse, FunctionLibraryRoot);\r
-                                               }\r
+                   @Override\r
+                   protected IStatus run(IProgressMonitor monitor) {\r
+                       IStatus status = ImportUtils.importFunctionLibrary(functionLibrary, selected, shell, monitor);\r
+                       return status;\r
+                   }\r
+               };\r
 \r
-                                               // Case: not SharedFunctionOntology or SysdynModelicaFunctionLibrary. \r
-                                       } else if(!graph.isInstanceOf(FunctionLibraryRoot, SysdynResource.getInstance(graph).SysdynModelicaFunctionLibrary)) {\r
-                                               Resource instanceOf = graph.getPossibleObject(FunctionLibraryRoot,l0.InstanceOf);\r
-                                               String type = "...";\r
-                                               if(instanceOf != null)\r
-                                                       type = NameUtils.getSafeName(graph, instanceOf);\r
-                                               else {\r
-                                                       Resource inheritedFrom = graph.getPossibleObject(FunctionLibraryRoot, l0.Inherits);\r
-                                                       if(inheritedFrom != null)\r
-                                                               type = NameUtils.getSafeName(graph, inheritedFrom);\r
-                                               }\r
-                                               final String ft = type; \r
+               job.setUser(true);\r
+               job.schedule();\r
 \r
-                                               // Remove the functionLibrary ConsistsOf root relation\r
-                                               graph.deny(FunctionLibraryRoot, l0.PartOf);\r
-\r
-                                               // Display error message\r
-                                               shell.getDisplay().asyncExec(new Runnable() {\r
-\r
-                                                       @Override\r
-                                                       public void run() {\r
-                                                               displayErrorMessage(shell, "The imported file is not of type: Function Library (" + ft +")");                                                   \r
-                                                       }\r
-                                               });\r
-                                       }\r
-\r
-                               }\r
-                       });\r
-               }\r
                return null;\r
        }\r
        \r
-       /**\r
-        * Import advisor for importing function libraries to SysDyn\r
-        * \r
-        * @author Teemu Lempinen\r
-        *\r
-        */\r
-       private class SysdynFunctionLibraryImportAdvisor extends DefaultPasteImportAdvisor {\r
-               \r
-               public SysdynFunctionLibraryImportAdvisor(Resource library) {\r
-                       super(library);\r
-               }\r
-               \r
-               @Override\r
-               public void analyzeType(ReadGraph graph, Root root) throws DatabaseException {\r
-                   // Change the library to http://SharedOntologies, if the imported library is of type SharedFunctionOntology\r
-                       if(root.type.equals(SysdynResource.URIs.SharedFunctionOntology)) {\r
-                               try {\r
-                                       library = graph.getResource("http://SharedOntologies");\r
-                               } catch (ResourceNotFoundException e) {\r
-                                       e.printStackTrace();\r
-                               }\r
-                       }\r
-               }\r
-               \r
-               @Override\r
-               public Resource createRoot(WriteOnlyGraph graph, Root root) throws DatabaseException {\r
-                       Layer0 l0 = graph.getService(Layer0.class);\r
-                       this.root = graph.newResource();\r
-                       graph.claim(library, l0.ConsistsOf, l0.PartOf, this.root);\r
-                       String name = root.name;\r
-                       String newName = nameMappings.get(name);\r
-                       graph.addLiteral(this.root, l0.HasName, l0.NameOf, l0.String, newName, Bindings.STRING);\r
-                       return this.root;\r
-\r
-               }\r
-                       \r
-       }\r
-       \r
-       private void ensureSharedOntologies() {\r
-               // Make sure the "http://SharedOntologies resource exists\r
-               try {\r
-                       Boolean hasSharedOntologies;\r
-                       hasSharedOntologies = SimanticsUI.getSession().syncRequest(new Read<Boolean>() {\r
-\r
-                               @Override\r
-                               public Boolean perform(ReadGraph graph) throws DatabaseException {\r
-                                       try {\r
-                                               graph.getResource("http://SharedOntologies");\r
-                                       } catch (ResourceNotFoundException e) {\r
-                                               return false;\r
-                                       }               \r
-                                       return true;\r
-                               }\r
-                       });\r
-\r
-                       if(!hasSharedOntologies) {\r
-                               SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
-\r
-                                       @Override\r
-                                       public void perform(WriteGraph graph) throws DatabaseException {\r
-                                               Layer0 l0 = Layer0.getInstance(graph);\r
-                                               GraphUtils.create2(graph, l0.Library, \r
-                                                               l0.HasName, "SharedOntologies",\r
-                                                               l0.PartOf, graph.getResource("http:/"));\r
-                                       }\r
-                               });\r
-\r
-                       }\r
-               } catch (DatabaseException e) {\r
-                       e.printStackTrace();\r
-               }\r
-\r
-       }\r
-       \r
-       private void displayErrorMessage(Shell shell, String message) {\r
-               MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ERROR);\r
-               mb.setText("Error");\r
-               mb.setMessage("The imported file is not of type: Model");\r
-               mb.open();\r
-       }\r
-\r
 }\r
index 99cbbeaa37b9e1da229a64d96497514e91046709..f08a7b76a3bb7dc90e325173084b8a1f49f7e8ff 100644 (file)
 package org.simantics.sysdyn.ui.handlers.imports;\r
 \r
 import java.io.File;\r
-import java.io.IOException;\r
-import java.util.ArrayList;\r
-import java.util.Collection;\r
-import java.util.Collections;\r
-import java.util.HashMap;\r
-import java.util.Map;\r
-import java.util.Set;\r
 \r
 import org.eclipse.core.commands.AbstractHandler;\r
 import org.eclipse.core.commands.ExecutionEvent;\r
@@ -26,50 +19,14 @@ import org.eclipse.core.commands.ExecutionException;
 import org.eclipse.core.runtime.IProgressMonitor;\r
 import org.eclipse.core.runtime.IStatus;\r
 import org.eclipse.core.runtime.Platform;\r
-import org.eclipse.core.runtime.Status;\r
-import org.eclipse.core.runtime.SubMonitor;\r
 import org.eclipse.core.runtime.jobs.Job;\r
 import org.eclipse.swt.SWT;\r
 import org.eclipse.swt.widgets.FileDialog;\r
 import org.eclipse.swt.widgets.Shell;\r
 import org.eclipse.ui.handlers.HandlerUtil;\r
 import org.simantics.DatabaseJob;\r
-import org.simantics.Simantics;\r
-import org.simantics.databoard.binding.Binding;\r
-import org.simantics.databoard.container.DataContainer;\r
-import org.simantics.databoard.container.DataContainers;\r
-import org.simantics.databoard.container.DataFormatException;\r
-import org.simantics.databoard.container.FormatHandler;\r
-import org.simantics.db.Issue;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.Session;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.ObjectsWithType;\r
-import org.simantics.db.common.request.WriteResultRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.adapter.impl.DefaultPasteHandler;\r
-import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;\r
-import org.simantics.db.layer0.migration.MigrationState;\r
-import org.simantics.db.layer0.migration.MigrationStateKeys;\r
-import org.simantics.db.layer0.migration.MigrationStep;\r
-import org.simantics.db.layer0.migration.MigrationUtils;\r
-import org.simantics.db.layer0.util.RemoverUtil;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.graph.representation.TransferableGraph1;\r
-import org.simantics.issues.common.AllBatchIssueSources;\r
-import org.simantics.issues.common.BatchIssueSource;\r
-import org.simantics.issues.ontology.IssueResource;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.modeling.utils.BatchValidations;\r
-import org.simantics.operation.Layer0X;\r
-import org.simantics.simulation.ontology.SimulationResource;\r
-import org.simantics.structural.stubs.StructuralResource2;\r
-import org.simantics.sysdyn.SysdynResource;\r
 import org.simantics.sysdyn.ui.Activator;\r
-import org.simantics.ui.SimanticsUI;\r
+import org.simantics.sysdyn.ui.utils.imports.ImportUtils;\r
 \r
 /**\r
  * Imports models from exported transferable graph files.\r
@@ -79,8 +36,6 @@ import org.simantics.ui.SimanticsUI;
  */\r
 public class ImportModelHandler extends AbstractHandler {\r
 \r
-    public static String IMPORTMODELTPATH = "IMPORT_MODEL_PATH";\r
-\r
     @Override\r
     public Object execute(ExecutionEvent event) throws ExecutionException {\r
 \r
@@ -89,7 +44,7 @@ public class ImportModelHandler extends AbstractHandler {
         FileDialog fd = new FileDialog(shell, SWT.OPEN);\r
         fd.setText("Import Model");\r
 \r
-        String path = Activator.getDefault().getPreferenceStore().getString(IMPORTMODELTPATH);\r
+        String path = Activator.getDefault().getPreferenceStore().getString(ImportUtils.IMPORTMODELTPATH);\r
         if(path.isEmpty() || !(new File(path).exists()))\r
             path = Platform.getLocation().toOSString();\r
         fd.setFilterPath(path);\r
@@ -102,7 +57,7 @@ public class ImportModelHandler extends AbstractHandler {
 \r
             @Override\r
             protected IStatus run(IProgressMonitor monitor) {\r
-                IStatus status = importFile(selected, shell, monitor);\r
+                IStatus status = ImportUtils.importModelFile(selected, shell, monitor);\r
                 return status;\r
             }\r
         };\r
@@ -112,289 +67,4 @@ public class ImportModelHandler extends AbstractHandler {
         return null;\r
 \r
     }\r
-\r
-    private IStatus importFile(String path, final Shell shell, final IProgressMonitor monitor) {\r
-        final Resource project = SimanticsUI.getProject().get();\r
-        if(project == null) return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import model: project not found", null);\r
-\r
-        monitor.beginTask("Import model", 7);\r
-        \r
-        Activator.getDefault().getPreferenceStore().setValue(IMPORTMODELTPATH, (new File(path)).getParent());\r
-\r
-\r
-\r
-        HashMap<String, FormatHandler<Object>> handlers = new HashMap<String, FormatHandler<Object>>();\r
-        handlers.put("sysdynModel:1", new FormatHandler<Object>() {\r
-            @Override\r
-            public Binding getBinding() {\r
-                return TransferableGraph1.BINDING;\r
-            }\r
-\r
-            @Override\r
-            public Object process(DataContainer container) throws DataFormatException {\r
-                DefaultPasteImportAdvisor ia = new DefaultPasteImportAdvisor(project);\r
-\r
-                try {\r
-                    monitor.subTask("Migrate");\r
-                    Session session = Simantics.getSession();\r
-                    TransferableGraph1 tg = (TransferableGraph1)container.content.getValue();\r
-\r
-                    MigrationStep step = MigrationUtils.getStep(session, SysdynResource.URIs.from1$6to1$7);\r
-                    MigrationState state = MigrationUtils.newState();\r
-                    state.setProperty(MigrationStateKeys.CURRENT_TG, tg);\r
-                    step.applyTo(session, state);\r
-                    tg = state.getProperty(MigrationStateKeys.CURRENT_TG);\r
-\r
-                    monitor.worked(1);\r
-                    monitor.subTask("Import");\r
-                    DefaultPasteHandler.defaultExecute(tg, project, ia);\r
-                    monitor.worked(1);\r
-                    return ia.getRoot();\r
-\r
-                } catch (DatabaseException e) {\r
-                    e.printStackTrace();\r
-                    return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import model failed", e);\r
-                } catch (Exception e) {\r
-                    e.printStackTrace();\r
-                    return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import model failed", e);\r
-                }\r
-            }\r
-        });\r
-\r
-        Object result = null;\r
-        try {\r
-            File file = new File(path);\r
-            if(!file.isFile()) {\r
-//                     displayErrorMessage(shell, "File " + path + " not found");\r
-                return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import model failed: File " + path + " not found", null);\r
-            } else {    \r
-                result = DataContainers.readFile(file, handlers);\r
-            }\r
-        } catch(DataFormatException e) {\r
-            e.printStackTrace();\r
-            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import model failed: Model could not be imported.", e);                 \r
-        } catch(IOException e) {\r
-            e.printStackTrace();\r
-            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import model failed: Model could not be imported.", e); \r
-        } catch(Exception e) {\r
-            if(e instanceof RuntimeException) {\r
-                return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import model failed: Model could not be imported.", e); \r
-//                     throw (RuntimeException)e;\r
-            } else {\r
-                return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import model failed: Model could not be imported.", e); \r
-//                     throw new RuntimeException(e);\r
-            }\r
-        }\r
-\r
-        if(result == null || !(result instanceof Resource)) {\r
-//                 displayErrorMessage(shell, "Model could not be imported.");\r
-            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import model failed: Model could not be imported.", null);\r
-        } else {\r
-            try {\r
-                final Resource ModelRoot = (Resource) result;\r
-                IStatus status = SimanticsUI.getSession().syncRequest(new WriteResultRequest<IStatus>()  {\r
-\r
-                    @Override\r
-                    public IStatus perform(WriteGraph graph) throws DatabaseException {\r
-                        if(!graph.isInstanceOf(ModelRoot, SysdynResource.getInstance(graph).SysdynModel)) {\r
-                            // Imported model was not a SysdynModel, display error message.\r
-                            Resource instanceOf = graph.getPossibleObject(ModelRoot, Layer0.getInstance(graph).InstanceOf);\r
-                            String type = "...";\r
-                            if(instanceOf != null)\r
-                                type = NameUtils.getSafeName(graph, instanceOf);\r
-                            else {\r
-                                Resource inheritedFrom = graph.getPossibleObject(ModelRoot, Layer0.getInstance(graph).Inherits);\r
-                                if(inheritedFrom != null)\r
-                                    type = NameUtils.getSafeName(graph, inheritedFrom);\r
-                            }\r
-                            final String ft = type; \r
-                            graph.deny(ModelRoot, Layer0.getInstance(graph).PartOf);\r
-\r
-//                                 shell.getDisplay().asyncExec(new Runnable() {\r
-//\r
-//                                     @Override\r
-//                                     public void run() {\r
-//                                         displayErrorMessage(shell, "The imported file is not of type: System Dynamics Model (" + ft +")");\r
-                            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "The imported file is not of type: System Dynamics Model (" + ft +")", null);\r
-//                                     }\r
-//                                 });\r
-\r
-                        } else {\r
-                            monitor.subTask("Add required dependencies");\r
-                            addDependencies(graph, ModelRoot);\r
-                            monitor.worked(1);\r
-                            monitor.subTask("Remove unnecessary issue sources");\r
-                            removeIssueSourcesFromModules(graph, ModelRoot);\r
-                            monitor.worked(1);\r
-                            monitor.subTask("Add enumeration issue source");\r
-                            addEnumerationIssueSource(graph, ModelRoot);\r
-                            monitor.worked(1);\r
-                            monitor.subTask("Activate model");\r
-                            activateModel(graph, ModelRoot);\r
-                            monitor.worked(1);\r
-                        }\r
-                        return null;\r
-\r
-                    }\r
-\r
-                });\r
-\r
-                if(status != null)\r
-                    return status;\r
-\r
-                monitor.subTask("Validate model");\r
-                Collection<Resource> confs = SimanticsUI.getSession().syncRequest(new Read<Collection<Resource>>() {\r
-\r
-                    @Override\r
-                    public Collection<Resource> perform(ReadGraph graph) throws DatabaseException {\r
-                        return findAllConfigurations(graph, ModelRoot);\r
-                    }\r
-\r
-                });\r
-\r
-\r
-                // Batch validate all issue sources after import\r
-                try {\r
-                    for(Resource conf : confs) {\r
-                        /*\r
-                         * This section is copied from BatchValidations.runAll. runAll did\r
-                         * not find module types to validate.\r
-                         */\r
-//                           BatchValidations.runAll(null, mod);\r
-\r
-                        final Session session = Simantics.getSession();\r
-                        final Collection<BatchIssueSource> validations = session.sync( new AllBatchIssueSources(ModelRoot) );\r
-                        SubMonitor progress = SubMonitor.convert(monitor, "Validate Model", 100);\r
-                        Collection<Resource> contexts = Collections.singletonList(conf);\r
-                        for(BatchIssueSource bis : validations) {\r
-                            Map<Resource, Set<Issue>> is = BatchValidations.validate(progress.newChild(90, SubMonitor.SUPPRESS_NONE), bis, contexts);\r
-                            BatchValidations.store(progress.newChild(10, SubMonitor.SUPPRESS_NONE), bis.getResource(), is);\r
-                        }\r
-                    }\r
-                } catch(Throwable t) {\r
-                    return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import model failed: Model could not be imported.", t);\r
-                } \r
-\r
-                monitor.worked(1);\r
-\r
-            } catch (DatabaseException e) {\r
-                e.printStackTrace();\r
-                return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import model failed: Model could not be imported.", e);\r
-            }\r
-\r
-            return Status.OK_STATUS;\r
-        }\r
-    }\r
-\r
-    protected void removeIssueSourcesFromModules(WriteGraph graph, Resource modelRoot) throws DatabaseException {\r
-        Layer0 L0 = Layer0.getInstance(graph);\r
-        IssueResource ISSUE = IssueResource.getInstance(graph);\r
-\r
-        for(Resource m : findAllModelsAndModules(graph, modelRoot)) {\r
-            if(m.equals(modelRoot))\r
-                continue;\r
-\r
-            // Module may contain issue sources due to legacy reasons. Remove these. \r
-            for(Resource issueSource : graph.syncRequest(new ObjectsWithType(m, L0.ConsistsOf, ISSUE.IssueSource))) {\r
-                // Issues are created to virtual graphs, so they should not need to be removed. Just in case they are created, remove them first\r
-                for(Resource issue : graph.getObjects(issueSource, ISSUE.IssueSource_Manages)) {\r
-                    RemoverUtil.remove(graph, issue);\r
-                }\r
-\r
-                // finally remove the issue source\r
-                RemoverUtil.remove(graph, issueSource);\r
-            }\r
-        }\r
-\r
-    }\r
-\r
-    protected void activateModel(WriteGraph graph, Resource modelRoot) throws DatabaseException {\r
-        Layer0 L0 = Layer0.getInstance(graph);\r
-        Layer0X L0X = Layer0X.getInstance(graph);\r
-        if(!graph.hasStatement(modelRoot, L0X.IsActivatedBy)) {\r
-            Resource project = graph.getPossibleObject(modelRoot, L0.PartOf);\r
-            if(project != null) {\r
-                graph.claim(modelRoot, L0X.IsActivatedBy, project);\r
-            }\r
-        }\r
-    }\r
-\r
-    protected void addDependencies(WriteGraph graph, Resource modelRoot) throws DatabaseException {\r
-        Layer0 L0 = Layer0.getInstance(graph);\r
-\r
-        ArrayList<String> links = new ArrayList<String>();\r
-        for(Resource link : graph.getObjects(modelRoot, L0.IsLinkedTo))\r
-            links.add(graph.getURI(link));\r
-\r
-\r
-        if(!links.contains("http://www.simantics.org/Documentation-1.1")) {\r
-            Resource documentation = graph.getPossibleResource("http://www.simantics.org/Documentation-1.1");\r
-            if(documentation != null)\r
-                graph.claim(modelRoot, L0.IsLinkedTo, documentation);\r
-        }\r
-\r
-        if(!links.contains("http://www.simantics.org/SelectionView-1.2")) {\r
-            Resource selectionView = graph.getPossibleResource("http://www.simantics.org/SelectionView-1.2");\r
-            if(selectionView != null)\r
-                graph.claim(modelRoot, L0.IsLinkedTo, selectionView);\r
-        }\r
-\r
-        if(!links.contains("http://www.simantics.org/DocumentWorkbench-1.0")) {\r
-            Resource documentWb = graph.getPossibleResource("http://www.simantics.org/DocumentWorkbench-1.0");\r
-            if(documentWb != null)\r
-                graph.claim(modelRoot, L0.IsLinkedTo, documentWb);\r
-        }\r
-    }\r
-\r
-    protected void addEnumerationIssueSource(WriteGraph graph, Resource modelRoot) throws DatabaseException {\r
-        Layer0 L0 = Layer0.getInstance(graph);\r
-        Layer0X L0X = Layer0X.getInstance(graph); \r
-        SysdynResource sr = SysdynResource.getInstance(graph);\r
-        Collection<Resource> enumerationIssueSources = graph.syncRequest(new ObjectsWithType(modelRoot, L0.ConsistsOf, sr.Validations_Enumerations_EnumerationIssueSource));\r
-        if(enumerationIssueSources.isEmpty()) {\r
-            GraphUtils.create2(graph,\r
-                    sr.Validations_Enumerations_EnumerationIssueSource,\r
-                    L0X.IsActivatedBy, modelRoot,\r
-                    L0.PartOf, modelRoot\r
-                    );  \r
-        }      }\r
-\r
-    private Collection<Resource> findAllConfigurations(ReadGraph graph, Resource modelRoot) throws DatabaseException {\r
-        SysdynResource sr = SysdynResource.getInstance(graph);\r
-        StructuralResource2 SR2 = StructuralResource2.getInstance(graph);\r
-        Collection<Resource> modulesAndModels = findAllModelsAndModules(graph, modelRoot);\r
-        Collection<Resource> configurations = new ArrayList<Resource>();\r
-\r
-        for(Resource r : modulesAndModels) {\r
-            if(graph.isInheritedFrom(r, sr.Module)) {\r
-                configurations.add(graph.getPossibleObject(r, SR2.IsDefinedBy));\r
-            } else if(graph.isInstanceOf(r, sr.SysdynModel)) {\r
-                configurations.add(graph.getPossibleObject(modelRoot, SimulationResource.getInstance(graph).HasConfiguration));\r
-            }\r
-        }\r
-\r
-        return configurations;\r
-    }\r
-\r
-    private Collection<Resource> findAllModelsAndModules(ReadGraph graph, Resource modelRoot) throws DatabaseException {\r
-        Layer0 L0 = Layer0.getInstance(graph);\r
-        SysdynResource sr = SysdynResource.getInstance(graph);\r
-        Collection<Resource> modelsAndModules = new ArrayList<Resource>();\r
-        modelsAndModules.add(modelRoot);\r
-\r
-        for(Resource r : graph.getObjects(modelRoot, L0.ConsistsOf)) {\r
-            if(graph.isInheritedFrom(r, sr.Module)) {\r
-                modelsAndModules.add(r);\r
-            }\r
-        }\r
-\r
-        return modelsAndModules;\r
-    }\r
-\r
-//     private void displayErrorMessage(Shell shell, String message) {\r
-//             MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ERROR);\r
-//             mb.setText("Error");\r
-//             mb.setMessage("The imported file is not of type: Model");\r
-//             mb.open();\r
-//     }\r
 }\r
index cf42242512b7b42a3bce196a002d8747ab9e965c..9b7f587761de38ae5ca859b7072909e178767ef6 100644 (file)
 package org.simantics.sysdyn.ui.handlers.imports;\r
 \r
 import java.io.File;\r
-import java.io.IOException;\r
-import java.util.HashMap;\r
 \r
 import org.eclipse.core.commands.AbstractHandler;\r
 import org.eclipse.core.commands.ExecutionEvent;\r
 import org.eclipse.core.commands.ExecutionException;\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
 import org.eclipse.core.runtime.Platform;\r
+import org.eclipse.core.runtime.jobs.Job;\r
 import org.eclipse.jface.viewers.ISelection;\r
 import org.eclipse.swt.SWT;\r
 import org.eclipse.swt.widgets.FileDialog;\r
-import org.eclipse.swt.widgets.MessageBox;\r
 import org.eclipse.swt.widgets.Shell;\r
 import org.eclipse.ui.handlers.HandlerUtil;\r
+import org.simantics.DatabaseJob;\r
 import org.simantics.browsing.ui.common.node.AbstractNode;\r
-import org.simantics.databoard.binding.Binding;\r
-import org.simantics.databoard.container.DataContainer;\r
-import org.simantics.databoard.container.DataContainers;\r
-import org.simantics.databoard.container.DataFormatException;\r
-import org.simantics.databoard.container.FormatHandler;\r
 import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.adapter.impl.DefaultPasteHandler;\r
-import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;\r
-import org.simantics.graph.representation.TransferableGraph1;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.sysdyn.SysdynResource;\r
 import org.simantics.sysdyn.ui.Activator;\r
-import org.simantics.ui.SimanticsUI;\r
-import org.simantics.ui.utils.AdaptionUtils;\r
+import org.simantics.sysdyn.ui.utils.imports.ImportUtils;\r
+import org.simantics.utils.ui.AdaptionUtils;\r
 \r
 /**\r
  * Imports modules from exported transferable graph files.\r
@@ -53,7 +40,6 @@ import org.simantics.ui.utils.AdaptionUtils;
  */\r
 public class ImportModuleHandler extends AbstractHandler {\r
 \r
-       public static String IMPORTMODULETPATH = "IMPORT_MODULE_PATH";\r
 \r
        @Override\r
        public Object execute(ExecutionEvent event) throws ExecutionException {\r
@@ -71,104 +57,27 @@ public class ImportModuleHandler extends AbstractHandler {
                FileDialog fd = new FileDialog(shell, SWT.OPEN);\r
                fd.setText("Import Module");\r
 \r
-               String path = Activator.getDefault().getPreferenceStore().getString(IMPORTMODULETPATH);\r
+               String path = Activator.getDefault().getPreferenceStore().getString(ImportUtils.IMPORTMODULETPATH);\r
                if(path.isEmpty() || !(new File(path).exists()))\r
                        path = Platform.getLocation().toOSString();\r
                fd.setFilterPath(path);\r
                String[] filterExt = {"*.tg"};\r
                fd.setFilterExtensions(filterExt);\r
-               String selected = fd.open();\r
+               final String selected = fd.open();\r
                if(selected == null) return null;\r
+               \r
+               Job job = new DatabaseJob("Import model") {\r
+\r
+            @Override\r
+            protected IStatus run(IProgressMonitor monitor) {\r
+                IStatus status = ImportUtils.importModuleFile(model, selected, shell, monitor);\r
+                return status;\r
+            }\r
+        };\r
+        job.setUser(true);\r
+        job.schedule();\r
 \r
-               Activator.getDefault().getPreferenceStore().setValue(IMPORTMODULETPATH, (new File(selected)).getParent());\r
-\r
-               // Handler for importing modules\r
-               HashMap<String, FormatHandler<Object>> handlers = new HashMap<String, FormatHandler<Object>>();\r
-               handlers.put("sysdynModule:1", new FormatHandler<Object>() {\r
-                       @Override\r
-                       public Binding getBinding() {\r
-                               return TransferableGraph1.BINDING;\r
-                       }\r
-\r
-                       @Override\r
-                       public Object process(DataContainer container) throws DataFormatException {\r
-                               DefaultPasteImportAdvisor ia = new DefaultPasteImportAdvisor(model);\r
-                               try {\r
-                                       DefaultPasteHandler.defaultExecute((TransferableGraph1)container.content.getValue(), model, ia);\r
-                                       return ia.getRoot();\r
-\r
-                               } catch (Exception e) {\r
-                                       e.printStackTrace();\r
-                                       return null;\r
-                               }\r
-                       }\r
-               });\r
-\r
-               // Read module file\r
-               Object result = null;\r
-               try {\r
-                       File file = new File(selected);\r
-                       if(!file.isFile()) {\r
-                               displayErrorMessage(shell, "File " + selected + " not found");\r
-                               return null;\r
-                       } else {        \r
-                               result = DataContainers.readFile(file, handlers);\r
-                       }\r
-               } catch(DataFormatException e) {\r
-                       e.printStackTrace();\r
-               } catch(IOException e) {\r
-                       e.printStackTrace();\r
-               } catch(Exception e) {\r
-                       if(e instanceof RuntimeException)\r
-                               throw (RuntimeException)e;\r
-                       else\r
-                               throw new RuntimeException(e);\r
-               }\r
-\r
-\r
-               if(result == null || !(result instanceof Resource)) {\r
-                       displayErrorMessage(shell, "Module could not be imported.");\r
-               } else {\r
-                       final Resource ModuleRoot = (Resource) result;\r
-                       // Check that the imported file actually was a module. Display error message otherwise.\r
-                       SimanticsUI.getSession().asyncRequest(new WriteRequest() {\r
-\r
-                               @Override\r
-                               public void perform(WriteGraph graph) throws DatabaseException {\r
-                                       if(!graph.isInheritedFrom(ModuleRoot, SysdynResource.getInstance(graph).Module)) {\r
-                                               Resource instanceOf = graph.getPossibleObject(ModuleRoot, Layer0.getInstance(graph).InstanceOf);\r
-                                               String type = "...";\r
-                                               if(instanceOf != null)\r
-                                                       type = NameUtils.getSafeName(graph, instanceOf);\r
-                                               else {\r
-                                                       Resource inheritedFrom = graph.getPossibleObject(ModuleRoot, Layer0.getInstance(graph).Inherits);\r
-                                                       if(inheritedFrom != null)\r
-                                                               type = NameUtils.getSafeName(graph, inheritedFrom);\r
-                                               }\r
-                                               final String ft = type; \r
-                                               graph.deny(ModuleRoot, Layer0.getInstance(graph).PartOf);\r
-\r
-                                               shell.getDisplay().asyncExec(new Runnable() {\r
-\r
-                                                       @Override\r
-                                                       public void run() {\r
-                                                               displayErrorMessage(shell, "The imported file is not of type: System Dynamics Module (" + ft +")");\r
-                                                       }\r
-                                               });\r
-                                       } \r
-                               }\r
-                       });\r
-\r
-               }\r
                return null;\r
        }\r
-\r
-\r
-       private void displayErrorMessage(Shell shell, String message) {\r
-               MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ERROR);\r
-               mb.setText("Error");\r
-               mb.setMessage("The imported file is not of type: Model");\r
-               mb.open();\r
-       }\r
-\r
+       \r
 }\r
diff --git a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/imports/ImportUtils.java b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/imports/ImportUtils.java
new file mode 100644 (file)
index 0000000..82416ea
--- /dev/null
@@ -0,0 +1,529 @@
+/*******************************************************************************\r
+ * Copyright (c) 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.utils.imports;\r
+\r
+import java.io.File;\r
+import java.io.IOException;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.Collections;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+import java.util.Set;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Status;\r
+import org.eclipse.core.runtime.SubMonitor;\r
+import org.eclipse.swt.widgets.Shell;\r
+import org.simantics.Simantics;\r
+import org.simantics.databoard.container.DataContainers;\r
+import org.simantics.databoard.container.DataFormatException;\r
+import org.simantics.databoard.container.FormatHandler;\r
+import org.simantics.db.Issue;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.common.request.WriteRequest;\r
+import org.simantics.db.common.request.WriteResultRequest;\r
+import org.simantics.db.common.utils.NameUtils;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.exception.ResourceNotFoundException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.issues.common.AllBatchIssueSources;\r
+import org.simantics.issues.common.BatchIssueSource;\r
+import org.simantics.issues.ontology.IssueResource;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.modeling.utils.BatchValidations;\r
+import org.simantics.operation.Layer0X;\r
+import org.simantics.simulation.ontology.SimulationResource;\r
+import org.simantics.structural.stubs.StructuralResource2;\r
+import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.Activator;\r
+import org.simantics.ui.SimanticsUI;\r
+\r
+/**\r
+ * Utilities for importing tg files: Models, Modules and Function libraries\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class ImportUtils {\r
+\r
+    public static String IMPORTMODELTPATH = "IMPORT_MODEL_PATH";\r
+    public static String IMPORTMODULETPATH = "IMPORT_MODULE_PATH";\r
+    public static String IMPORTFUNCTIONLIBRARYPATH = "IMPORT_FUNCTION_LIBRARY_PATH";\r
+\r
+    /**\r
+     * Null-checked begin task for monitor\r
+     * @param monitor\r
+     * @param taskName\r
+     * @param totalWork\r
+     */\r
+    private static void beginTask(IProgressMonitor monitor, String taskName, int totalWork) {\r
+        if(monitor != null)\r
+            monitor.beginTask(taskName, totalWork);\r
+    }\r
+    \r
+    /**\r
+     * Null-checked sub task for monitor\r
+     * @param monitor\r
+     * @param taskName\r
+     */\r
+    private static void subTask(IProgressMonitor monitor, String taskName) {\r
+        if(monitor != null)\r
+            monitor.subTask(taskName);\r
+    }\r
+    \r
+    /**\r
+     * Null-checked worked command for monitor\r
+     * @param monitor\r
+     * @param work\r
+     */\r
+    private static void worked(IProgressMonitor monitor, int work) {\r
+        if(monitor != null)\r
+            monitor.worked(work);\r
+    }\r
+\r
+\r
+    /**\r
+     * Read a file from hard drive using handlers \r
+     * @param path\r
+     * @param handlers\r
+     * @return IStatus if import failed, otherwise the result is determined by handlers\r
+     */\r
+    public static Object readFile(String path, HashMap<String, FormatHandler<Object>> handlers) {\r
+        Object result = null;\r
+        try {\r
+            File file = new File(path);\r
+            if(!file.isFile()) {\r
+                return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import failed: File " + path + " not found", null);\r
+            } else {    \r
+                result = DataContainers.readFile(file, handlers);\r
+            }\r
+        } catch(DataFormatException e) {\r
+            e.printStackTrace();\r
+            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import failed", e);              \r
+        } catch(IOException e) {\r
+            e.printStackTrace();\r
+            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import failed", e); \r
+        } catch(Exception e) {\r
+            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import failed", e); \r
+        }\r
+        return result;\r
+    }\r
+\r
+\r
+\r
+    /* ********************************* */\r
+    /* *******   IMPORT MODEL  ********* */\r
+    /* ********************************* */\r
+    public static IStatus importModelFile(String path, final Shell shell, final IProgressMonitor monitor) {\r
+        final Resource project = SimanticsUI.getProject().get();\r
+        if(project == null) return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import model: project not found", null);\r
+\r
+        beginTask(monitor, "Import model", 7);\r
+\r
+        Activator.getDefault().getPreferenceStore().setValue(IMPORTMODELTPATH, (new File(path)).getParent());\r
+\r
+\r
+\r
+        HashMap<String, FormatHandler<Object>> handlers = new HashMap<String, FormatHandler<Object>>();\r
+        handlers.put("sysdynModel:1", new SysdynImportFormatHandler(project, SysdynResource.URIs.from1$6to1$7, monitor));\r
+\r
+        Object result = ImportUtils.readFile(path, handlers);\r
+\r
+        if(result == null || !(result instanceof Resource)) {\r
+            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import model failed: Model could not be imported.", null);\r
+        } else {\r
+            try {\r
+                final Resource ModelRoot = (Resource) result;\r
+                IStatus status = SimanticsUI.getSession().syncRequest(new WriteResultRequest<IStatus>()  {\r
+\r
+                    @Override\r
+                    public IStatus perform(WriteGraph graph) throws DatabaseException {\r
+                        if(!graph.isInstanceOf(ModelRoot, SysdynResource.getInstance(graph).SysdynModel)) {\r
+                            // Imported model was not a SysdynModel, display error message.\r
+                            Resource instanceOf = graph.getPossibleObject(ModelRoot, Layer0.getInstance(graph).InstanceOf);\r
+                            String type = "...";\r
+                            if(instanceOf != null)\r
+                                type = NameUtils.getSafeName(graph, instanceOf);\r
+                            else {\r
+                                Resource inheritedFrom = graph.getPossibleObject(ModelRoot, Layer0.getInstance(graph).Inherits);\r
+                                if(inheritedFrom != null)\r
+                                    type = NameUtils.getSafeName(graph, inheritedFrom);\r
+                            }\r
+                            final String ft = type; \r
+                            graph.deny(ModelRoot, Layer0.getInstance(graph).PartOf);\r
+\r
+                            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "The imported file is not of type: System Dynamics Model (" + ft +")", null);\r
+                        } else {\r
+                            subTask(monitor, "Add required dependencies");\r
+                            addDependencies(graph, ModelRoot);\r
+                            worked(monitor, 1);\r
+                            subTask(monitor, "Remove unnecessary issue sources");\r
+                            removeIssueSourcesFromModules(graph, ModelRoot);\r
+                            worked(monitor, 1);\r
+                            subTask(monitor, "Add enumeration issue source");\r
+                            addEnumerationIssueSource(graph, ModelRoot);\r
+                            worked(monitor, 1);\r
+                            subTask(monitor, "Activate model");\r
+                            activateModel(graph, ModelRoot);\r
+                            worked(monitor, 1);\r
+                        }\r
+                        return null;\r
+\r
+                    }\r
+\r
+                });\r
+\r
+                if(status != null)\r
+                    return status;\r
+\r
+                subTask(monitor, "Validate model");\r
+                Collection<Resource> confs = SimanticsUI.getSession().syncRequest(new Read<Collection<Resource>>() {\r
+\r
+                    @Override\r
+                    public Collection<Resource> perform(ReadGraph graph) throws DatabaseException {\r
+                        return findAllConfigurations(graph, ModelRoot);\r
+                    }\r
+\r
+                });\r
+\r
+\r
+                // Batch validate all issue sources after import\r
+                try {\r
+                    for(Resource conf : confs) {\r
+                        /*\r
+                         * This section is copied from BatchValidations.runAll. runAll did\r
+                         * not find module types to validate.\r
+                         */\r
+//                        BatchValidations.runAll(null, mod);\r
+\r
+                        final Session session = Simantics.getSession();\r
+                        final Collection<BatchIssueSource> validations = session.sync( new AllBatchIssueSources(ModelRoot) );\r
+                        SubMonitor progress = null;\r
+                        if(monitor != null)\r
+                            progress = SubMonitor.convert(monitor, "Validate Model", 100);\r
+                        Collection<Resource> contexts = Collections.singletonList(conf);\r
+                        for(BatchIssueSource bis : validations) {\r
+                            Map<Resource, Set<Issue>> is = BatchValidations.validate(monitor != null ? progress.newChild(90, SubMonitor.SUPPRESS_NONE) : null, bis, contexts);\r
+                            BatchValidations.store(monitor != null ? progress.newChild(10, SubMonitor.SUPPRESS_NONE) : null, bis.getResource(), is);\r
+                        }\r
+                    }\r
+                } catch(Throwable t) {\r
+                    return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import model failed: Model could not be imported.", t);\r
+                } \r
+\r
+                worked(monitor, 1);\r
+\r
+            } catch (DatabaseException e) {\r
+                e.printStackTrace();\r
+                return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import model failed: Model could not be imported.", e);\r
+            }\r
+\r
+            return Status.OK_STATUS;\r
+        }\r
+    }\r
+\r
+    private static void removeIssueSourcesFromModules(WriteGraph graph, Resource modelRoot) throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        IssueResource ISSUE = IssueResource.getInstance(graph);\r
+\r
+        for(Resource m : findAllModelsAndModules(graph, modelRoot)) {\r
+            if(m.equals(modelRoot))\r
+                continue;\r
+\r
+            // Module may contain issue sources due to legacy reasons. Remove these. \r
+            for(Resource issueSource : graph.syncRequest(new ObjectsWithType(m, L0.ConsistsOf, ISSUE.IssueSource))) {\r
+                // Issues are created to virtual graphs, so they should not need to be removed. Just in case they are created, remove them first\r
+                for(Resource issue : graph.getObjects(issueSource, ISSUE.IssueSource_Manages)) {\r
+                    RemoverUtil.remove(graph, issue);\r
+                }\r
+\r
+                // finally remove the issue source\r
+                RemoverUtil.remove(graph, issueSource);\r
+            }\r
+        }\r
+\r
+    }\r
+\r
+    private static void activateModel(WriteGraph graph, Resource modelRoot) throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        Layer0X L0X = Layer0X.getInstance(graph);\r
+        if(!graph.hasStatement(modelRoot, L0X.IsActivatedBy)) {\r
+            Resource project = graph.getPossibleObject(modelRoot, L0.PartOf);\r
+            if(project != null) {\r
+                graph.claim(modelRoot, L0X.IsActivatedBy, project);\r
+            }\r
+        }\r
+    }\r
+\r
+    private static void addDependencies(WriteGraph graph, Resource modelRoot) throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+\r
+        ArrayList<String> links = new ArrayList<String>();\r
+        for(Resource link : graph.getObjects(modelRoot, L0.IsLinkedTo))\r
+            links.add(graph.getURI(link));\r
+\r
+\r
+        if(!links.contains("http://www.simantics.org/Documentation-1.1")) {\r
+            Resource documentation = graph.getPossibleResource("http://www.simantics.org/Documentation-1.1");\r
+            if(documentation != null)\r
+                graph.claim(modelRoot, L0.IsLinkedTo, documentation);\r
+        }\r
+\r
+        if(!links.contains("http://www.simantics.org/SelectionView-1.2")) {\r
+            Resource selectionView = graph.getPossibleResource("http://www.simantics.org/SelectionView-1.2");\r
+            if(selectionView != null)\r
+                graph.claim(modelRoot, L0.IsLinkedTo, selectionView);\r
+        }\r
+\r
+        if(!links.contains("http://www.simantics.org/DocumentWorkbench-1.0")) {\r
+            Resource documentWb = graph.getPossibleResource("http://www.simantics.org/DocumentWorkbench-1.0");\r
+            if(documentWb != null)\r
+                graph.claim(modelRoot, L0.IsLinkedTo, documentWb);\r
+        }\r
+    }\r
+\r
+    private static void addEnumerationIssueSource(WriteGraph graph, Resource modelRoot) throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        Layer0X L0X = Layer0X.getInstance(graph); \r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Collection<Resource> enumerationIssueSources = graph.syncRequest(new ObjectsWithType(modelRoot, L0.ConsistsOf, sr.Validations_Enumerations_EnumerationIssueSource));\r
+        if(enumerationIssueSources.isEmpty()) {\r
+            GraphUtils.create2(graph,\r
+                    sr.Validations_Enumerations_EnumerationIssueSource,\r
+                    L0X.IsActivatedBy, modelRoot,\r
+                    L0.PartOf, modelRoot\r
+                    );  \r
+        }   }\r
+\r
+    private static Collection<Resource> findAllConfigurations(ReadGraph graph, Resource modelRoot) throws DatabaseException {\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        StructuralResource2 SR2 = StructuralResource2.getInstance(graph);\r
+        Collection<Resource> modulesAndModels = findAllModelsAndModules(graph, modelRoot);\r
+        Collection<Resource> configurations = new ArrayList<Resource>();\r
+\r
+        for(Resource r : modulesAndModels) {\r
+            if(graph.isInheritedFrom(r, sr.Module)) {\r
+                configurations.add(graph.getPossibleObject(r, SR2.IsDefinedBy));\r
+            } else if(graph.isInstanceOf(r, sr.SysdynModel)) {\r
+                configurations.add(graph.getPossibleObject(modelRoot, SimulationResource.getInstance(graph).HasConfiguration));\r
+            }\r
+        }\r
+\r
+        return configurations;\r
+    }\r
+\r
+    private static Collection<Resource> findAllModelsAndModules(ReadGraph graph, Resource modelRoot) throws DatabaseException {\r
+        Layer0 L0 = Layer0.getInstance(graph);\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        Collection<Resource> modelsAndModules = new ArrayList<Resource>();\r
+        modelsAndModules.add(modelRoot);\r
+\r
+        for(Resource r : graph.getObjects(modelRoot, L0.ConsistsOf)) {\r
+            if(graph.isInheritedFrom(r, sr.Module)) {\r
+                modelsAndModules.add(r);\r
+            }\r
+        }\r
+\r
+        return modelsAndModules;\r
+    }\r
+\r
+    /* ********************************* */\r
+    /* *******  IMPORT MODULE  ********* */\r
+    /* ********************************* */\r
+    public static IStatus importModuleFile(final Resource model, String path, final Shell shell, final IProgressMonitor monitor) {\r
+        beginTask(monitor, "Import Module", 3);\r
+\r
+\r
+        Activator.getDefault().getPreferenceStore().setValue(IMPORTMODULETPATH, (new File(path)).getParent());\r
+\r
+        // Handler for importing modules\r
+        HashMap<String, FormatHandler<Object>> handlers = new HashMap<String, FormatHandler<Object>>();\r
+        handlers.put("sysdynModule:1", new SysdynImportFormatHandler(model, SysdynResource.URIs.from1$6to1$7, monitor));\r
+\r
+        // Read module file\r
+        Object result = ImportUtils.readFile(path, handlers);\r
+\r
+\r
+        if(result == null || !(result instanceof Resource)) {\r
+            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import module failed: Module could not be imported.", null);\r
+        } else {\r
+            final Resource ModuleRoot = (Resource) result;\r
+            // Check that the imported file actually was a module. Display error message otherwise.\r
+            try {\r
+                subTask(monitor, "Validate model");\r
+                IStatus status = SimanticsUI.getSession().syncRequest(new WriteResultRequest<IStatus>()  {\r
+\r
+                    @Override\r
+                    public IStatus perform(WriteGraph graph) throws DatabaseException {\r
+                        if(!graph.isInheritedFrom(ModuleRoot, SysdynResource.getInstance(graph).Module)) {\r
+                            Resource instanceOf = graph.getPossibleObject(ModuleRoot, Layer0.getInstance(graph).InstanceOf);\r
+                            String type = "...";\r
+                            if(instanceOf != null)\r
+                                type = NameUtils.getSafeName(graph, instanceOf);\r
+                            else {\r
+                                Resource inheritedFrom = graph.getPossibleObject(ModuleRoot, Layer0.getInstance(graph).Inherits);\r
+                                if(inheritedFrom != null)\r
+                                    type = NameUtils.getSafeName(graph, inheritedFrom);\r
+                            }\r
+                            final String ft = type; \r
+                            graph.deny(ModuleRoot, Layer0.getInstance(graph).PartOf);\r
+\r
+                            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "The imported file is not of type: System Dynamics Module (" + ft +")", null);\r
+                        } \r
+                        return null;\r
+                    }\r
+                });\r
+\r
+                if(status != null)\r
+                    return status;\r
+                worked(monitor, 1);\r
+            } catch (DatabaseException e) {\r
+                e.printStackTrace();\r
+            }\r
+\r
+        }\r
+\r
+        return Status.OK_STATUS;\r
+    }\r
+\r
+\r
+\r
+    /* ********************************* */\r
+    /* ***  IMPORT FUNCTION LIBRARY  *** */\r
+    /* ********************************* */\r
+\r
+    public static IStatus importFunctionLibrary(final Resource functionLibrary, final String path, final Shell shell, final IProgressMonitor monitor) {\r
+        beginTask(monitor, "Import Module", 3);\r
+\r
+        Activator.getDefault().getPreferenceStore().setValue(IMPORTFUNCTIONLIBRARYPATH, (new File(path)).getParent());\r
+\r
+        // Ensure that shared functions ontology exists\r
+        ensureSharedOntologies();\r
+\r
+        // Handler for importing function libraries\r
+        HashMap<String, FormatHandler<Object>> handlers = new HashMap<String, FormatHandler<Object>>();\r
+        handlers.put("sysdynFunctionLibrary:1", new SysdynImportFormatHandler(functionLibrary, SysdynResource.URIs.from1$6to1$7, monitor, new SysdynFunctionLibraryImportAdvisor(functionLibrary)));\r
+\r
+        // Read function library file\r
+        Object result = ImportUtils.readFile(path, handlers);\r
+\r
+        if(result == null || !(result instanceof Resource)) {\r
+            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import Function library failed: Function library not be imported.", null);\r
+        } else {\r
+            final Resource FunctionLibraryRoot = (Resource) result;\r
+            // Link the imported library to the selected resource (functionLibrary)\r
+            try {\r
+                subTask(monitor, "Validate model");\r
+                IStatus status = SimanticsUI.getSession().syncRequest(new WriteResultRequest<IStatus>()  {\r
+\r
+                    /**\r
+                     * Link the imported library to the selected resource (functionLibrary)\r
+                     * The imported library can be either SysdynModelicaFunctionLibrary or SysdynFunctionOntology\r
+                     */\r
+                    @Override\r
+                    public IStatus perform(WriteGraph graph) throws DatabaseException {\r
+                        Layer0 l0 = Layer0.getInstance(graph);\r
+                        // Case: SharedFunctionOntology. Link to SharedOntologies\r
+                        if(graph.isInstanceOf(FunctionLibraryRoot, SysdynResource.getInstance(graph).SharedFunctionOntology)) {\r
+                            Resource library = graph.getResource("http://SharedOntologies");\r
+                            if(!graph.hasStatement(library, l0.ConsistsOf, FunctionLibraryRoot)) {\r
+                                graph.claim(library, l0.ConsistsOf, FunctionLibraryRoot);\r
+                            }\r
+\r
+                            // Link model to the shared library\r
+                            SysdynResource sr = SysdynResource.getInstance(graph);\r
+                            Resource model = functionLibrary;\r
+                            while(!graph.isInstanceOf(model, sr.SysdynModel) && graph.isInstanceOf(model, l0.Ontology))\r
+                                model = graph.getSingleObject(model, l0.PartOf);\r
+                            if(graph.isInstanceOf(model, sr.SysdynModel)) {\r
+                                graph.claim(model, l0.IsLinkedTo, l0.IsLinkedTo_Inverse, FunctionLibraryRoot);\r
+                            }\r
+\r
+                            // Case: not SharedFunctionOntology or SysdynModelicaFunctionLibrary. \r
+                        } else if(!graph.isInstanceOf(FunctionLibraryRoot, SysdynResource.getInstance(graph).SysdynModelicaFunctionLibrary)) {\r
+                            Resource instanceOf = graph.getPossibleObject(FunctionLibraryRoot,l0.InstanceOf);\r
+                            String type = "...";\r
+                            if(instanceOf != null)\r
+                                type = NameUtils.getSafeName(graph, instanceOf);\r
+                            else {\r
+                                Resource inheritedFrom = graph.getPossibleObject(FunctionLibraryRoot, l0.Inherits);\r
+                                if(inheritedFrom != null)\r
+                                    type = NameUtils.getSafeName(graph, inheritedFrom);\r
+                            }\r
+                            final String ft = type; \r
+\r
+                            // Remove the functionLibrary ConsistsOf root relation\r
+                            graph.deny(FunctionLibraryRoot, l0.PartOf);\r
+\r
+                            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "The imported file is not of type: Function Library (" + ft +")", null);\r
+                        }\r
+                        return null;\r
+\r
+\r
+                    }\r
+                });\r
+\r
+                if(status != null)\r
+                    return status;\r
+                worked(monitor, 1);\r
+\r
+            } catch (DatabaseException e) {\r
+                e.printStackTrace();\r
+            }\r
+        }\r
+\r
+        return Status.OK_STATUS;\r
+    }\r
+\r
+    private static void ensureSharedOntologies() {\r
+        // Make sure the "http://SharedOntologies resource exists\r
+        try {\r
+            Boolean hasSharedOntologies;\r
+            hasSharedOntologies = SimanticsUI.getSession().syncRequest(new Read<Boolean>() {\r
+\r
+                @Override\r
+                public Boolean perform(ReadGraph graph) throws DatabaseException {\r
+                    try {\r
+                        graph.getResource("http://SharedOntologies");\r
+                    } catch (ResourceNotFoundException e) {\r
+                        return false;\r
+                    }       \r
+                    return true;\r
+                }\r
+            });\r
+\r
+            if(!hasSharedOntologies) {\r
+                SimanticsUI.getSession().syncRequest(new WriteRequest() {\r
+\r
+                    @Override\r
+                    public void perform(WriteGraph graph) throws DatabaseException {\r
+                        Layer0 l0 = Layer0.getInstance(graph);\r
+                        GraphUtils.create2(graph, l0.Library, \r
+                                l0.HasName, "SharedOntologies",\r
+                                l0.PartOf, graph.getResource("http:/"));\r
+                    }\r
+                });\r
+\r
+            }\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/imports/SysdynFunctionLibraryImportAdvisor.java b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/imports/SysdynFunctionLibraryImportAdvisor.java
new file mode 100644 (file)
index 0000000..b23385a
--- /dev/null
@@ -0,0 +1,61 @@
+/*******************************************************************************\r
+ * Copyright (c) 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.utils.imports;\r
+\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteOnlyGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.exception.ResourceNotFoundException;\r
+import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;\r
+import org.simantics.graph.representation.Root;\r
+import org.simantics.layer0.Layer0;\r
+import org.simantics.sysdyn.SysdynResource;\r
+\r
+/**\r
+ * Import advisor for importing function libraries to SysDyn\r
+ * \r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SysdynFunctionLibraryImportAdvisor extends DefaultPasteImportAdvisor {\r
+    \r
+    public SysdynFunctionLibraryImportAdvisor(Resource library) {\r
+        super(library);\r
+    }\r
+    \r
+    @Override\r
+    public void analyzeType(ReadGraph graph, Root root) throws DatabaseException {\r
+        // Change the library to http://SharedOntologies, if the imported library is of type SharedFunctionOntology\r
+        if(root.type.equals(SysdynResource.URIs.SharedFunctionOntology)) {\r
+            try {\r
+                library = graph.getResource("http://SharedOntologies");\r
+            } catch (ResourceNotFoundException e) {\r
+                e.printStackTrace();\r
+            }\r
+        }\r
+    }\r
+    \r
+    @Override\r
+    public Resource createRoot(WriteOnlyGraph graph, Root root) throws DatabaseException {\r
+        Layer0 l0 = graph.getService(Layer0.class);\r
+        this.root = graph.newResource();\r
+        graph.claim(library, l0.ConsistsOf, l0.PartOf, this.root);\r
+        String name = root.name;\r
+        String newName = nameMappings.get(name);\r
+        graph.addLiteral(this.root, l0.HasName, l0.NameOf, l0.String, newName, Bindings.STRING);\r
+        return this.root;\r
+\r
+    }\r
+        \r
+}
\ No newline at end of file
diff --git a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/imports/SysdynImportFormatHandler.java b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/utils/imports/SysdynImportFormatHandler.java
new file mode 100644 (file)
index 0000000..05d0271
--- /dev/null
@@ -0,0 +1,107 @@
+/*******************************************************************************\r
+ * Copyright (c) 2012 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.utils.imports;\r
+\r
+import org.eclipse.core.runtime.IProgressMonitor;\r
+import org.eclipse.core.runtime.IStatus;\r
+import org.eclipse.core.runtime.Status;\r
+import org.simantics.Simantics;\r
+import org.simantics.databoard.binding.Binding;\r
+import org.simantics.databoard.container.DataContainer;\r
+import org.simantics.databoard.container.DataFormatException;\r
+import org.simantics.databoard.container.FormatHandler;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.Session;\r
+import org.simantics.db.layer0.adapter.impl.DefaultPasteHandler;\r
+import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;\r
+import org.simantics.db.layer0.migration.MigrationState;\r
+import org.simantics.db.layer0.migration.MigrationStateKeys;\r
+import org.simantics.db.layer0.migration.MigrationStep;\r
+import org.simantics.db.layer0.migration.MigrationUtils;\r
+import org.simantics.graph.representation.TransferableGraph1;\r
+import org.simantics.sysdyn.ui.Activator;\r
+\r
+/**\r
+ * Handler for migrating a tg and importing it to database\r
+ * @author Teemu Lempinen\r
+ *\r
+ */\r
+public class SysdynImportFormatHandler implements FormatHandler<Object> {\r
+    \r
+    private Resource parent;\r
+    private IProgressMonitor monitor;\r
+    private String migrationURI;\r
+    private DefaultPasteImportAdvisor importAdvisor;\r
+    \r
+    /**\r
+     * Works 2 (2 * 1) in the monitor\r
+     * @param parent\r
+     * @param migrationURI\r
+     * @param monitor\r
+     */\r
+    public SysdynImportFormatHandler(Resource parent, String migrationURI, IProgressMonitor monitor) {\r
+        this(parent, migrationURI, monitor, null);\r
+    }\r
+    \r
+    public SysdynImportFormatHandler(Resource parent, String migrationURI, IProgressMonitor monitor,\r
+            DefaultPasteImportAdvisor importAdvisor) {\r
+        assert(parent != null);\r
+        assert(migrationURI != null);\r
+        this.parent = parent;\r
+        this.monitor = monitor;\r
+        this.migrationURI = migrationURI;\r
+        this.importAdvisor = importAdvisor;\r
+    }\r
+\r
+    private void subTask(String taskName) {\r
+        if(monitor != null)\r
+            monitor.subTask(taskName);\r
+    }\r
+    \r
+    private void worked(int work) {\r
+        if(monitor != null)\r
+            monitor.worked(work);\r
+    }\r
+    \r
+    @Override\r
+    public Binding getBinding() {\r
+        return TransferableGraph1.BINDING;\r
+    }\r
+\r
+    @Override\r
+    public Object process(DataContainer container) throws DataFormatException {\r
+        DefaultPasteImportAdvisor ia = importAdvisor != null ? importAdvisor : new DefaultPasteImportAdvisor(parent);\r
+        try {\r
+            subTask("Migrate");\r
+            Session session = Simantics.getSession();\r
+            TransferableGraph1 tg = (TransferableGraph1)container.content.getValue();\r
+\r
+            MigrationStep step = MigrationUtils.getStep(session, migrationURI);\r
+            MigrationState state = MigrationUtils.newState();\r
+            state.setProperty(MigrationStateKeys.CURRENT_TG, tg);\r
+            step.applyTo(session, state);\r
+            tg = state.getProperty(MigrationStateKeys.CURRENT_TG);\r
+\r
+            worked(1);\r
+            subTask("Import");\r
+            \r
+            DefaultPasteHandler.defaultExecute(tg, parent, ia);\r
+            worked(1);\r
+            \r
+            return ia.getRoot();\r
+\r
+        } catch (Exception e) {\r
+            return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Import module failed", e);\r
+        }\r
+    }\r
+\r
+}\r
index ee679124cd6da56c7f1fdc695145d62e12f5ef01..ee210702f23e2a94a7259fc5f65d736656c8b80a 100644 (file)
@@ -1,9 +1,10 @@
 package org.simantics.sysdyn.ui.wizards.functions;\r
 \r
 import java.io.File;\r
-import java.io.IOException;\r
 \r
+import org.eclipse.core.runtime.IStatus;\r
 import org.eclipse.core.runtime.Path;\r
+import org.eclipse.core.runtime.Status;\r
 import org.eclipse.jface.layout.GridDataFactory;\r
 import org.eclipse.jface.layout.PixelConverter;\r
 import org.eclipse.jface.viewers.ISelection;\r
@@ -27,25 +28,12 @@ import org.eclipse.swt.widgets.Text;
 import org.eclipse.swt.widgets.Tree;\r
 import org.simantics.browsing.ui.swt.AdaptableHintContext;\r
 import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.databoard.Files;\r
-import org.simantics.databoard.binding.error.RuntimeBindingConstructionException;\r
 import org.simantics.db.ReadGraph;\r
 import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.WriteOnlyGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
 import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.exception.ResourceNotFoundException;\r
-import org.simantics.db.layer0.adapter.impl.DefaultPasteHandler;\r
-import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;\r
 import org.simantics.db.request.Read;\r
-import org.simantics.graph.representation.Root;\r
-import org.simantics.graph.representation.TransferableGraph1;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
 import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.utils.imports.ImportUtils;\r
 import org.simantics.ui.SimanticsUI;\r
 import org.simantics.utils.datastructures.ArrayMap;\r
 \r
@@ -68,8 +56,6 @@ public class WizardFunctionsImportPage extends WizardPage{
 \r
        GraphExplorerComposite functionLibraryExplorer;\r
        \r
-       private String error = "";\r
-       \r
        private boolean selectionMade = false;\r
        \r
        /**\r
@@ -294,7 +280,10 @@ public class WizardFunctionsImportPage extends WizardPage{
                        setErrorMessage("No file selected");\r
                        return false;\r
                }\r
+               \r
+               IStatus status = ImportUtils.importFunctionLibrary(selectedModel, selected, shell, null);\r
 \r
+               /*\r
                TransferableGraph1 tg = null;\r
                try {\r
                        tg = (TransferableGraph1)Files.readFile(new File(selected), Bindings.getBindingUnchecked(TransferableGraph1.class));\r
@@ -396,9 +385,15 @@ public class WizardFunctionsImportPage extends WizardPage{
                        setErrorMessage("The imported file is not of type: Function Library (" + error +")");\r
                        error = "";\r
                        return false;\r
+               }\r
+                */\r
+               if(status == null || !status.equals(Status.OK_STATUS)) {\r
+                   setErrorMessage(status.getMessage());\r
+                   return false;\r
                }\r
                return true;\r
        }\r
+       /*\r
 \r
        private class SysdynFunctionLibraryImportAdvisor extends DefaultPasteImportAdvisor {\r
 \r
@@ -430,6 +425,8 @@ public class WizardFunctionsImportPage extends WizardPage{
                }\r
 \r
        }\r
+       */\r
+       \r
        void validatePage() {\r
 \r
                if (previouslyBrowsedFile.isEmpty() || selectionMade == false){\r
index 6de98d7a0fc1e037a39311af47773e2a3cbc131d..3f041ee5841956626ca0897e79938eec50caa32f 100644 (file)
@@ -1,11 +1,10 @@
 package org.simantics.sysdyn.ui.wizards.models;\r
 \r
 import java.io.File;\r
-import java.io.IOException;\r
-import java.util.HashSet;\r
-import java.util.UUID;\r
 \r
+import org.eclipse.core.runtime.IStatus;\r
 import org.eclipse.core.runtime.Platform;\r
+import org.eclipse.core.runtime.Status;\r
 import org.eclipse.jface.layout.PixelConverter;\r
 import org.eclipse.jface.viewers.IStructuredSelection;\r
 import org.eclipse.jface.wizard.WizardPage;\r
@@ -22,29 +21,10 @@ import org.eclipse.swt.widgets.FileDialog;
 import org.eclipse.swt.widgets.Label;\r
 import org.eclipse.swt.widgets.Shell;\r
 import org.eclipse.swt.widgets.Text;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.databoard.Files;\r
-import org.simantics.databoard.binding.error.RuntimeBindingConstructionException;\r
 import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.ObjectsWithType;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
 import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.adapter.impl.DefaultPasteHandler;\r
-import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;\r
-import org.simantics.graph.representation.TransferableGraph1;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.layer0.utils.direct.GraphUtils;\r
-import org.simantics.modeling.ModelingResources;\r
-import org.simantics.operation.Layer0X;\r
-import org.simantics.simulation.ontology.SimulationResource;\r
-import org.simantics.spreadsheet.resource.SpreadsheetResource;\r
-import org.simantics.structural.stubs.StructuralResource2;\r
-import org.simantics.sysdyn.SysdynResource;\r
 import org.simantics.sysdyn.ui.Activator;\r
-import org.simantics.sysdyn.ui.handlers.imports.ImportModelHandler;\r
-import org.simantics.sysdyn.ui.utils.OldTransferableGraph1;\r
+import org.simantics.sysdyn.ui.utils.imports.ImportUtils;\r
 import org.simantics.ui.SimanticsUI;\r
 \r
 public class WizardModelsImportPage extends WizardPage{\r
@@ -59,8 +39,6 @@ public class WizardModelsImportPage extends WizardPage{
 \r
        private Shell shell;\r
        \r
-       private String error = "";\r
-       \r
        /**\r
         * Creates a new project creation wizard page.\r
         * \r
@@ -182,7 +160,7 @@ public class WizardModelsImportPage extends WizardPage{
                \r
                dialog.setText("Import Model");\r
 \r
-               String path = Activator.getDefault().getPreferenceStore().getString(ImportModelHandler.IMPORTMODELTPATH);\r
+               String path = Activator.getDefault().getPreferenceStore().getString(ImportUtils.IMPORTMODELTPATH);\r
                if(path.isEmpty() || !(new File(path).exists()))\r
                        path = Platform.getLocation().toOSString();\r
                dialog.setFilterPath(path);\r
@@ -204,12 +182,15 @@ public class WizardModelsImportPage extends WizardPage{
                        return false;\r
                }\r
                \r
-               String selected = previouslyBrowsedFile;\r
+               final String selected = previouslyBrowsedFile;\r
                if(selected == null){\r
                        setErrorMessage("No file selected");\r
                        return false;\r
                }\r
                \r
+               IStatus status = ImportUtils.importModelFile(selected, shell, null);\r
+               \r
+        /*\r
                TransferableGraph1 tg = null;\r
                try {\r
                        tg = (TransferableGraph1)Files.readFile(new File(selected), Bindings.getBindingUnchecked(TransferableGraph1.class));\r
@@ -269,12 +250,17 @@ public class WizardModelsImportPage extends WizardPage{
                } catch (Exception e) {\r
                        e.printStackTrace();\r
                }\r
-\r
+    \r
                if (!error.isEmpty()){\r
                        setErrorMessage("The imported file is not of type: System Dynamics Model (" + error +")");\r
                        error = "";\r
                        return false;\r
                }\r
+               */\r
+               if(status == null || !status.equals(Status.OK_STATUS)) {\r
+                   setErrorMessage(status.getMessage());\r
+                   return false;\r
+               }\r
                return true;            \r
        }\r
        \r
@@ -283,6 +269,7 @@ public class WizardModelsImportPage extends WizardPage{
         * @param graph WriteGraph\r
         * @param model Imported model\r
         */\r
+       /*\r
        private static void updateOldConfigurationToBaseRealization(WriteGraph graph, Resource model) {\r
                Layer0X L0X = Layer0X.getInstance(graph);\r
                try {\r
@@ -294,6 +281,7 @@ public class WizardModelsImportPage extends WizardPage{
                }\r
                \r
        }\r
+       */\r
        \r
        /**\r
         * Links should be exported and imported automatically. If it has failed, the \r
@@ -302,7 +290,7 @@ public class WizardModelsImportPage extends WizardPage{
         * @param graph WriteGraph\r
         * @param model Imported model\r
         */\r
-        \r
+        /*\r
        private static void addDefaultOntologyLinks(WriteGraph graph, Resource model) {\r
                try {\r
                        Layer0 l0 = Layer0.getInstance(graph);\r
@@ -353,7 +341,7 @@ public class WizardModelsImportPage extends WizardPage{
                        e.printStackTrace();\r
                }\r
        }\r
-       \r
+*/     \r
        \r
        /**\r
         * Add a missing spreadsheet book to the model\r
@@ -361,6 +349,7 @@ public class WizardModelsImportPage extends WizardPage{
         * @param graph\r
         * @param model\r
         */\r
+       /*\r
        private static void addSpreadSheetBook(WriteGraph graph, Resource model) {\r
            try {\r
                Layer0 l0 = Layer0.getInstance(graph);\r
@@ -379,7 +368,7 @@ public class WizardModelsImportPage extends WizardPage{
                e.printStackTrace();\r
            }\r
        }\r
-       \r
+       */\r
        /**\r
         * Create a sheet (Copied from SysdynProject)\r
         * \r
@@ -391,6 +380,7 @@ public class WizardModelsImportPage extends WizardPage{
         * @return\r
         * @throws DatabaseException\r
         */\r
+       /*\r
     private static Resource createSheet(WriteGraph graph, Resource book, String name, String[] colNames, int[] colWidths) throws DatabaseException {\r
 \r
         Layer0 L0 = Layer0.getInstance(graph);\r
@@ -443,7 +433,7 @@ public class WizardModelsImportPage extends WizardPage{
         return result;\r
 \r
     }\r
-    \r
+    */\r
     void validatePage(){\r
        \r
                if (previouslyBrowsedFile.isEmpty()){\r
index 9ec3377de95c9f9bf43fe7234241a81fd3890522..9c08c02e780cdb42e933e0ec29e83ca9cf97331f 100644 (file)
@@ -1,9 +1,10 @@
 package org.simantics.sysdyn.ui.wizards.modules;\r
 \r
 import java.io.File;\r
-import java.io.IOException;\r
 \r
+import org.eclipse.core.runtime.IStatus;\r
 import org.eclipse.core.runtime.Path;\r
+import org.eclipse.core.runtime.Status;\r
 import org.eclipse.jface.layout.GridDataFactory;\r
 import org.eclipse.jface.layout.PixelConverter;\r
 import org.eclipse.jface.viewers.ISelection;\r
@@ -27,22 +28,12 @@ import org.eclipse.swt.widgets.Text;
 import org.eclipse.swt.widgets.Tree;\r
 import org.simantics.browsing.ui.swt.AdaptableHintContext;\r
 import org.simantics.browsing.ui.swt.widgets.GraphExplorerComposite;\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.databoard.Files;\r
-import org.simantics.databoard.binding.error.RuntimeBindingConstructionException;\r
 import org.simantics.db.ReadGraph;\r
 import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.common.request.WriteRequest;\r
-import org.simantics.db.common.utils.NameUtils;\r
 import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.layer0.adapter.impl.DefaultPasteHandler;\r
-import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;\r
 import org.simantics.db.request.Read;\r
-import org.simantics.graph.db.MissingDependencyException;\r
-import org.simantics.graph.representation.TransferableGraph1;\r
-import org.simantics.layer0.Layer0;\r
 import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.utils.imports.ImportUtils;\r
 import org.simantics.ui.SimanticsUI;\r
 import org.simantics.utils.datastructures.ArrayMap;\r
 \r
@@ -71,8 +62,6 @@ public class WizardModulesImportPage extends WizardPage{
        \r
        private boolean selectionMade = false;\r
        \r
-       private String error = "";\r
-       \r
        /**\r
         * Creates a new project creation wizard page.\r
         * \r
@@ -294,6 +283,9 @@ public class WizardModulesImportPage extends WizardPage{
                        return false;\r
                }\r
                \r
+               IStatus status = ImportUtils.importModuleFile(selectedModel, selected, shell, null);\r
+               \r
+               /*\r
                TransferableGraph1 tg = null;\r
                try {\r
                        tg = (TransferableGraph1)Files.readFile(new File(selected), Bindings.getBindingUnchecked(TransferableGraph1.class));\r
@@ -349,6 +341,12 @@ public class WizardModulesImportPage extends WizardPage{
                        error = "";\r
                        return false;\r
                }\r
+               */\r
+               if(status == null || !status.equals(Status.OK_STATUS)) {\r
+                   setErrorMessage(status.getMessage());\r
+                   return false;\r
+               }\r
+\r
                return true;\r
        }\r
        \r