36671d18b457bc48c21b0f65b16b504b31558417
[simantics/platform.git] / bundles / org.simantics.db.layer0 / src / org / simantics / db / layer0 / migration / MigrationUtils.java
1 /*******************************************************************************
2  * Copyright (c) 2012 Association for Decentralized Information Management in
3  * Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.db.layer0.migration;
13
14 import java.io.DataInputStream;
15 import java.io.File;
16 import java.io.IOException;
17 import java.net.MalformedURLException;
18 import java.net.URL;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.HashSet;
23 import java.util.Map;
24 import java.util.Set;
25
26 import org.eclipse.core.runtime.IProgressMonitor;
27 import org.eclipse.core.runtime.NullProgressMonitor;
28 import org.simantics.databoard.Bindings;
29 import org.simantics.databoard.adapter.AdaptException;
30 import org.simantics.databoard.binding.mutable.Variant;
31 import org.simantics.databoard.container.DataContainer;
32 import org.simantics.databoard.container.DataContainers;
33 import org.simantics.db.ReadGraph;
34 import org.simantics.db.Resource;
35 import org.simantics.db.Session;
36 import org.simantics.db.WriteGraph;
37 import org.simantics.db.WriteOnlyGraph;
38 import org.simantics.db.common.CommentMetadata;
39 import org.simantics.db.common.primitiverequest.PossibleResource;
40 import org.simantics.db.common.request.BinaryRead;
41 import org.simantics.db.common.request.FreshEscapedName;
42 import org.simantics.db.common.request.UnaryRead;
43 import org.simantics.db.common.request.WriteRequest;
44 import org.simantics.db.common.utils.VersionMap;
45 import org.simantics.db.common.utils.VersionMapRequest;
46 import org.simantics.db.common.utils.Versions;
47 import org.simantics.db.exception.DatabaseException;
48 import org.simantics.db.layer0.adapter.Instances;
49 import org.simantics.db.layer0.adapter.impl.DefaultPasteHandler;
50 import org.simantics.db.layer0.adapter.impl.SharedOntologyImportAdvisor;
51 import org.simantics.db.layer0.adapter.impl.TrashBinRemover;
52 import org.simantics.db.layer0.internal.SimanticsInternal;
53 import org.simantics.db.layer0.util.ExternalDownloadBean;
54 import org.simantics.db.layer0.util.Layer0Utils;
55 import org.simantics.db.layer0.util.TGTransferableGraphSource;
56 import org.simantics.db.service.XSupport;
57 import org.simantics.graph.db.IImportAdvisor;
58 import org.simantics.graph.db.ImportResult;
59 import org.simantics.graph.db.MissingDependencyException;
60 import org.simantics.graph.db.TransferableGraphException;
61 import org.simantics.graph.representation.Identity;
62 import org.simantics.graph.representation.Root;
63 import org.simantics.graph.representation.TransferableGraph1;
64 import org.simantics.graph.representation.TransferableGraphUtils;
65 import org.simantics.layer0.Layer0;
66 import org.simantics.operation.Layer0X;
67 import org.simantics.simulation.ontology.SimulationResource;
68 import org.simantics.utils.datastructures.Pair;
69 import org.simantics.utils.datastructures.collections.CollectionUtils;
70
71 public class MigrationUtils {
72         
73         public static final boolean DEBUG = false;
74
75     public static MigrationState newState() {
76         return new MigrationStateImpl();
77     }
78
79     public static MigrationStep getStep(Session session, String uri) throws DatabaseException {
80         return session.sync(new UnaryRead<String, MigrationStep>(uri) {
81
82             @Override
83             public MigrationStep perform(ReadGraph graph) throws DatabaseException {
84                 Resource r = graph.getResource(parameter);
85                 return graph.adapt(r, MigrationStep.class);
86             }
87
88         });
89     }
90
91 //    public static TransferableGraph1 getTG(Session session, MigrationState state) {
92 //        return getTG(session, state, true, false);
93 //    }
94     
95     public static void clearTempResource(Session session, final Resource resource) {
96         session.asyncRequest(new WriteRequest() {
97
98             @Override
99             public void perform(WriteGraph graph) throws DatabaseException {
100                 graph.deny(resource, Layer0.getInstance(graph).PartOf);
101             }
102         });
103     }
104
105     /**
106      * Activate the imported resource, if there are no other active models and the resource is a Model. 
107      */
108     private static void activateIfNoActiveModel(WriteGraph graph, Resource root, Resource parent) throws DatabaseException {
109         Layer0X L0X = Layer0X.getInstance(graph);
110         SimulationResource SIMU = SimulationResource.getInstance(graph);
111         if(!graph.hasStatement(parent, L0X.Activates) && graph.isInstanceOf(root, SIMU.Model))
112             graph.claim(parent, L0X.Activates, root);
113     }
114
115     public static Collection<Resource> importTo(IProgressMonitor monitor, Session session, MigrationState state, final Resource parent, final IImportAdvisor advisor) throws DatabaseException, TransferableGraphException {
116         final Resource resource = getResource(monitor, session, state);
117         final ArrayList<Resource> result = new ArrayList<Resource>();
118         if(resource != null) {
119             session.syncRequest(new WriteRequest() {
120                 
121                 @Override
122                 public void perform(WriteGraph graph) throws DatabaseException {
123                     
124                         Layer0 L0 = Layer0.getInstance(graph);
125                         
126                         for(Resource root : graph.getObjects(resource, L0.ConsistsOf)) {
127                                 
128                                 String baseName = Versions.getBaseName(graph, root);
129                             String version = Versions.getVersion(graph, root);
130                             if(version != null) {
131                                         VersionMap map = graph.syncRequest(new VersionMapRequest(parent));
132                                         if(map.contains(baseName, version)) {
133                                     String newName = graph.syncRequest(new FreshEscapedName(parent, Layer0.getInstance(graph).ConsistsOf, baseName));
134                                         graph.claimLiteral(root, L0.HasName, newName + "@1", Bindings.STRING);
135                                         }
136                             } else {
137                             String newName = graph.syncRequest(new FreshEscapedName(parent, Layer0.getInstance(graph).ConsistsOf, baseName));
138                             if(!newName.equals(baseName)) {
139                                 graph.claimLiteral(root, L0.HasName, newName, Bindings.STRING);
140                             }
141                             }
142
143                             graph.deny(root, L0.PartOf);
144                             graph.claim(root, L0.PartOf, parent);
145                             
146                             activateIfNoActiveModel(graph, root, parent);
147
148                             CommentMetadata cm = graph.getMetadata(CommentMetadata.class);
149                             graph.addMetadata(cm.add("Imported " + graph.getURI(root) + ", resource " + root));
150                             
151                             result.add(root);
152                     
153                         }
154                         
155                         graph.deny(resource, L0.PartOf);
156
157                 }
158             });
159         } else {
160             TransferableGraph1 tg = getTG(session, state);
161             if(tg != null) {
162                 DefaultPasteHandler.defaultExecute(tg, parent, new IImportAdvisor() {
163                     
164                     @Override
165                     public Resource createRoot(WriteOnlyGraph graph, Root root) throws DatabaseException {
166                         Resource r = advisor.createRoot(graph, root);
167                         result.add(r);
168                         return r;
169                     }
170                     
171                     @Override
172                     public Resource analyzeRoot(ReadGraph graph, Root root) throws DatabaseException {
173                         return advisor.analyzeRoot(graph, root);
174                     }
175                 });
176             }
177         }
178         return result;
179     }
180     
181     
182         public static Collection<MigrationStep> getMigrationSteps(DataContainer header) throws DatabaseException {
183         
184         return SimanticsInternal.sync(new BinaryRead<String,Integer,Collection<MigrationStep>>(header.format, header.version) {
185
186                         @Override
187                         public Collection<MigrationStep> perform(ReadGraph graph) throws DatabaseException {
188                                 
189                                 Layer0 L0 = Layer0.getInstance(graph);
190                                 ArrayList<Pair<Double,MigrationStep>> steps = new ArrayList<Pair<Double,MigrationStep>>();
191                         Instances query = graph.adapt(L0.Migration, Instances.class);
192                         Set<Resource> migrations = new HashSet<Resource>();
193                                 for(Resource ontology : Layer0Utils.listOntologies(graph)) {
194                                         migrations.addAll(Layer0Utils.sortByCluster(graph, query.find(graph, ontology)));
195                                 }
196                                 for(Resource migration : migrations) {
197                                         if(DEBUG)
198                                                 System.err.println("getMigrationSteps: " + graph.getURI(migration));
199                                         String format = graph.getRelatedValue(migration, L0.Migration_format);
200                                         if(DEBUG)
201                                                 System.err.println("-format=" + format);
202                                         if(parameter.equals(format)) {
203                                                 Integer from = graph.getRelatedValue(migration, L0.Migration_from);
204                                                 if(DEBUG)
205                                                         System.err.println("-from=" + from);
206                                                 Resource step = graph.getSingleObject(migration, L0.Migration_step);
207                                                 if(parameter2.equals(from)) {
208                                                         Double priority = graph.getRelatedValue(migration, L0.Migration_priority);
209                                                         steps.add(Pair.make(-priority, graph.adapt(step, MigrationStep.class))); 
210                                                         if(DEBUG)
211                                                                 System.err.println("=> ACCEPT");
212                                                 } else {
213                                                         if(DEBUG)
214                                                                 System.err.println("=> REJECT");
215                                                 }
216                                         }
217                                 }
218                                 /*
219                                 Resource base = graph.getResource(baseURI);
220                         if(DEBUG)
221                                 System.err.println("getMigrationSteps format=" + parameter + ", version=" + parameter2);
222                                 for(Resource migration : graph.sync(new ObjectsWithType(base, L0.ConsistsOf, L0.Migration))) {
223                                 }*/
224                                 return CollectionUtils.sortByFirst(steps);
225                         }
226                 
227         });
228     }
229     
230     public static Resource importMigrated(IProgressMonitor monitor, Session session, File modelFile, MigrationState state, IImportAdvisor advisor, Resource target) throws Exception {
231         Collection<Resource> roots = importMigratedMany(monitor, session, modelFile, state, advisor, target);
232         if(roots.size() == 1) {
233             return roots.iterator().next();
234         } else {
235             return null;
236         }
237     }
238
239     public static Collection<Resource> importMigratedMany(IProgressMonitor monitor, Session session, File modelFile, MigrationState state, IImportAdvisor advisor, Resource target) throws Exception {
240
241         //assert(target != null);
242         assert(advisor != null);
243         
244         if(monitor == null) monitor = new NullProgressMonitor();
245         
246         if(DEBUG)
247                 System.err.println("importMigrated: file=" + (modelFile != null ? modelFile.getAbsolutePath() : null));
248         
249         //String baseURI = state.getProperty(MigrationStateKeys.BASE_URI);
250 //      if(DEBUG)
251 //              System.err.println("importMigrated: baseURI=" + baseURI);
252
253         state.setProperty(MigrationStateKeys.MODEL_FILE, modelFile);
254         state.setProperty(MigrationStateKeys.SESSION, session);
255         state.setProperty(MigrationStateKeys.PROGRESS_MONITOR, monitor);
256         state.setProperty(MigrationStateKeys.IMPORT_ADVISOR, advisor);
257
258         DataContainer dc = state.getProperty(MigrationStateKeys.CURRENT_DATA_CONTAINER);
259         Collection<MigrationStep> migration = getMigrationSteps(dc);
260
261 //        TransferableGraph1 tg = state.getProperty(MigrationStateKeys.CURRENT_TG);
262 //        state.setProperty(MigrationStateKeys.TG_EXTENSIONS, tg.extensions);
263         
264         for(MigrationStep step : migration) {
265             step.applyTo(monitor, session, state);
266             if (monitor.isCanceled())
267                 break;
268         }
269
270         if (monitor.isCanceled()) {
271             // Move possibly created material into TrashBin and quit.
272             final Resource root = state.probeProperty(MigrationStateKeys.CURRENT_RESOURCE);
273             if (root != null) {
274                 session.syncRequest(new WriteRequest() {
275                     @Override
276                     public void perform(WriteGraph graph) throws DatabaseException {
277                         new TrashBinRemover(root).remove(graph);
278                     }
279                 });
280             }
281             return Collections.emptyList();
282         }
283
284         // Absolute path imports end up here
285         if(target == null) {
286                 Collection<Resource> roots = state.getProperty(MigrationStateKeys.CURRENT_ROOT_RESOURCES);
287                 return roots;
288         }
289                         
290         // Finally import model into final destination
291         return importTo(monitor, session, state, target, advisor);
292         
293     }
294     
295     public static TransferableGraph1 getTG(Session session, MigrationState state) throws DatabaseException {
296         return state.getProperty(MigrationStateKeys.CURRENT_TG);
297     }
298     
299     public static Resource getResource(IProgressMonitor monitor, Session session, MigrationState state) throws DatabaseException {
300         return state.getProperty(MigrationStateKeys.CURRENT_RESOURCE);
301     }
302
303     public static Collection<Resource> getRootResources(IProgressMonitor monitor, Session session, MigrationState state) throws DatabaseException {
304         return state.getProperty(MigrationStateKeys.CURRENT_ROOT_RESOURCES);
305     }
306
307     /**
308      * Get a property from the specified MigrationState and return specified
309      * default value if the property value is <code>null</code>.
310      * 
311      * @param state the state to get the property from
312      * @param key the property to get
313      * @param defaultValue
314      *            the default value to return if the property value is
315      *            <code>null</code>
316      * @return the property value
317      * @throws DatabaseException
318      *             if fetching the property fails for some reason
319      */
320     public static <T> T getProperty(MigrationState state, String key, T defaultValue) throws DatabaseException {
321         T t = state.getProperty(key);
322         return t != null ? t : defaultValue;
323     }
324
325     public static MigratedImportResult importSharedOntology(Session session, TransferableGraph1 tg, boolean published) throws DatabaseException {
326         return importSharedOntology(null, session, tg, published);
327     }
328
329     public static MigratedImportResult importSharedOntology(IProgressMonitor monitor, Session session, TransferableGraph1 tg, boolean published) throws DatabaseException {
330         
331         if(monitor == null) monitor = new NullProgressMonitor();
332         
333         Variant edbVariant = tg.extensions.get(ExternalDownloadBean.EXTENSION_KEY);
334         if(edbVariant != null) {
335                 try {
336                                 ExternalDownloadBean edb = (ExternalDownloadBean)edbVariant.getValue(ExternalDownloadBean.BINDING);
337                                 for(Map.Entry<String, String> entry : edb.downloads.entrySet()) {
338                                         String uri = entry.getKey();
339                                         Resource existing = session.syncRequest(new PossibleResource(uri));
340                                         if(existing == null) {
341                                                 String download = entry.getValue();
342                                                  URL url = new URL(download);
343                                                  DataContainer container = DataContainers.readFile(new DataInputStream(url.openStream()));
344                                                  TransferableGraph1 dependencyTg = (TransferableGraph1) container.content.getValue(TransferableGraph1.BINDING);
345                                                  importSharedOntology(monitor, session, dependencyTg, true);
346                                         }
347                                 }
348                         } catch (AdaptException e) {
349                                 throw new DatabaseException(e);
350                         } catch (MalformedURLException e) {
351                                 throw new DatabaseException(e);
352                         } catch (IOException e) {
353                                 throw new DatabaseException(e);
354                         }
355                 
356         }
357         
358         Collection<Identity> roots = TransferableGraphUtils.getRoots(tg);
359         if(roots.size() == 1) {
360             try {
361                 TGTransferableGraphSource tgSource = new TGTransferableGraphSource(tg);
362                 SharedOntologyImportAdvisor advisor = new SharedOntologyImportAdvisor(published);
363
364                 MigrationState state = newState();
365                 state.setProperty(MigrationStateKeys.UPDATE_DEPENDENCIES, false);
366                 state.setProperty(MigrationStateKeys.CURRENT_TGS, tgSource);
367                 state.setProperty(MigrationStateKeys.SESSION, session);
368                 state.setProperty(MigrationStateKeys.PROGRESS_MONITOR, monitor);
369                 state.setProperty(MigrationStateKeys.CURRENT_DATA_CONTAINER, new DataContainer("sharedLibrary", 1, new Variant(TransferableGraph1.BINDING, tg)));
370
371                 MigrationUtils.importMigrated(monitor, session, null, state, advisor, null);
372
373                 Collection<Resource> resultRoots = state.getProperty(MigrationStateKeys.CURRENT_ROOT_RESOURCES);
374                 ImportResult result = state.getProperty(MigrationStateKeys.IMPORT_RESULT);
375                 return new MigratedImportResult(resultRoots, result);
376                         } catch (TransferableGraphException e) {
377                                 throw new DatabaseException(e);
378                         } catch (MissingDependencyException e) {
379                                 throw e;
380                         } catch (DatabaseException e) {
381                                 throw e;
382                         } catch (Exception e) {
383                             throw new DatabaseException(e);
384             } finally {
385                 session.getService(XSupport.class).setServiceMode(false, false);
386             }
387             
388         }
389         
390         return null;
391         
392     }
393     
394 }