]> gerrit.simantics Code Review - simantics/platform.git/blobdiff - bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/migration/MigrationUtils.java
Fixed MigrationUtils.importTo root activation to use virtual graph
[simantics/platform.git] / bundles / org.simantics.db.layer0 / src / org / simantics / db / layer0 / migration / MigrationUtils.java
index 052bc6e6fb393beb39f2f0e1e4b93ef7852f9eb8..e1421df90a89054f23d0a4625665f90ccf8be527 100644 (file)
  *******************************************************************************/
 package org.simantics.db.layer0.migration;
 
+import java.io.DataInputStream;
 import java.io.File;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashSet;
+import java.util.Map;
 import java.util.Set;
 
 import org.eclipse.core.runtime.IProgressMonitor;
 import org.eclipse.core.runtime.NullProgressMonitor;
 import org.simantics.databoard.Bindings;
+import org.simantics.databoard.adapter.AdaptException;
 import org.simantics.databoard.binding.mutable.Variant;
 import org.simantics.databoard.container.DataContainer;
+import org.simantics.databoard.container.DataContainers;
 import org.simantics.db.ReadGraph;
 import org.simantics.db.Resource;
 import org.simantics.db.Session;
 import org.simantics.db.WriteGraph;
 import org.simantics.db.WriteOnlyGraph;
 import org.simantics.db.common.CommentMetadata;
+import org.simantics.db.common.primitiverequest.PossibleResource;
 import org.simantics.db.common.request.BinaryRead;
 import org.simantics.db.common.request.FreshEscapedName;
 import org.simantics.db.common.request.UnaryRead;
@@ -42,10 +50,14 @@ import org.simantics.db.layer0.adapter.impl.DefaultPasteHandler;
 import org.simantics.db.layer0.adapter.impl.SharedOntologyImportAdvisor;
 import org.simantics.db.layer0.adapter.impl.TrashBinRemover;
 import org.simantics.db.layer0.internal.SimanticsInternal;
+import org.simantics.db.layer0.request.ActivateModel;
+import org.simantics.db.layer0.util.ExternalDownloadBean;
 import org.simantics.db.layer0.util.Layer0Utils;
 import org.simantics.db.layer0.util.TGTransferableGraphSource;
+import org.simantics.db.request.Write;
 import org.simantics.db.service.XSupport;
 import org.simantics.graph.db.IImportAdvisor;
+import org.simantics.graph.db.ImportResult;
 import org.simantics.graph.db.MissingDependencyException;
 import org.simantics.graph.db.TransferableGraphException;
 import org.simantics.graph.representation.Identity;
@@ -53,6 +65,8 @@ import org.simantics.graph.representation.Root;
 import org.simantics.graph.representation.TransferableGraph1;
 import org.simantics.graph.representation.TransferableGraphUtils;
 import org.simantics.layer0.Layer0;
+import org.simantics.operation.Layer0X;
+import org.simantics.simulation.ontology.SimulationResource;
 import org.simantics.utils.datastructures.Pair;
 import org.simantics.utils.datastructures.collections.CollectionUtils;
 
