]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/migration/MigrationStateImpl.java
Make Write-interfaces as @FunctionalInterface for lambdas
[simantics/platform.git] / bundles / org.simantics.db.layer0 / src / org / simantics / db / layer0 / migration / MigrationStateImpl.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.File;
15 import java.io.IOException;
16 import java.text.DateFormat;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.Date;
20 import java.util.HashMap;
21 import java.util.Map;
22
23 import org.eclipse.core.runtime.IProgressMonitor;
24 import org.simantics.databoard.Bindings;
25 import org.simantics.databoard.binding.mutable.Variant;
26 import org.simantics.databoard.container.DataContainer;
27 import org.simantics.db.ReadGraph;
28 import org.simantics.db.Resource;
29 import org.simantics.db.Session;
30 import org.simantics.db.WriteGraph;
31 import org.simantics.db.WriteOnlyGraph;
32 import org.simantics.db.common.request.WriteResultRequest;
33 import org.simantics.db.common.utils.Logger;
34 import org.simantics.db.exception.AssumptionException;
35 import org.simantics.db.exception.DatabaseException;
36 import org.simantics.db.layer0.adapter.impl.DefaultPasteImportAdvisor;
37 import org.simantics.db.layer0.internal.SimanticsInternal;
38 import org.simantics.db.layer0.util.Layer0Utils;
39 import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest;
40 import org.simantics.db.layer0.util.TransferableGraphConfiguration2;
41 import org.simantics.db.request.Read;
42 import org.simantics.db.service.ManagementSupport;
43 import org.simantics.db.service.SerialisationSupport;
44 import org.simantics.graph.db.IImportAdvisor;
45 import org.simantics.graph.db.IImportAdvisor2;
46 import org.simantics.graph.db.StreamingTransferableGraphFileReader;
47 import org.simantics.graph.db.TGStatusMonitor;
48 import org.simantics.graph.db.TransferableGraphImporter;
49 import org.simantics.graph.db.TransferableGraphSource;
50 import org.simantics.graph.db.TransferableGraphs;
51 import org.simantics.graph.db.WrapperAdvisor;
52 import org.simantics.graph.representation.ByteFileReader;
53 import org.simantics.graph.representation.TransferableGraph1;
54 import org.simantics.graph.representation.TransferableGraphFileReader;
55 import org.simantics.layer0.Layer0;
56
57 public class MigrationStateImpl implements MigrationState {
58
59         final private HashMap<String, Object> properties = new HashMap<String, Object>();
60         
61     @SuppressWarnings("unchecked")
62     @Override
63     public <T> T probeProperty(String key) throws DatabaseException {
64         return (T)properties.get(key);
65     }
66
67         @SuppressWarnings("unchecked")
68     @Override
69         public <T> T getProperty(String key) throws DatabaseException {
70             
71             T property = (T)properties.get(key);
72             if(property != null) return property;
73             
74             if(MigrationStateKeys.BASE_URI.equals(key)) {
75                 throw new IllegalStateException("Base URI needs to be supplied for migration.");
76         } else if (MigrationStateKeys.SESSION.equals(key)) {
77             throw new IllegalStateException("Session needs to be supplied for migration.");
78         } else if (MigrationStateKeys.MODEL_FILE.equals(key)) {
79             throw new IllegalStateException("Model file needs to be supplied for migration.");
80             } else if (MigrationStateKeys.CURRENT_TG.equals(key)) {
81                 
82                 final Resource resource = probeProperty(MigrationStateKeys.CURRENT_RESOURCE);
83                 final Collection<Resource> roots = probeProperty(MigrationStateKeys.CURRENT_ROOT_RESOURCES);
84                 if(roots != null) {
85                     Session session = getProperty(MigrationStateKeys.SESSION);
86                     TransferableGraph1 tg = session.syncRequest(new Read<TransferableGraph1>() {
87                         @Override
88                         public TransferableGraph1 perform(ReadGraph graph) throws DatabaseException {
89                             TransferableGraphConfiguration2 conf = new TransferableGraphConfiguration2(graph, roots, true, false);
90                             TransferableGraphSource source = graph.syncRequest(new ModelTransferableGraphSourceRequest(conf));
91                             return TransferableGraphs.create(graph, source);
92                         }
93                     });
94                     if (resource != null)
95                         MigrationUtils.clearTempResource(session, resource);
96                     setProperty(MigrationStateKeys.CURRENT_RESOURCE, null);
97                     setProperty(MigrationStateKeys.CURRENT_ROOT_RESOURCES, null);
98                 setProperty(MigrationStateKeys.DATABASE_REVISION_AFTER_TG_IMPORT, null);
99                     setProperty(MigrationStateKeys.CURRENT_TG, tg);
100                     return (T)tg;
101                 }
102                 
103             TransferableGraphFileReader reader = null;
104             try {
105                 File modelFile = getProperty(MigrationStateKeys.MODEL_FILE);
106                 reader = new TransferableGraphFileReader(modelFile);
107                 TransferableGraph1 tg = reader.readTG();
108                 setProperty(MigrationStateKeys.CURRENT_TG, tg);
109                 return (T)tg;
110             } catch (DatabaseException e) {
111                 throw e;
112             } catch (Throwable t) {
113                 throw new DatabaseException(t);
114             } finally {
115                 uncheckedClose(reader);
116             }
117                 
118         } else if (MigrationStateKeys.CURRENT_TGS.equals(key)) {
119
120             File modelFile = getProperty(MigrationStateKeys.MODEL_FILE);
121             
122             try {
123                 StreamingTransferableGraphFileReader reader = new StreamingTransferableGraphFileReader(modelFile);
124                 TransferableGraphSource tgs = reader.readTG();
125                 setProperty(MigrationStateKeys.CURRENT_TGS_READER, reader);
126                 setProperty(MigrationStateKeys.CURRENT_TGS, tgs);
127                 return (T)tgs;
128             } catch (DatabaseException e) {
129                 throw e;
130             } catch (IOException e) {
131                 throw new DatabaseException("An I/O exception occurred during reading '" + modelFile.getAbsolutePath() + "'", e);
132             } catch (Throwable t) {
133                 throw new DatabaseException(t);
134             }
135
136         } else if (MigrationStateKeys.CURRENT_DATA_CONTAINER.equals(key)) {
137             
138             try {
139                 
140                 TransferableGraphSource tgs = getProperty(MigrationStateKeys.CURRENT_TGS);
141                 DataContainer dc = tgs.getHeader();
142                 setProperty(MigrationStateKeys.CURRENT_DATA_CONTAINER, dc);
143                 return (T)dc;
144                 
145             } catch (DatabaseException e) {
146                 throw e;
147             } catch (Throwable t) {
148                 throw new DatabaseException(t);
149             }
150             
151         } else if (MigrationStateKeys.TG_EXTENSIONS.equals(key)) {
152             
153             try {
154                 
155                 TransferableGraphSource tgs = getProperty(MigrationStateKeys.CURRENT_TGS);
156                 Map<String,Variant> extensions = tgs.getExtensions();
157                 setProperty(MigrationStateKeys.TG_EXTENSIONS, extensions);
158                 return (T)extensions;
159                 
160             } catch (DatabaseException e) {
161                 throw e;
162             } catch (Throwable t) {
163                 throw new DatabaseException(t);
164             }
165
166         } else if (MigrationStateKeys.CURRENT_RESOURCE.equals(key) || MigrationStateKeys.CURRENT_ROOT_RESOURCES.equals(key)) {
167             
168             final Session session = getProperty(MigrationStateKeys.SESSION);
169             final IProgressMonitor monitor = probeProperty(MigrationStateKeys.PROGRESS_MONITOR);
170             final boolean updateDependencies = MigrationUtils.getProperty(this, MigrationStateKeys.UPDATE_DEPENDENCIES, Boolean.TRUE);
171             
172             final TransferableGraph1 tg = probeProperty(MigrationStateKeys.CURRENT_TG);
173             if(tg != null) {
174                 
175                 final Resource indexRoot = session.syncRequest(new WriteResultRequest<Resource>() {
176                     @Override
177                     public Resource perform(WriteGraph graph) throws DatabaseException {
178                         if(!updateDependencies)
179                             Layer0Utils.setDependenciesIndexingDisabled(graph, true);
180                         return createTemporaryRoot(graph);
181                     }
182                 });
183
184                 IImportAdvisor baseAdvisor = MigrationUtils.getProperty(this, MigrationStateKeys.IMPORT_ADVISOR, new DefaultPasteImportAdvisor(indexRoot));
185                 IImportAdvisor2 advisor = new WrapperAdvisor(baseAdvisor) {
186                         @Override
187                     public void beforeWrite(WriteOnlyGraph graph, TransferableGraphImporter process) throws DatabaseException {
188                         super.beforeWrite(graph, process);
189                         if(!updateDependencies)
190                             Layer0Utils.setDependenciesIndexingDisabled(graph, true);
191                     }
192                         @Override
193                     public void afterWrite(WriteOnlyGraph graph, TransferableGraphImporter process) throws DatabaseException {
194                         super.afterWrite(graph, process);
195                         Boolean storeResources = probeProperty(MigrationStateKeys.GET_RESOURCE_IDS);
196                         if(storeResources != null && storeResources) {
197                                 long[] ids = process.getResourceIds(session.getService(SerialisationSupport.class));
198                                 setProperty(MigrationStateKeys.RESOURCE_IDS, ids);
199                         }
200                     }
201                                 };
202                                 // Make sure that the supplied advisor is redirected to temp
203                                 advisor.redirect(indexRoot);
204                 
205                 TransferableGraphs.importGraph1WithMonitor(session, tg, advisor, new TGStatusMonitor() {
206                     @Override
207                     public void status(int percentage) {
208                         monitor.subTask("Importing model from file (" + percentage + "%)");
209                     }
210                     @Override
211                     public boolean isCanceled() {
212                         return monitor.isCanceled();
213                     }
214                 });
215                 
216                 setProperty(MigrationStateKeys.CURRENT_RESOURCE, indexRoot);
217                 setProperty(MigrationStateKeys.CURRENT_ROOT_RESOURCES, new ArrayList<>(advisor.getRoots()));
218                 setProperty(MigrationStateKeys.DATABASE_REVISION_AFTER_TG_IMPORT, session.getService(ManagementSupport.class).getHeadRevisionId());
219                 setProperty(MigrationStateKeys.CURRENT_TG, null);
220
221                 return getProperty(key);
222             }
223
224             final TransferableGraphSource tgs = getProperty(MigrationStateKeys.CURRENT_TGS);
225             if(tgs != null) {
226
227                 final Resource indexRoot = session.syncRequest(new WriteResultRequest<Resource>() {
228                     @Override
229                     public Resource perform(WriteGraph graph) throws DatabaseException {
230                         if(!updateDependencies)
231                             Layer0Utils.setDependenciesIndexingDisabled(graph, true);
232                         return createTemporaryRoot(graph);
233                     }
234                 });
235
236                 IImportAdvisor baseAdvisor = MigrationUtils.getProperty(this, MigrationStateKeys.IMPORT_ADVISOR, new DefaultPasteImportAdvisor(indexRoot));
237                 IImportAdvisor2 advisor = new WrapperAdvisor(baseAdvisor) {
238                         @Override
239                         public Resource getTarget() {
240                                 return indexRoot;
241                         }
242                         @Override
243                     public void beforeWrite(WriteOnlyGraph graph, TransferableGraphImporter process) throws DatabaseException {
244                         super.beforeWrite(graph, process);
245                         if(!updateDependencies)
246                             Layer0Utils.setDependenciesIndexingDisabled(graph, true);
247                     }
248                         @Override
249                     public void afterWrite(WriteOnlyGraph graph, TransferableGraphImporter process) throws DatabaseException {
250                         super.afterWrite(graph, process);
251                         Boolean storeResources = probeProperty(MigrationStateKeys.GET_RESOURCE_IDS);
252                         if(storeResources != null && storeResources) {
253                                 long[] ids = process.getResourceIds(session.getService(SerialisationSupport.class));
254                                 setProperty(MigrationStateKeys.RESOURCE_IDS, ids);
255                         }
256                     }
257                                 };
258                                 // Make sure that the supplied advisor is redirected to temp
259                                 advisor.redirect(indexRoot);
260                                 
261                 TransferableGraphs.importGraph1(session, tgs, advisor, new TGStatusMonitor() {
262                     @Override
263                     public void status(int percentage) {
264                         monitor.subTask("Importing model from file (" + percentage + "%)");
265                     }
266                     @Override
267                     public boolean isCanceled() {
268                         return monitor.isCanceled();
269                     }
270                 });
271
272                 setProperty(MigrationStateKeys.CURRENT_RESOURCE, indexRoot);
273                 setProperty(MigrationStateKeys.CURRENT_ROOT_RESOURCES, new ArrayList<>(advisor.getRoots()));
274                 setProperty(MigrationStateKeys.DATABASE_REVISION_AFTER_TG_IMPORT, session.getService(ManagementSupport.class).getHeadRevisionId());
275                 setProperty(MigrationStateKeys.CURRENT_TG, null);
276
277                 return getProperty(key);
278
279             }
280
281         } else if (MigrationStateKeys.UPDATE_DEPENDENCIES.equals(key)) {
282
283             return null;
284
285         }
286
287         return null;
288
289         }
290
291         @Override
292         public <T> void setProperty(String key, T value) {
293                 properties.put(key, value);
294         }
295
296         @Override
297         public void dispose() {
298                 // Close all possible open file handles
299                 try {
300                         StreamingTransferableGraphFileReader tgs = probeProperty(MigrationStateKeys.CURRENT_TGS_READER);
301                         uncheckedClose(tgs);
302                 } catch (DatabaseException e) {
303                         Logger.defaultLogError(e);
304                 }
305         }
306
307         private static void uncheckedClose(ByteFileReader closeable) {
308                 try {
309                         if (closeable != null)
310                                 closeable.close();
311                 } catch (IOException e) {
312                         //ignore
313                 }
314         }
315
316     private Resource createTemporaryRoot(WriteGraph graph) throws DatabaseException {
317         Layer0 L0 = Layer0.getInstance(graph);
318         Resource project = SimanticsInternal.getProject();
319         Resource root = graph.getPossibleObject(project, L0.PartOf);
320         Resource temp = Layer0Utils.getPossibleChild(graph, root, "Temp");
321         if (temp == null) 
322             throw new AssumptionException("Temporary folder 'Temp' not found under " + graph.getPossibleURI(root));
323
324         Resource indexRoot = graph.newResource();
325         String indexRootName = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date());
326         graph.claim(indexRoot, L0.InstanceOf, L0.IndexRoot);
327         graph.addLiteral(indexRoot, L0.HasName, L0.String, indexRootName, Bindings.STRING);
328         graph.claim(temp, L0.ConsistsOf, indexRoot);
329         return indexRoot;
330     }
331
332 }