1 package org.simantics.structural.synchronization.base;
3 import org.eclipse.core.runtime.IProgressMonitor;
4 import org.simantics.db.ReadGraph;
5 import org.simantics.db.exception.CancelTransactionException;
6 import org.simantics.db.exception.DatabaseException;
7 import org.simantics.db.layer0.variable.Variable;
9 import gnu.trove.map.hash.THashMap;
12 * Utility for updating UIDs in the given component to correspond
13 * the RVIs of the given variable. This operation is needed when
14 * the mapping is part of a model that is imported to a new database
15 * and resource ids have been changed.
17 * @author Hannu Niemistö
18 * @author Tuukka Lehtonen
20 public class UpdateComponentUids<T extends ComponentBase<T>> {
22 public static interface ComponentUpdateProgressMonitor {
23 void componentsDone(int components, int componentCount);
26 private THashMap<String, String> oldToNewUids;
27 private IProgressMonitor monitor;
28 private ComponentUpdateProgressMonitor componentMonitor;
29 private ReadGraph graph;
30 private int componentCount;
33 private UpdateComponentUids(IProgressMonitor monitor, ReadGraph graph, int componentCount) {
34 this.monitor = monitor;
35 this.componentMonitor = monitor instanceof ComponentUpdateProgressMonitor ? (ComponentUpdateProgressMonitor) monitor : null;
37 this.componentCount = componentCount;
38 this.oldToNewUids = new THashMap<>(componentCount);
41 private void update(T component, Variable variable) throws DatabaseException {
42 String newUid = variable.getRVI(graph).toString();
43 oldToNewUids.put(component.uid, newUid);
44 component.uid = newUid;
46 // Handle progress monitoring and cancellation
48 if (monitor != null) {
49 if (componentMonitor != null)
50 componentMonitor.componentsDone(counter, componentCount);
51 if (monitor.isCanceled())
52 throw new CancelTransactionException();
55 for(Variable childVariable : variable.getChildren(graph)) {
56 String childName = childVariable.getName(graph);
57 T childComponent = component.getChild(childName);
58 if(childComponent != null)
59 update(childComponent, childVariable);
63 public static <T extends ComponentBase<T>> THashMap<String, String> update(ReadGraph graph, T component, Variable variable) throws DatabaseException {
64 return update(null, graph, component, variable);
67 public static <T extends ComponentBase<T>> THashMap<String, String> update(IProgressMonitor monitor, ReadGraph graph, T component, Variable variable) throws DatabaseException {
68 UpdateComponentUids<T> updateComponentUids = new UpdateComponentUids<T>(monitor, graph, countComponents(component));
69 updateComponentUids.update(component, variable);
70 return updateComponentUids.oldToNewUids;
73 public static <T extends ComponentBase<T>> int countComponents(T component) {
74 return new Counter<T>().count(component);
77 private static class Counter<T extends ComponentBase<T>> {
79 int count(T component) {
81 for (T child : component.getChildren())