@@ -80,19 +94,26 @@ public class MigrationUtils {
 //        return getTG(session, state, true, false);
 //    }
     
-    public static void clearTempResource(Session session, final Resource resource) {
-        session.asyncRequest(new WriteRequest() {
-
-            @Override
-            public void perform(WriteGraph graph) throws DatabaseException {
-                graph.deny(resource, Layer0.getInstance(graph).PartOf);
-            }
+    public static void clearTempResource(Session session, Resource resource) {
+        session.asyncRequest((Write) graph -> {
+            graph.deny(resource, Layer0.getInstance(graph).PartOf);
         });
     }
 
+    /**
+     * Activate the imported resource, if there are no other active models and the resource is a Model. 
+     */
+    private static void activateIfNoActiveModel(WriteGraph graph, Resource root, Resource parent) throws DatabaseException {
+        Layer0X L0X = Layer0X.getInstance(graph);
+        SimulationResource SIMU = SimulationResource.getInstance(graph);
+        if (!graph.hasStatement(parent, L0X.Activates) && graph.isInstanceOf(root, SIMU.Model)) {
+            new ActivateModel(parent, root).perform(graph);
+        }
+    }
+
     public static Collection<Resource> importTo(IProgressMonitor monitor, Session session, MigrationState state, final Resource parent, final IImportAdvisor advisor) throws DatabaseException, TransferableGraphException {
         final Resource resource = getResource(monitor, session, state);
-        final ArrayList<Resource> result = new ArrayList<Resource>();
+        final ArrayList<Resource> result = new ArrayList<>();
         if(resource != null) {
             session.syncRequest(new WriteRequest() {
                 
@@ -108,11 +129,11 @@ public class MigrationUtils {
                            if(version != null) {
                                        VersionMap map = graph.syncRequest(new VersionMapRequest(parent));
                                        if(map.contains(baseName, version)) {
-                                   String newName = graph.syncRequest(new FreshEscapedName(parent, Layer0.getInstance(graph).ConsistsOf, baseName));
+                                   String newName = graph.syncRequest(new FreshEscapedName(parent, L0.ConsistsOf, baseName));
                                        graph.claimLiteral(root, L0.HasName, newName + "@1", Bindings.STRING);
                                        }
                            } else {
-                           String newName = graph.syncRequest(new FreshEscapedName(parent, Layer0.getInstance(graph).ConsistsOf, baseName));
+                           String newName = graph.syncRequest(new FreshEscapedName(parent, L0.ConsistsOf, baseName));
                            if(!newName.equals(baseName)) {
                                graph.claimLiteral(root, L0.HasName, newName, Bindings.STRING);
                            }
@@ -121,6 +142,10 @@ public class MigrationUtils {
                            graph.deny(root, L0.PartOf);
                            graph.claim(root, L0.PartOf, parent);
 
+                           if (Boolean.TRUE.equals( state.getProperty(MigrationKeys.ACTIVATE_ROOT_IF_NONE_ACTIVE) )) {
+                               activateIfNoActiveModel(graph, root, parent);
+                           }
+
                            CommentMetadata cm = graph.getMetadata(CommentMetadata.class);
                            graph.addMetadata(cm.add("Imported " + graph.getURI(root) + ", resource " + root));
                            
@@ -155,7 +180,6 @@ public class MigrationUtils {
     }
     
     
-    @SuppressWarnings("deprecation")
        public static Collection<MigrationStep> getMigrationSteps(DataContainer header) throws DatabaseException {
        
        return SimanticsInternal.sync(new BinaryRead<String,Integer,Collection<MigrationStep>>(header.format, header.version) {
@@ -164,9 +188,9 @@ public class MigrationUtils {
                        public Collection<MigrationStep> perform(ReadGraph graph) throws DatabaseException {
                                
                                Layer0 L0 = Layer0.getInstance(graph);
-                               ArrayList<Pair<Double,MigrationStep>> steps = new ArrayList<Pair<Double,MigrationStep>>();
+                               ArrayList<Pair<Double,MigrationStep>> steps = new ArrayList<>();
                        Instances query = graph.adapt(L0.Migration, Instances.class);
-                       Set<Resource> migrations = new HashSet<Resource>();
+                       Set<Resource> migrations = new HashSet<>();
                                for(Resource ontology : Layer0Utils.listOntologies(graph)) {
                                        migrations.addAll(Layer0Utils.sortByCluster(graph, query.find(graph, ontology)));
                                }
@@ -299,48 +323,57 @@ public class MigrationUtils {
         return t != null ? t : defaultValue;
     }
 
-    public static Resource importSharedOntology(Session session, TransferableGraph1 tg, boolean published) throws DatabaseException {
+    public static MigratedImportResult importSharedOntology(Session session, TransferableGraph1 tg, boolean published) throws DatabaseException {
        return importSharedOntology(null, session, tg, published);
     }
 
-    public static Resource importSharedOntology(IProgressMonitor monitor, Session session, TransferableGraph1 tg, boolean published) throws DatabaseException {
+    public static MigratedImportResult importSharedOntology(IProgressMonitor monitor, Session session, TransferableGraph1 tg, boolean published) throws DatabaseException {
        
        if(monitor == null) monitor = new NullProgressMonitor();
        
+       Variant edbVariant = tg.extensions.get(ExternalDownloadBean.EXTENSION_KEY);
+       if(edbVariant != null) {
+               try {
+                               ExternalDownloadBean edb = (ExternalDownloadBean)edbVariant.getValue(ExternalDownloadBean.BINDING);
+                               for(Map.Entry<String, String> entry : edb.downloads.entrySet()) {
+                                       String uri = entry.getKey();
+                                       Resource existing = session.syncRequest(new PossibleResource(uri));
+                                       if(existing == null) {
+                                               String download = entry.getValue();
+                                                URL url = new URL(download);
+                                                DataContainer container = DataContainers.readFile(new DataInputStream(url.openStream()));
+                                                TransferableGraph1 dependencyTg = (TransferableGraph1) container.content.getValue(TransferableGraph1.BINDING);
+                                                importSharedOntology(monitor, session, dependencyTg, true);
+                                       }
+                               }
+                       } catch (AdaptException e) {
+                               throw new DatabaseException(e);
+                       } catch (MalformedURLException e) {
+                               throw new DatabaseException(e);
+                       } catch (IOException e) {
+                               throw new DatabaseException(e);
+                       }
+               
+       }
+       
         Collection<Identity> roots = TransferableGraphUtils.getRoots(tg);
         if(roots.size() == 1) {
-//             Identity id = roots.iterator().next();
-//             final Root root = (Root)id.definition;
-//             Resource rootResource = session.syncRequest(new WriteResultRequest<Resource>() {
-//                             @Override
-//                             public Resource perform(WriteGraph graph) throws DatabaseException {
-//                                     Resource type = graph.getResource(root.type);
-//                                     Resource existing = graph.getPossibleResource(root.name);
-//                                     if(existing != null) throw new DatabaseException("Shared library " + root.name + " exists already.");
-//                                     return Layer0Utils.applySCL("Simantics/SharedOntologies", "createSharedOntology", graph, root.name, type);
-//                             }
-//             });
             try {
-               
                 TGTransferableGraphSource tgSource = new TGTransferableGraphSource(tg);
                 SharedOntologyImportAdvisor advisor = new SharedOntologyImportAdvisor(published);
-//                TransferableGraphs.importGraph1(session, tgSource, advisor);
-                
-//                if (advisor.getRoots().size() == 1) {
-//                     return advisor.getRoots().iterator().next();
-//                }
-                               //TransferableGraphs.importGraph1(session, tg, new SharedOntologyImportAdvisor(), null);
 
                 MigrationState state = newState();
-                //state.setProperty(MigrationStateKeys.BASE_URI, AprosBuiltins.URIs.Migration);
                 state.setProperty(MigrationStateKeys.UPDATE_DEPENDENCIES, false);
                 state.setProperty(MigrationStateKeys.CURRENT_TGS, tgSource);
                 state.setProperty(MigrationStateKeys.SESSION, session);
                 state.setProperty(MigrationStateKeys.PROGRESS_MONITOR, monitor);
                 state.setProperty(MigrationStateKeys.CURRENT_DATA_CONTAINER, new DataContainer("sharedLibrary", 1, new Variant(TransferableGraph1.BINDING, tg)));
 
-                return MigrationUtils.importMigrated(monitor, session, null, state, advisor, null);
-                
+                MigrationUtils.importMigrated(monitor, session, null, state, advisor, null);
+
+                Collection<Resource> resultRoots = state.getProperty(MigrationStateKeys.CURRENT_ROOT_RESOURCES);
+                ImportResult result = state.getProperty(MigrationStateKeys.IMPORT_RESULT);
+                return new MigratedImportResult(resultRoots, result);
                        } catch (TransferableGraphException e) {
                                throw new DatabaseException(e);
                        } catch (MissingDependencyException e) {