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;
40 private void update(T component, Variable variable) throws DatabaseException {
41 String newUid = variable.getRVI(graph).toString();
42 oldToNewUids.put(component.uid, newUid);
43 component.uid = newUid;
45 // Handle progress monitoring and cancellation
47 if (monitor != null) {
48 if (componentMonitor != null)
49 componentMonitor.componentsDone(counter, componentCount);
50 if (monitor.isCanceled())
51 throw new CancelTransactionException();
54 for(Variable childVariable : variable.getChildren(graph)) {
55 String childName = childVariable.getName(graph);
56 T childComponent = component.getChild(childName);
57 if(childComponent != null)
58 update(childComponent, childVariable);
62 public static <T extends ComponentBase<T>> THashMap<String, String> update(ReadGraph graph, T component, Variable variable) throws DatabaseException {
63 return update(null, graph, component, variable);
66 public static <T extends ComponentBase<T>> THashMap<String, String> update(IProgressMonitor monitor, ReadGraph graph, T component, Variable variable) throws DatabaseException {
67 UpdateComponentUids<T> updateComponentUids = new UpdateComponentUids<T>(monitor, graph, countComponents(component));
68 updateComponentUids.update(component, variable);
69 return updateComponentUids.oldToNewUids;
72 public static <T extends ComponentBase<T>> int countComponents(T component) {
73 return new Counter<T>().count(component);
76 private static class Counter<T extends ComponentBase<T>> {
78 int count(T component) {
80 for (T child : component.getChildren())