--- /dev/null
+package org.simantics.interop.update.model;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Stack;
+
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.Statement;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.interop.test.GraphChanges;
+
+/**
+ *
+ * @author Marko Luukkainen <marko.luukkainen@vtt.fi>
+ *
+ */
+public abstract class UpdateOperations {
+
+ private List<UpdateOp> operations = new ArrayList<UpdateOp>();
+ private Map<Resource, UpdateOp> opMap = new HashMap<Resource, UpdateOp>();
+ private GraphChanges changes;
+
+ public UpdateOperations(GraphChanges changes) {
+ this.changes = changes;
+
+ }
+
+ public UpdateOp getUpdateOp(Resource r) {
+ return opMap.get(r);
+ }
+
+ public void applyAll(WriteGraph g) throws DatabaseException {
+ for (UpdateOp op : operations) {
+ apply(g, op);
+ }
+ }
+
+ public void applySelected(WriteGraph g) throws DatabaseException {
+ for (UpdateOp op : operations) {
+ if (op.selected())
+ apply(g, op);
+ }
+ }
+
+ public List<UpdateOp> getOperations() {
+ return operations;
+ }
+
+ private void apply(WriteGraph g, UpdateOp op) throws DatabaseException {
+ Stack<UpdateOp> stack = new Stack<UpdateOp>();
+ _apply(g, stack, op);
+ }
+
+ private void _apply(WriteGraph g, Stack<UpdateOp> stack, UpdateOp op) throws DatabaseException {
+ if (op.applied())
+ return;
+ if (stack.contains(op))
+ return;
+ stack.push(op);
+ if (op.requiresParentOps()) {
+ for (UpdateOp pop : op.getParentOps())
+ if (!pop.applied())
+ _apply(g, stack, pop);
+ }
+ if (op.requiresSubOps()) {
+ for (UpdateOp sop : op.getSubOps())
+ if (!sop.applied())
+ _apply(g, stack, sop);
+ }
+ stack.pop();
+ op.apply(g);
+ }
+
+ protected List<UpdateOp> getOps() {
+ List<UpdateOp> list = new ArrayList<UpdateOp>(operations.size());
+ list.addAll(operations);
+ return list;
+ }
+
+ protected void addOp(Resource r, UpdateOp op) {
+ opMap.put(r, op);
+ operations.add(op);
+ }
+
+ protected UpdateOp getOP(Resource r) {
+ return opMap.get(r);
+ }
+
+ public abstract void populate(ReadGraph g) throws DatabaseException;
+
+ protected static Statement getInverse(ReadGraph g, Statement otherComponentInv) throws DatabaseException{
+ Statement otherComponent = null;
+ for (Statement s : g.getStatements(otherComponentInv.getObject(), g.getInverse(otherComponentInv.getPredicate()))) {
+ if (s.getObject().equals(otherComponentInv.getSubject()))
+ otherComponent = s;
+ }
+ return otherComponent;
+ }
+
+ protected boolean compares(Resource r1, Resource r2) {
+ if (r1.equals(r2))
+ return true;
+ if (changes.getComparable().contains(r1, r2))
+ return true;
+ return false;
+ }
+
+}