1 package org.simantics.structural.synchronization.client;
3 import gnu.trove.map.hash.TObjectIntHashMap;
4 import gnu.trove.set.hash.THashSet;
6 import java.util.ArrayList;
7 import java.util.Collection;
8 import java.util.Collections;
11 import org.eclipse.core.runtime.IProgressMonitor;
12 import org.simantics.db.ReadGraph;
13 import org.simantics.db.Resource;
14 import org.simantics.db.common.procedure.adapter.TransientCacheAsyncListener;
15 import org.simantics.db.exception.CancelTransactionException;
16 import org.simantics.db.exception.DatabaseException;
17 import org.simantics.db.layer0.exception.MissingVariableValueException;
18 import org.simantics.db.layer0.request.ResourceToPossibleVariable;
19 import org.simantics.db.layer0.variable.RVI;
20 import org.simantics.db.layer0.variable.Variable;
21 import org.simantics.db.service.ManagementSupport;
22 import org.simantics.layer0.Layer0;
23 import org.simantics.scl.runtime.SCLContext;
24 import org.simantics.structural.stubs.StructuralResource2;
25 import org.simantics.structural.synchronization.protocol.ChildInfo;
26 import org.simantics.structural.synchronization.protocol.Connection;
27 import org.simantics.structural.synchronization.protocol.SerializedVariable;
28 import org.simantics.structural.synchronization.protocol.SynchronizationEventHandler;
29 import org.simantics.structural.synchronization.protocol.SynchronizationException;
30 import org.simantics.structural2.variables.VariableConnectionPointDescriptor;
32 public class Synchronizer {
34 public static boolean TRACE = false;
38 StructuralResource2 STR;
39 THashSet<String> visitedTypes = new THashSet<String>();
40 IProgressMonitor monitor;
42 double workDone = 0.0;
46 public Synchronizer(ReadGraph graph) {
48 L0 = Layer0.getInstance(graph);
49 STR = StructuralResource2.getInstance(graph);
52 public void setMonitor(IProgressMonitor monitor, int maxWork) {
53 this.monitor = monitor;
54 this.maxWork = maxWork;
55 this.workDoneInteger = 0;
58 private void didWork(double amount) {
60 //System.out.println(workDone);
62 int t = (int)(workDone * maxWork);
63 if(t > workDoneInteger) {
64 monitor.worked(t-workDoneInteger);
70 ChildInfo mapChild(Variable child) throws DatabaseException {
71 String name = child.getName(graph);
72 RVI rvi = child.getRVI(graph);
73 return new ChildInfo(name, rvi.toString());
76 Collection<ChildInfo> mapChildren(SynchronizationEventHandler handler, Collection<Variable> children) throws DatabaseException {
77 ArrayList<ChildInfo> result = new ArrayList<ChildInfo>(children.size());
78 for(Variable child : children) {
79 if(child.getPossibleType(graph, STR.Component) != null)
81 result.add(mapChild(child));
82 } catch(Exception e) {
83 handler.reportProblem("Failed to get ChildInfo for " + child + ".", e);
89 Collection<Connection> mapConnections(SynchronizationEventHandler handler, Variable child) throws DatabaseException {
90 ArrayList<Connection> result = new ArrayList<Connection>();
91 for(Variable conn : child.getProperties(graph, StructuralResource2.URIs.SynchronizedConnectionRelation)) {
92 String name = conn.getName(graph);
93 org.simantics.structural2.variables.Connection vc = conn.getValue(graph);
94 Collection<VariableConnectionPointDescriptor> connectionPoints = vc.getConnectionPointDescriptors(graph, null);
95 List<String> cps = new ArrayList<String>(connectionPoints.size());
96 for(VariableConnectionPointDescriptor desc : connectionPoints) {
97 if(desc.isFlattenedFrom(graph, conn)) continue;
98 if(!desc.hasClassification(graph, StructuralResource2.URIs.ProvidingConnectionRelation)) continue;
99 String cpRef = desc.getRelativeRVI(graph, child);
103 result.add(new Connection(name, cps));
111 private SerializedVariable serialize(SynchronizationEventHandler handler, Variable var, String name) throws DatabaseException {
113 SerializedVariable result = new SerializedVariable(name, var.getVariantValue(graph));
114 for(Variable prop : var.getProperties(graph, StructuralResource2.URIs.SynchronizedRelation)) {
115 String pName = prop.getName(graph);
116 SerializedVariable v = serialize(handler, prop, pName);
117 if(v != null) result.addProperty(pName, v);
120 } catch (MissingVariableValueException e) {
121 handler.reportProblem("Failed to read " + name + ". " + e.getMessage());
124 while((cur = cur.getCause()) != null) {
125 if(!(cur instanceof MissingVariableValueException)) {
126 handler.reportProblem(cur.getMessage());
130 } catch (Exception e) {
131 handler.reportProblem("Failed to serialize " + name + ": " + e.getMessage(), e);
138 Collection<SerializedVariable> mapProperties(SynchronizationEventHandler handler, Variable child) throws DatabaseException {
139 ArrayList<SerializedVariable> result = new ArrayList<SerializedVariable>();
140 for(Variable prop : child.getProperties(graph, StructuralResource2.URIs.SynchronizedRelation)) {
141 SerializedVariable serialized = serialize(handler, prop, prop.getName(graph));
142 if(serialized != null) result.add(serialized);
148 * Assumes that the variable points to a composite.
150 public void fullSynchronization(Variable variable, SynchronizationEventHandler handler) throws DatabaseException {
153 System.out.println("fullSynchronization " + variable.getURI(graph));
154 duration -= System.nanoTime();
156 SCLContext context = SCLContext.getCurrent();
157 Object oldGraph = context.put("graph", graph);
159 handler.beginSynchronization();
160 synchronizationRec(variable, handler, null, 1.0);
161 handler.endSynchronization();
163 context.put("graph", oldGraph);
166 duration += System.nanoTime();
167 System.out.println("full sync in " + 1e-9*duration + "s.");
172 * Recursive implementation of partial and full synchronization. If {@code changeFlags}
173 * is null, this is full synchronization, otherwise partial synchronization.
175 private void synchronizationRec(Variable variable, SynchronizationEventHandler handler,
176 TObjectIntHashMap<Variable> changeFlags,
177 double proportionOfWork) throws DatabaseException {
178 String name = variable.getName(graph);
179 Resource type = variable.getPossibleType(graph, STR.Component);
181 // This same filtering is done separately in mapChildren when beginComponent has been called for the parent.
184 Collection<Variable> children = variable.getChildren(graph);
185 if(graph.isInheritedFrom(type, STR.Composite) || graph.isInheritedFrom(type, STR.AbstractDefinedComponentType)) {
186 String typeId = graph.getPossibleURI(type);
188 throw new SynchronizationException("User component " + type + " does not have an URI.");
189 if(visitedTypes.add(typeId))
190 visitType(typeId, type, handler);
191 boolean endComponentNeeded = false;
193 Collection<SerializedVariable> propertyMap = mapProperties(handler, variable);
194 Collection<ChildInfo> childMap = mapChildren(handler, children);
195 endComponentNeeded = true;
196 handler.beginComponent(name, typeId,
198 Collections.<Connection>emptyList(),
200 } catch(Exception e) {
201 handler.reportProblem("Failed to synchronize " + name + ": " + e.getMessage(), e);
202 if (endComponentNeeded)
203 handler.endComponent();
207 String typeId = graph.getPossibleURI(type);
209 throw new SynchronizationException("User component " + type + " does not have an URI.");
210 if(visitedTypes.add(typeId))
211 visitType(typeId, type, handler);
212 boolean endComponentNeeded = false;
214 Collection<SerializedVariable> propertyMap = mapProperties(handler, variable);
215 Collection<Connection> connectionMap = mapConnections(handler, variable);
216 Collection<ChildInfo> childMap = mapChildren(handler, children);
217 endComponentNeeded = true;
218 handler.beginComponent(name,
223 } catch(Exception e) {
224 handler.reportProblem("Failed to synchronize " + name + ": " + e.getMessage(), e);
225 if (endComponentNeeded)
226 handler.endComponent();
231 if(changeFlags == null) {
232 // Full synchronization, synchronize all children
233 if(children.size() > 0) {
234 double proportionOfWorkForChildren = proportionOfWork / children.size();
235 for(Variable child : children)
236 synchronizationRec(child, handler, null, proportionOfWorkForChildren);
239 didWork(proportionOfWork);
240 // Full synchronization is cancelable
241 if(monitor != null && monitor.isCanceled())
242 throw new CancelTransactionException();
246 // Partial synchronization, synchronize only children with positive changeFlag
247 int relevantChildCount = 0;
248 for(final Variable child : children) {
249 int changeStatus = changeFlags.get(child);
250 if(changeStatus != 0)
251 ++relevantChildCount;
253 if(relevantChildCount > 0) {
254 double proportionOfWorkForChildren = proportionOfWork / relevantChildCount;
255 for(final Variable child : children) {
256 int changeStatus = changeFlags.get(child);
257 if(changeStatus == 0)
259 synchronizationRec(child, handler,
260 // Apply full synchronization for subtree if changeStatus > 1
261 changeStatus==1 ? changeFlags : null,
262 proportionOfWorkForChildren
267 didWork(proportionOfWork);
270 handler.endComponent();
273 public void partialSynchronization(Variable variable, SynchronizationEventHandler handler, TObjectIntHashMap<Variable> changeFlags) throws DatabaseException {
276 System.out.println("partialSynchronization " + variable.getURI(graph));
277 duration -= System.nanoTime();
279 int changeStatus = changeFlags.get(variable);
280 if(changeStatus == 0) return;
281 SCLContext context = SCLContext.getCurrent();
282 Object oldGraph = context.put("graph", graph);
284 handler.beginSynchronization();
285 synchronizationRec(variable, handler, changeStatus == 1 ? changeFlags : null, 1.0);
286 handler.endSynchronization();
288 context.put("graph", oldGraph);
291 duration += System.nanoTime();
292 System.out.println("partial sync in " + 1e-9*duration + "s.");
296 public void partialSynchronization(Variable variable, SynchronizationEventHandler handler, long fromRevision) throws DatabaseException {
297 TObjectIntHashMap<Variable> modifiedComponents = StructuralChangeFlattener.getModifiedComponents(graph, variable, fromRevision);
298 /*System.out.println("----------------");
299 modifiedComponents.forEachEntry(
300 new TObjectIntProcedure<Variable>() {
302 public boolean execute(Variable a, int b) {
304 System.out.println("Changed: " + a.getURI(graph) + " " + b);
305 } catch (DatabaseException e) {
311 partialSynchronization(variable, handler, modifiedComponents);
314 void visitType(String typeId, Resource typeResource, SynchronizationEventHandler handler) throws DatabaseException {
315 Variable typeVariable = graph.syncRequest(new ResourceToPossibleVariable(typeResource), TransientCacheAsyncListener.<Variable>instance());
316 handler.beginType(typeId, mapProperties(handler, typeVariable));
320 public long getHeadRevisionId() throws DatabaseException {
321 return graph.getService(ManagementSupport.class).getHeadRevisionId()+1;