-/*******************************************************************************\r
- * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
- * in Industry THTH ry.\r
- * All rights reserved. This program and the accompanying materials\r
- * are made available under the terms of the Eclipse Public License v1.0\r
- * which accompanies this distribution, and is available at\r
- * http://www.eclipse.org/legal/epl-v10.html\r
- *\r
- * Contributors:\r
- * VTT Technical Research Centre of Finland - initial API and implementation\r
- *******************************************************************************/\r
-package org.simantics.db.common.utils;\r
-\r
-import java.util.ArrayList;\r
-import java.util.Collection;\r
-import java.util.Collections;\r
-import java.util.HashSet;\r
-import java.util.List;\r
-import java.util.ListIterator;\r
-import java.util.Set;\r
-\r
-import org.simantics.databoard.Bindings;\r
-import org.simantics.db.AsyncReadGraph;\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.Resource;\r
-import org.simantics.db.WriteGraph;\r
-import org.simantics.db.WriteOnlyGraph;\r
-import org.simantics.db.common.request.ReadRequest;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.exception.RuntimeDatabaseException;\r
-import org.simantics.db.exception.ValidationException;\r
-import org.simantics.db.function.DbFunction;\r
-import org.simantics.db.procedure.AsyncMultiProcedure;\r
-import org.simantics.layer0.Layer0;\r
-import org.simantics.utils.datastructures.Pair;\r
-\r
-public class OrderedSetUtils {\r
-\r
- /**\r
- * Returns true, if <tt>l</tt> contains the element <tt>el</tt>.\r
- */\r
- public static boolean contains(ReadGraph g, Resource l, Resource el) throws DatabaseException {\r
- return g.hasStatement(el, l) && !l.equals(el);\r
- }\r
-\r
- /**\r
- * Returns the next element in the ordered set or <tt>l</tt>,\r
- * if <tt>el</tt> is the last element. Called for <tt>el</tt>, returns\r
- * the first element in the set.\r
- */\r
- public static Resource next(ReadGraph g, Resource l, Resource el) throws DatabaseException {\r
- Collection<Resource> nexts = g.getObjects(el, l);\r
- if(nexts.size() != 1)\r
- throw new InvalidOrderedSetException("Invalid list element: " + l + " " + el + " " + nexts.size() + " successors.");\r
- for(Resource r : nexts)\r
- return r;\r
- return null;\r
- }\r
-\r
- public static void forNext(AsyncReadGraph g, final Resource l, Resource el, final AsyncMultiProcedure<Resource> procedure) {\r
- g.forEachObject(el, l, new AsyncMultiProcedure<Resource>() {\r
-\r
- @Override\r
- public void exception(AsyncReadGraph graph, Throwable t) {\r
- procedure.exception(graph, t);\r
- }\r
-\r
- @Override\r
- public void finished(AsyncReadGraph graph) {\r
- }\r
-\r
- @Override\r
- public void execute(AsyncReadGraph graph, Resource nel) {\r
- if(!nel.equals(l)) {\r
- procedure.execute(graph, nel);\r
- forNext(graph, l, nel, procedure);\r
- }\r
- }\r
- });\r
-// Collection<Resource> nexts = g.getObjects(el, l);\r
-// if(nexts.size() != 1)\r
-// throw new NoSingleResultException("Invalid list element: " + nexts.size() + " successors.");\r
-// for(Resource r : nexts)\r
-// return r;\r
-// return null;\r
- }\r
-\r
- /**\r
- * Returns the previouse element in the ordered set or <tt>l</tt>,\r
- * if <tt>el</tt> is the first element. Called for <tt>el</tt>, returns\r
- * the last element in the set.\r
- */\r
- public static Resource prev(ReadGraph g, Resource l, Resource el) throws DatabaseException {\r
- Collection<Resource> prevs = g.getObjects(el, g.getInverse(l));\r
- if(prevs.size() != 1) {\r
- throw new InvalidOrderedSetException("Invalid list element, " + prevs.size() + " predecessors.");\r
- }\r
- for(Resource r : prevs)\r
- return r;\r
- return null;\r
- }\r
-\r
- /**\r
- * Adds a given elements <tt>el</tt> to the list <tt>l</tt>. Returns\r
- * true, if the element was really added.\r
- */\r
- public static boolean add(WriteGraph g, Resource l, Resource el) throws DatabaseException {\r
- if(g.hasStatement(el, l))\r
- return false;\r
- Resource back = prev(g, l, l);\r
- g.denyStatement(back, l, l);\r
- g.claim(back, l, el);\r
- g.claim(el, l, l);\r
- return true;\r
- }\r
-\r
- /**\r
- * Adds a given elements <tt>el</tt> to the list <tt>l</tt>. Returns\r
- * true, if the element was really added.\r
- */\r
- public static boolean addFirst(WriteGraph g, Resource l, Resource el) throws DatabaseException {\r
- return addAfter(g, l, l, el);\r
- }\r
-\r
- public static boolean addAll(WriteGraph g, Resource l, Iterable<Resource> els) throws DatabaseException {\r
- for(Resource r : els)\r
- if(g.hasStatement(r, l))\r
- return false;\r
- Resource cur = prev(g, l, l);\r
- g.denyStatement(cur, l, l);\r
- for(Resource r : els) {\r
- g.claim(cur, l, r);\r
- cur = r;\r
- }\r
- g.claim(cur, l, l);\r
- return true;\r
- }\r
-\r
- public static boolean addAllNew(WriteGraph g, Resource l, Iterable<Resource> els) throws DatabaseException {\r
- Resource cur = prev(g, l, l);\r
- Resource inv = g.getInverse(l);\r
- g.deny(cur, l, inv, l);\r
- for(Resource r : els) {\r
- g.claim(cur, l, inv, r);\r
- cur = r;\r
- }\r
- g.claim(cur, l, inv, l);\r
- return true;\r
- }\r
-\r
- public static boolean addAfter(WriteGraph g, Resource l, Resource pos, Resource el) throws DatabaseException {\r
- if(g.hasStatement(el, l))\r
- return false;\r
- Resource next = next(g, l, pos);\r
- g.denyStatement(pos, l, next);\r
- g.claim(pos, l, el);\r
- g.claim(el, l, next);\r
- return true;\r
- }\r
-\r
- public static boolean addBefore(WriteGraph g, Resource l, Resource pos, Resource el) throws DatabaseException {\r
- if(g.hasStatement(el, l))\r
- return false;\r
- Resource prev = prev(g, l, pos);\r
- g.denyStatement(prev, l, pos);\r
- g.claim(prev, l, el);\r
- g.claim(el, l, pos);\r
- return true;\r
- }\r
-\r
- /**\r
- * Removes a given elements <tt>el</tt> from the list <tt>l</tt>. Returns\r
- * true, if the element was really removed.\r
- */\r
- public static boolean remove(WriteGraph g, Resource l, Resource el) throws DatabaseException {\r
- Collection<Resource> nexts = g.getObjects(el, l);\r
- if(nexts.size() == 0)\r
- return false;\r
- if(nexts.size() != 1)\r
- throw new InvalidOrderedSetException("Invalid list element.");\r
- Collection<Resource> prevs = g.getObjects(el, g.getInverse(l));\r
- if(prevs.size() != 1)\r
- throw new InvalidOrderedSetException("Invalid list element.");\r
-\r
- for(Resource p : prevs)\r
- for(Resource n : nexts) {\r
- g.denyStatement(p, l, el);\r
- g.denyStatement(el, l, n);\r
- g.claim(p, l, n);\r
- return true;\r
- }\r
- return true;\r
- }\r
-\r
- public static List<Resource> removeList(WriteGraph g, Resource l) throws DatabaseException {\r
- List<Resource> els = toList(g, l);\r
- for(Resource el : els)\r
- g.deny(el, l);\r
- g.deny(l, l);\r
- Resource inv = g.getInverse(l);\r
- g.deny(l);\r
- g.deny(inv);\r
- return els;\r
- }\r
-\r
- public static void replace(WriteGraph g, Resource l, Resource oldEl, Resource newEl) throws DatabaseException {\r
- Collection<Resource> nexts = g.getObjects(oldEl, l);\r
- if(nexts.size() != 1)\r
- throw new InvalidOrderedSetException("Invalid list element.");\r
- Collection<Resource> prevs = g.getObjects(oldEl, g.getInverse(l));\r
- if(prevs.size() != 1)\r
- throw new InvalidOrderedSetException("Invalid list element.");\r
-\r
- for(Resource p : prevs)\r
- for(Resource n : nexts) {\r
- g.denyStatement(p, l, oldEl);\r
- g.denyStatement(oldEl, l, n);\r
- g.claim(p, l, newEl);\r
- g.claim(newEl, l, n);\r
- return;\r
- }\r
- }\r
-\r
- /**\r
- * Converts ordered set into a list.\r
- */\r
- public static List<Resource> toList(ReadGraph g, Resource l) throws DatabaseException {\r
- ArrayList<Resource> ret = new ArrayList<Resource>();\r
- Resource cur = l;\r
- while(true) {\r
- cur = next(g, l, cur);\r
- if(cur.equals(l))\r
- return ret;\r
- ret.add(cur);\r
- }\r
- }\r
-\r
- /**\r
- * Converts ordered set into a list.\r
- */\r
- public static void forEach(AsyncReadGraph g, final Resource l, final AsyncMultiProcedure<Resource> procedure) {\r
- g.asyncRequest(new ReadRequest() {\r
-\r
- @Override\r
- public void run(ReadGraph graph) throws DatabaseException {\r
- for(Resource r : toList(graph, l))\r
- procedure.execute(graph, r);\r
- }\r
-\r
- });\r
- }\r
-\r
- /**\r
- * Creates an empty ordered set.\r
- */\r
- public static Resource create(WriteOnlyGraph g, Resource type) throws DatabaseException {\r
- Layer0 l0 = g.getService(Layer0.class);\r
- Resource l = g.newResource();\r
- g.claim(l, l0.InstanceOf, null, type);\r
- g.claim(l, l0.SubrelationOf, null, l0.HasNext);\r
- Resource invL = g.newResource();\r
- g.claim(invL, l0.SubrelationOf, null, l0.HasPrevious);\r
- g.claim(l, l0.InverseOf, l0.InverseOf, invL);\r
- g.claim(l, l, invL, l);\r
- return l;\r
- }\r
-\r
- /**\r
- * Creates an ordered set containing the given elements.\r
- * It is assumed that the elements do not contain duplicates.\r
- */\r
- @Deprecated\r
- public static Resource create(WriteOnlyGraph g, Resource type, Iterable<Resource> c) throws DatabaseException {\r
- Layer0 l0 = g.getService(Layer0.class);\r
- Resource l = g.newResource();\r
- g.claim(l, l0.InstanceOf, null, type);\r
- g.claim(l, l0.SubrelationOf, null, l0.HasNext);\r
- Resource invL = g.newResource();\r
- g.claim(invL, l0.SubrelationOf, null, l0.HasPrevious);\r
- g.claim(l, l0.InverseOf, l0.InverseOf, invL);\r
- Resource cur = l;\r
- for(Resource r : c) {\r
- g.claim(cur, l, invL, r);\r
- cur = r;\r
- }\r
- g.claim(cur, l, invL, l);\r
- return l;\r
- }\r
-\r
- public static Resource create(WriteOnlyGraph g, Resource type, String name, Iterable<Resource> c) throws DatabaseException {\r
- return createExisting(g, g.newResource(), type, name, c);\r
- }\r
-\r
- public static Resource createExisting(WriteOnlyGraph g, Resource l, Resource type, String name, Iterable<Resource> c) throws DatabaseException {\r
- Layer0 l0 = g.getService(Layer0.class);\r
- g.claim(l, l0.InstanceOf, null, type);\r
- g.claim(l, l0.SubrelationOf, null, l0.HasNext);\r
- g.addLiteral(l, l0.HasName, l0.NameOf, l0.String, name, Bindings.STRING);\r
- Resource invL = g.newResource();\r
- g.claim(invL, l0.SubrelationOf, null, l0.HasPrevious);\r
- g.addLiteral(invL, l0.HasName, l0.NameOf, l0.String, "Inverse", Bindings.STRING);\r
- g.claim(l, l0.InverseOf, l0.InverseOf, invL);\r
- g.claim(l, l0.ConsistsOf, l0.PartOf, invL);\r
- Resource cur = l;\r
- for(Resource r : c) {\r
- g.claim(cur, l, invL, r);\r
- cur = r;\r
- }\r
- g.claim(cur, l, invL, l);\r
- return l;\r
- }\r
- \r
- public static Resource create(WriteOnlyGraph g, Resource type, Resource ... c) throws DatabaseException {\r
- Layer0 l0 = g.getService(Layer0.class);\r
- Resource l = g.newResource();\r
- g.claim(l, l0.InstanceOf, null, type);\r
- g.claim(l, l0.SubrelationOf, null, l0.HasNext);\r
- Resource invL = g.newResource();\r
- g.claim(invL, l0.SubrelationOf, null, l0.HasPrevious);\r
- g.claim(l, l0.InverseOf, l0.InverseOf, invL);\r
- Resource cur = l;\r
- for(Resource r : c) {\r
- g.claim(cur, l, invL, r);\r
- cur = r;\r
- }\r
- g.claim(cur, l, invL, l);\r
- return l;\r
- }\r
-\r
- public static Resource createExisting(WriteGraph g, Resource l, Resource ... c) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(g);\r
- g.claim(l, l0.SubrelationOf, null, l0.HasNext);\r
- Resource invL = g.newResource();\r
- g.claim(invL, l0.SubrelationOf, null, l0.HasPrevious);\r
- g.claim(l, l0.InverseOf, l0.InverseOf, invL);\r
- Resource cur = l;\r
- for(Resource r : c) {\r
- g.claim(cur, l, invL, r);\r
- cur = r;\r
- }\r
- g.claim(cur, l, invL, l);\r
- return l;\r
- }\r
- \r
-// public static Resource create(GraphWriter graph, Resource type, Iterable<Resource> c) throws DatabaseException {\r
-// ReadGraph g = w.getGraph();\r
-// Builtins b = g.getBuiltins();\r
-// Resource l = w.create(type).get();\r
-// w.let(b.SubrelationOf, b.IsRelatedTo);\r
-// w.createInverse(l).let(b.SubrelationOf, g.getInverse(b.IsRelatedTo));\r
-//\r
-// Resource cur = l;\r
-// for(Resource r : c) {\r
-// w.stat(cur, l, r);\r
-// cur = r;\r
-// }\r
-// w.stat(cur, l, l);\r
-// return l;\r
-// }\r
-\r
- public static class OrderedSetIterator implements ListIterator<Resource> {\r
-\r
- ReadGraph g;\r
- Resource l;\r
- Resource prev;\r
- Resource next;\r
- int index;\r
- boolean direction;\r
-\r
- WriteGraph getWriteGraph() {\r
- if (!(g instanceof WriteGraph))\r
- throw new UnsupportedOperationException("");\r
- return (WriteGraph) g;\r
- }\r
-\r
- public OrderedSetIterator(ReadGraph g, Resource l) throws DatabaseException {\r
- this.g = g;\r
- this.l = l;\r
- this.prev = l;\r
- this.next = OrderedSetUtils.next(g, l, l);\r
- this.index = 0;\r
- }\r
-\r
- @Override\r
- public boolean hasNext() {\r
- return !next.equals(l);\r
- }\r
-\r
- @Override\r
- public Resource next() {\r
- prev = next;\r
- try {\r
- next = OrderedSetUtils.next(g, l, next);\r
- } catch (DatabaseException e) {\r
- throw new RuntimeDatabaseException(e);\r
- }\r
- ++index;\r
- direction = true;\r
- return prev;\r
- }\r
-\r
- @Override\r
- public void remove() {\r
- try {\r
- WriteGraph wg = getWriteGraph();\r
- if(direction) {\r
- OrderedSetUtils.remove(wg, l, prev);\r
- prev = OrderedSetUtils.prev(wg, l, next);\r
- }\r
- else {\r
- OrderedSetUtils.remove(wg, l, next);\r
- next = OrderedSetUtils.next(wg, l, prev);\r
- }\r
- } catch (DatabaseException e) {\r
- throw new RuntimeDatabaseException(e);\r
- }\r
- }\r
-\r
- @Override\r
- public void add(Resource e) {\r
- try {\r
- WriteGraph wg = getWriteGraph();\r
- wg.denyStatement(prev, l, next);\r
- wg.claim(prev, l, e);\r
- wg.claim(e, l, next);\r
- prev = e;\r
- } catch (DatabaseException ex) {\r
- throw new RuntimeDatabaseException(ex);\r
- }\r
- }\r
-\r
- @Override\r
- public boolean hasPrevious() {\r
- return !prev.equals(l);\r
- }\r
-\r
- @Override\r
- public int nextIndex() {\r
- return index;\r
- }\r
-\r
- @Override\r
- public Resource previous() {\r
- try {\r
- next = prev;\r
- prev = OrderedSetUtils.prev(g, l, prev);\r
- --index;\r
- direction = false;\r
- return next;\r
- } catch (DatabaseException ex) {\r
- throw new RuntimeDatabaseException(ex);\r
- }\r
- }\r
-\r
- @Override\r
- public int previousIndex() {\r
- return index-1;\r
- }\r
-\r
- @Override\r
- public void set(Resource e) {\r
- try {\r
- WriteGraph wg = getWriteGraph();\r
- if(direction) {\r
- OrderedSetUtils.replace(wg, l, prev, e);\r
- prev = e;\r
- }\r
- else {\r
- OrderedSetUtils.replace(wg, l, next, e);\r
- next = e;\r
- }\r
- } catch (DatabaseException ex) {\r
- throw new RuntimeDatabaseException(ex);\r
- }\r
- }\r
-\r
- }\r
-\r
- public static ListIterator<Resource> iterator(ReadGraph g, Resource l) throws DatabaseException {\r
- return new OrderedSetIterator(g, l);\r
- }\r
-\r
- public static boolean set(WriteGraph g, Resource l, Iterable<Resource> els) throws DatabaseException {\r
-\r
- // Compute delta\r
- Set<Pair<Resource,Resource>> removed = new HashSet<Pair<Resource,Resource>>();\r
- Collection<Pair<Resource,Resource>> added = new ArrayList<Pair<Resource,Resource>>();\r
- Resource cur = l;\r
- do {\r
- Resource temp = next(g, l, cur);\r
- removed.add(new Pair<Resource,Resource>(cur, temp));\r
- cur = temp;\r
- } while(!cur.equals(l));\r
-\r
- cur = l;\r
- for(Resource temp : els) {\r
- Pair<Resource,Resource> pair = new Pair<Resource, Resource>(cur, temp);\r
- if(!removed.remove(pair))\r
- added.add(pair);\r
- cur = temp;\r
- }\r
-\r
- {\r
- Pair<Resource,Resource> pair = new Pair<Resource, Resource>(cur, l);\r
- if(!removed.remove(pair))\r
- added.add(pair);\r
- }\r
-\r
- // Apply\r
- if(added.isEmpty() && removed.isEmpty())\r
- return false;\r
- for(Pair<Resource,Resource> pair : removed)\r
- g.denyStatement(pair.first, l, pair.second);\r
- for(Pair<Resource,Resource> pair : added)\r
- g.claim(pair.first, l, pair.second);\r
- return true;\r
- }\r
-\r
- /**\r
- * Retrieves the owner list the specified list element\r
- * \r
- * @param g\r
- * @param el a possible element of a list of the specified type\r
- * @param listBaseRelation a base relation of the list to look for\r
- * @return\r
- */\r
- public static Resource getSingleOwnerList(ReadGraph g, Resource el, Resource listBaseRelation) throws DatabaseException {\r
- Collection<Resource> result = getOwnerLists(g, el, listBaseRelation);\r
- if (result.size() != 1)\r
- throw new ValidationException(NameUtils.getSafeName(g, el) + " is part of " + result.size() + " lists of base type " + NameUtils.getSafeName(g, listBaseRelation) + ", expected only one list.");\r
- return result.iterator().next();\r
- }\r
-\r
- public static Resource getSingleOwnerList(ReadGraph g, Resource el) throws DatabaseException {\r
- Layer0 l0 = Layer0.getInstance(g);\r
- Collection<Resource> result = getOwnerLists(g, el, l0.OrderedSet);\r
- if (result.size() != 1)\r
- throw new ValidationException(NameUtils.getSafeName(g, el) + " is part of " + result.size() + " lists of base type L0.OrderedSet, expected only one list.");\r
- return result.iterator().next();\r
- }\r
- \r
- public static Collection<Resource> getSubjects(ReadGraph g, Resource object) throws DatabaseException {\r
- Collection<Resource> result = new ArrayList<Resource>(1);\r
- Layer0 l0 = Layer0.getInstance(g);\r
- for(Resource pred : g.getPredicates(object)) {\r
- if(g.isInstanceOf(pred, l0.OrderedSet) && !pred.equals(object))\r
- result.add(pred);\r
- }\r
- return result;\r
- }\r
-\r
- private static void forSubjects(ReadGraph g, Resource object, DbFunction<Resource, Boolean> consumer) throws DatabaseException {\r
- for (Resource pred : g.getPredicates(object)) {\r
- if (!pred.equals(object))\r
- if (!consumer.apply(pred))\r
- break;\r
- }\r
- }\r
-\r
- /**\r
- * Retrieves the owner list the specified list element\r
- * \r
- * @param g\r
- * @param el a possible element of a list of the specified type\r
- * @param listBaseRelation a base relation of the list to look for\r
- * @return\r
- */\r
- public static Collection<Resource> getOwnerLists(ReadGraph g, Resource el, Resource listBaseRelation) throws DatabaseException {\r
- Collection<Resource> result = null;\r
- Collection<Resource> rs = getSubjects(g, el);\r
- for (Resource r : rs) {\r
- if (g.isInstanceOf(r, listBaseRelation)) {\r
- if (result == null)\r
- result = new ArrayList<Resource>(2);\r
- result.add(r);\r
- }\r
- }\r
- if (result == null)\r
- result = Collections.emptyList();\r
- return result;\r
- }\r
-\r
- private static class PossibleOwnerList implements DbFunction<Resource, Boolean> {\r
- private ReadGraph graph;\r
- private final Resource listBaseRelation;\r
- public Layer0 L0;\r
- public Resource result;\r
-\r
- PossibleOwnerList(ReadGraph graph, Resource listBaseRelation) {\r
- this.graph = graph;\r
- this.listBaseRelation = listBaseRelation;\r
- this.L0 = Layer0.getInstance(graph);\r
- }\r
-\r
- @Override\r
- public Boolean apply(Resource t) throws DatabaseException {\r
- Set<Resource> types = graph.getTypes(t);\r
- if (types.contains(L0.OrderedSet) && types.contains(listBaseRelation)) {\r
- if (result != null) {\r
- result = null;\r
- return false;\r
- }\r
- result = t;\r
- }\r
- return true;\r
- }\r
- }\r
-\r
- /**\r
- * Retrieves a possible single owner list the specified list element\r
- * \r
- * @param g\r
- * @param el\r
- * a possible element of a list of the specified type\r
- * @param listBaseRelation\r
- * a base relation of the list to look for\r
- * @return <code>null</code> if there is zero or more than one owner lists\r
- * with specified base relation\r
- */\r
- public static Resource getPossibleOwnerList(ReadGraph g, Resource el, Resource listBaseRelation) throws DatabaseException {\r
- PossibleOwnerList proc = new PossibleOwnerList(g, listBaseRelation);\r
- forSubjects(g, el, proc);\r
- return proc.result;\r
- }\r
-\r
-}\r
+/*******************************************************************************
+ * Copyright (c) 2007, 2018 Association for Decentralized Information Management
+ * in Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * VTT Technical Research Centre of Finland - initial API and implementation
+ *******************************************************************************/
+package org.simantics.db.common.utils;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Set;
+
+import org.simantics.databoard.Bindings;
+import org.simantics.db.AsyncReadGraph;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.WriteGraph;
+import org.simantics.db.WriteOnlyGraph;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.exception.RuntimeDatabaseException;
+import org.simantics.db.exception.ValidationException;
+import org.simantics.db.function.DbFunction;
+import org.simantics.db.procedure.AsyncMultiProcedure;
+import org.simantics.layer0.Layer0;
+import org.simantics.utils.datastructures.Pair;
+
+public class OrderedSetUtils {
+
+ /**
+ * Returns true, if <tt>l</tt> contains the element <tt>el</tt>.
+ */
+ public static boolean contains(ReadGraph g, Resource l, Resource el) throws DatabaseException {
+ return g.hasStatement(el, l) && !l.equals(el);
+ }
+
+ /**
+ * Returns the next element in the ordered set or <tt>l</tt>,
+ * if <tt>el</tt> is the last element. Called for <tt>el</tt>, returns
+ * the first element in the set.
+ */
+ public static Resource next(ReadGraph g, Resource l, Resource el) throws DatabaseException {
+ Collection<Resource> nexts = g.getObjects(el, l);
+ if(nexts.size() != 1)
+ throw new InvalidOrderedSetException("Invalid list element: " + l + " " + el + " " + nexts.size() + " successors.");
+ for(Resource r : nexts)
+ return r;
+ return null;
+ }
+
+ public static void forNext(AsyncReadGraph g, final Resource l, Resource el, final AsyncMultiProcedure<Resource> procedure) {
+ g.forEachObject(el, l, new AsyncMultiProcedure<Resource>() {
+
+ @Override
+ public void exception(AsyncReadGraph graph, Throwable t) {
+ procedure.exception(graph, t);
+ }
+
+ @Override
+ public void finished(AsyncReadGraph graph) {
+ }
+
+ @Override
+ public void execute(AsyncReadGraph graph, Resource nel) {
+ if(!nel.equals(l)) {
+ procedure.execute(graph, nel);
+ forNext(graph, l, nel, procedure);
+ }
+ }
+ });
+// Collection<Resource> nexts = g.getObjects(el, l);
+// if(nexts.size() != 1)
+// throw new NoSingleResultException("Invalid list element: " + nexts.size() + " successors.");
+// for(Resource r : nexts)
+// return r;
+// return null;
+ }
+
+ /**
+ * Returns the previouse element in the ordered set or <tt>l</tt>,
+ * if <tt>el</tt> is the first element. Called for <tt>el</tt>, returns
+ * the last element in the set.
+ */
+ public static Resource prev(ReadGraph g, Resource l, Resource el) throws DatabaseException {
+ Collection<Resource> prevs = g.getObjects(el, g.getInverse(l));
+ if(prevs.size() != 1) {
+ throw new InvalidOrderedSetException("Invalid list element, " + prevs.size() + " predecessors.");
+ }
+ for(Resource r : prevs)
+ return r;
+ return null;
+ }
+
+ /**
+ * Adds a given elements <tt>el</tt> to the list <tt>l</tt>. Returns
+ * true, if the element was really added.
+ */
+ public static boolean add(WriteGraph g, Resource l, Resource el) throws DatabaseException {
+ if(g.hasStatement(el, l))
+ return false;
+ Resource back = prev(g, l, l);
+ g.denyStatement(back, l, l);
+ g.claim(back, l, el);
+ g.claim(el, l, l);
+ return true;
+ }
+
+ /**
+ * Adds a given elements <tt>el</tt> to the list <tt>l</tt>. Returns
+ * true, if the element was really added.
+ */
+ public static boolean addFirst(WriteGraph g, Resource l, Resource el) throws DatabaseException {
+ return addAfter(g, l, l, el);
+ }
+
+ public static boolean addAll(WriteGraph g, Resource l, Iterable<Resource> els) throws DatabaseException {
+ for(Resource r : els)
+ if(g.hasStatement(r, l))
+ return false;
+ Resource cur = prev(g, l, l);
+ g.denyStatement(cur, l, l);
+ for(Resource r : els) {
+ g.claim(cur, l, r);
+ cur = r;
+ }
+ g.claim(cur, l, l);
+ return true;
+ }
+
+ public static boolean addAllNew(WriteGraph g, Resource l, Iterable<Resource> els) throws DatabaseException {
+ Resource cur = prev(g, l, l);
+ Resource inv = g.getInverse(l);
+ g.deny(cur, l, inv, l);
+ for(Resource r : els) {
+ g.claim(cur, l, inv, r);
+ cur = r;
+ }
+ g.claim(cur, l, inv, l);
+ return true;
+ }
+
+ public static boolean addAfter(WriteGraph g, Resource l, Resource pos, Resource el) throws DatabaseException {
+ if(g.hasStatement(el, l))
+ return false;
+ Resource next = next(g, l, pos);
+ g.denyStatement(pos, l, next);
+ g.claim(pos, l, el);
+ g.claim(el, l, next);
+ return true;
+ }
+
+ public static boolean addBefore(WriteGraph g, Resource l, Resource pos, Resource el) throws DatabaseException {
+ if(g.hasStatement(el, l))
+ return false;
+ Resource prev = prev(g, l, pos);
+ g.denyStatement(prev, l, pos);
+ g.claim(prev, l, el);
+ g.claim(el, l, pos);
+ return true;
+ }
+
+ /**
+ * Removes a given elements <tt>el</tt> from the list <tt>l</tt>. Returns
+ * true, if the element was really removed.
+ */
+ public static boolean remove(WriteGraph g, Resource l, Resource el) throws DatabaseException {
+ Collection<Resource> nexts = g.getObjects(el, l);
+ if(nexts.size() == 0)
+ return false;
+ if(nexts.size() != 1)
+ throw new InvalidOrderedSetException("Invalid list element.");
+ Collection<Resource> prevs = g.getObjects(el, g.getInverse(l));
+ if(prevs.size() != 1)
+ throw new InvalidOrderedSetException("Invalid list element.");
+
+ for(Resource p : prevs)
+ for(Resource n : nexts) {
+ g.denyStatement(p, l, el);
+ g.denyStatement(el, l, n);
+ g.claim(p, l, n);
+ return true;
+ }
+ return true;
+ }
+
+ public static List<Resource> removeList(WriteGraph g, Resource l) throws DatabaseException {
+ List<Resource> els = toList(g, l);
+ for(Resource el : els)
+ g.deny(el, l);
+ g.deny(l, l);
+ Resource inv = g.getInverse(l);
+ g.deny(l);
+ g.deny(inv);
+ return els;
+ }
+
+ public static void replace(WriteGraph g, Resource l, Resource oldEl, Resource newEl) throws DatabaseException {
+ Collection<Resource> nexts = g.getObjects(oldEl, l);
+ if(nexts.size() != 1)
+ throw new InvalidOrderedSetException("Invalid list element.");
+ Collection<Resource> prevs = g.getObjects(oldEl, g.getInverse(l));
+ if(prevs.size() != 1)
+ throw new InvalidOrderedSetException("Invalid list element.");
+
+ for(Resource p : prevs)
+ for(Resource n : nexts) {
+ g.denyStatement(p, l, oldEl);
+ g.denyStatement(oldEl, l, n);
+ g.claim(p, l, newEl);
+ g.claim(newEl, l, n);
+ return;
+ }
+ }
+
+ /**
+ * Converts ordered set into a list.
+ */
+ public static List<Resource> toList(ReadGraph g, Resource l) throws DatabaseException {
+ ArrayList<Resource> ret = new ArrayList<Resource>();
+ Resource cur = l;
+ while(true) {
+ cur = next(g, l, cur);
+ if(cur.equals(l))
+ return ret;
+ ret.add(cur);
+ }
+ }
+
+ /**
+ * Creates an empty ordered set.
+ */
+ public static Resource create(WriteOnlyGraph g, Resource type) throws DatabaseException {
+ Layer0 l0 = g.getService(Layer0.class);
+ Resource l = g.newResource();
+ g.claim(l, l0.InstanceOf, null, type);
+ g.claim(l, l0.SubrelationOf, null, l0.HasNext);
+ Resource invL = g.newResource();
+ g.claim(invL, l0.SubrelationOf, null, l0.HasPrevious);
+ g.claim(l, l0.InverseOf, l0.InverseOf, invL);
+ g.claim(l, l, invL, l);
+ return l;
+ }
+
+ /**
+ * Creates an ordered set containing the given elements.
+ * It is assumed that the elements do not contain duplicates.
+ */
+ @Deprecated
+ public static Resource create(WriteOnlyGraph g, Resource type, Iterable<Resource> c) throws DatabaseException {
+ Layer0 l0 = g.getService(Layer0.class);
+ Resource l = g.newResource();
+ g.claim(l, l0.InstanceOf, null, type);
+ g.claim(l, l0.SubrelationOf, null, l0.HasNext);
+ Resource invL = g.newResource();
+ g.claim(invL, l0.SubrelationOf, null, l0.HasPrevious);
+ g.claim(l, l0.InverseOf, l0.InverseOf, invL);
+ Resource cur = l;
+ for(Resource r : c) {
+ g.claim(cur, l, invL, r);
+ cur = r;
+ }
+ g.claim(cur, l, invL, l);
+ return l;
+ }
+
+ public static Resource create(WriteOnlyGraph g, Resource type, String name, Iterable<Resource> c) throws DatabaseException {
+ return createExisting(g, g.newResource(), type, name, c);
+ }
+
+ public static Resource createExisting(WriteOnlyGraph g, Resource l, Resource type, String name, Iterable<Resource> c) throws DatabaseException {
+ Layer0 l0 = g.getService(Layer0.class);
+ g.claim(l, l0.InstanceOf, null, type);
+ g.claim(l, l0.SubrelationOf, null, l0.HasNext);
+ g.addLiteral(l, l0.HasName, l0.NameOf, l0.String, name, Bindings.STRING);
+ Resource invL = g.newResource();
+ g.claim(invL, l0.SubrelationOf, null, l0.HasPrevious);
+ g.addLiteral(invL, l0.HasName, l0.NameOf, l0.String, "Inverse", Bindings.STRING);
+ g.claim(l, l0.InverseOf, l0.InverseOf, invL);
+ g.claim(l, l0.ConsistsOf, l0.PartOf, invL);
+ Resource cur = l;
+ for(Resource r : c) {
+ g.claim(cur, l, invL, r);
+ cur = r;
+ }
+ g.claim(cur, l, invL, l);
+ return l;
+ }
+
+ public static Resource create(WriteOnlyGraph g, Resource type, Resource ... c) throws DatabaseException {
+ Layer0 l0 = g.getService(Layer0.class);
+ Resource l = g.newResource();
+ g.claim(l, l0.InstanceOf, null, type);
+ g.claim(l, l0.SubrelationOf, null, l0.HasNext);
+ Resource invL = g.newResource();
+ g.claim(invL, l0.SubrelationOf, null, l0.HasPrevious);
+ g.claim(l, l0.InverseOf, l0.InverseOf, invL);
+ Resource cur = l;
+ for(Resource r : c) {
+ g.claim(cur, l, invL, r);
+ cur = r;
+ }
+ g.claim(cur, l, invL, l);
+ return l;
+ }
+
+ public static Resource createExisting(WriteGraph g, Resource l, Resource ... c) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(g);
+ g.claim(l, l0.SubrelationOf, null, l0.HasNext);
+ Resource invL = g.newResource();
+ g.claim(invL, l0.SubrelationOf, null, l0.HasPrevious);
+ g.claim(l, l0.InverseOf, l0.InverseOf, invL);
+ Resource cur = l;
+ for(Resource r : c) {
+ g.claim(cur, l, invL, r);
+ cur = r;
+ }
+ g.claim(cur, l, invL, l);
+ return l;
+ }
+
+// public static Resource create(GraphWriter graph, Resource type, Iterable<Resource> c) throws DatabaseException {
+// ReadGraph g = w.getGraph();
+// Builtins b = g.getBuiltins();
+// Resource l = w.create(type).get();
+// w.let(b.SubrelationOf, b.IsRelatedTo);
+// w.createInverse(l).let(b.SubrelationOf, g.getInverse(b.IsRelatedTo));
+//
+// Resource cur = l;
+// for(Resource r : c) {
+// w.stat(cur, l, r);
+// cur = r;
+// }
+// w.stat(cur, l, l);
+// return l;
+// }
+
+ public static class OrderedSetIterator implements ListIterator<Resource> {
+
+ ReadGraph g;
+ Resource l;
+ Resource prev;
+ Resource next;
+ int index;
+ boolean direction;
+
+ WriteGraph getWriteGraph() {
+ if (!(g instanceof WriteGraph))
+ throw new UnsupportedOperationException("");
+ return (WriteGraph) g;
+ }
+
+ public OrderedSetIterator(ReadGraph g, Resource l) throws DatabaseException {
+ this.g = g;
+ this.l = l;
+ this.prev = l;
+ this.next = OrderedSetUtils.next(g, l, l);
+ this.index = 0;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return !next.equals(l);
+ }
+
+ @Override
+ public Resource next() {
+ prev = next;
+ try {
+ next = OrderedSetUtils.next(g, l, next);
+ } catch (DatabaseException e) {
+ throw new RuntimeDatabaseException(e);
+ }
+ ++index;
+ direction = true;
+ return prev;
+ }
+
+ @Override
+ public void remove() {
+ try {
+ WriteGraph wg = getWriteGraph();
+ if(direction) {
+ OrderedSetUtils.remove(wg, l, prev);
+ prev = OrderedSetUtils.prev(wg, l, next);
+ }
+ else {
+ OrderedSetUtils.remove(wg, l, next);
+ next = OrderedSetUtils.next(wg, l, prev);
+ }
+ } catch (DatabaseException e) {
+ throw new RuntimeDatabaseException(e);
+ }
+ }
+
+ @Override
+ public void add(Resource e) {
+ try {
+ WriteGraph wg = getWriteGraph();
+ wg.denyStatement(prev, l, next);
+ wg.claim(prev, l, e);
+ wg.claim(e, l, next);
+ prev = e;
+ } catch (DatabaseException ex) {
+ throw new RuntimeDatabaseException(ex);
+ }
+ }
+
+ @Override
+ public boolean hasPrevious() {
+ return !prev.equals(l);
+ }
+
+ @Override
+ public int nextIndex() {
+ return index;
+ }
+
+ @Override
+ public Resource previous() {
+ try {
+ next = prev;
+ prev = OrderedSetUtils.prev(g, l, prev);
+ --index;
+ direction = false;
+ return next;
+ } catch (DatabaseException ex) {
+ throw new RuntimeDatabaseException(ex);
+ }
+ }
+
+ @Override
+ public int previousIndex() {
+ return index-1;
+ }
+
+ @Override
+ public void set(Resource e) {
+ try {
+ WriteGraph wg = getWriteGraph();
+ if(direction) {
+ OrderedSetUtils.replace(wg, l, prev, e);
+ prev = e;
+ }
+ else {
+ OrderedSetUtils.replace(wg, l, next, e);
+ next = e;
+ }
+ } catch (DatabaseException ex) {
+ throw new RuntimeDatabaseException(ex);
+ }
+ }
+
+ }
+
+ public static ListIterator<Resource> iterator(ReadGraph g, Resource l) throws DatabaseException {
+ return new OrderedSetIterator(g, l);
+ }
+
+ public static boolean set(WriteGraph g, Resource l, Iterable<Resource> els) throws DatabaseException {
+
+ // Compute delta
+ Set<Pair<Resource,Resource>> removed = new HashSet<Pair<Resource,Resource>>();
+ Collection<Pair<Resource,Resource>> added = new ArrayList<Pair<Resource,Resource>>();
+ Resource cur = l;
+ do {
+ Resource temp = next(g, l, cur);
+ removed.add(new Pair<Resource,Resource>(cur, temp));
+ cur = temp;
+ } while(!cur.equals(l));
+
+ cur = l;
+ for(Resource temp : els) {
+ Pair<Resource,Resource> pair = new Pair<Resource, Resource>(cur, temp);
+ if(!removed.remove(pair))
+ added.add(pair);
+ cur = temp;
+ }
+
+ {
+ Pair<Resource,Resource> pair = new Pair<Resource, Resource>(cur, l);
+ if(!removed.remove(pair))
+ added.add(pair);
+ }
+
+ // Apply
+ if(added.isEmpty() && removed.isEmpty())
+ return false;
+ for(Pair<Resource,Resource> pair : removed)
+ g.denyStatement(pair.first, l, pair.second);
+ for(Pair<Resource,Resource> pair : added)
+ g.claim(pair.first, l, pair.second);
+ return true;
+ }
+
+ /**
+ * Retrieves the owner list the specified list element
+ *
+ * @param g
+ * @param el a possible element of a list of the specified type
+ * @param listBaseRelation a base relation of the list to look for
+ * @return
+ */
+ public static Resource getSingleOwnerList(ReadGraph g, Resource el, Resource listBaseRelation) throws DatabaseException {
+ Collection<Resource> result = getOwnerLists(g, el, listBaseRelation);
+ if (result.size() != 1)
+ throw new ValidationException(NameUtils.getSafeName(g, el) + " is part of " + result.size() + " lists of base type " + NameUtils.getSafeName(g, listBaseRelation) + ", expected only one list.");
+ return result.iterator().next();
+ }
+
+ public static Resource getSingleOwnerList(ReadGraph g, Resource el) throws DatabaseException {
+ Layer0 l0 = Layer0.getInstance(g);
+ Collection<Resource> result = getOwnerLists(g, el, l0.OrderedSet);
+ if (result.size() != 1)
+ throw new ValidationException(NameUtils.getSafeName(g, el) + " is part of " + result.size() + " lists of base type L0.OrderedSet, expected only one list.");
+ return result.iterator().next();
+ }
+
+ public static Collection<Resource> getSubjects(ReadGraph g, Resource object) throws DatabaseException {
+ Collection<Resource> result = new ArrayList<Resource>(1);
+ Layer0 l0 = Layer0.getInstance(g);
+ for(Resource pred : g.getPredicates(object)) {
+ if(g.isInstanceOf(pred, l0.OrderedSet) && !pred.equals(object))
+ result.add(pred);
+ }
+ return result;
+ }
+
+ private static void forSubjects(ReadGraph g, Resource object, DbFunction<Resource, Boolean> consumer) throws DatabaseException {
+ for (Resource pred : g.getPredicates(object)) {
+ if (!pred.equals(object))
+ if (!consumer.apply(pred))
+ break;
+ }
+ }
+
+ /**
+ * Retrieves the owner list the specified list element
+ *
+ * @param g
+ * @param el a possible element of a list of the specified type
+ * @param listBaseRelation a base relation of the list to look for
+ * @return
+ */
+ public static Collection<Resource> getOwnerLists(ReadGraph g, Resource el, Resource listBaseRelation) throws DatabaseException {
+ Collection<Resource> result = null;
+ Collection<Resource> rs = getSubjects(g, el);
+ for (Resource r : rs) {
+ if (g.isInstanceOf(r, listBaseRelation)) {
+ if (result == null)
+ result = new ArrayList<Resource>(2);
+ result.add(r);
+ }
+ }
+ if (result == null)
+ result = Collections.emptyList();
+ return result;
+ }
+
+ private static class PossibleOwnerList implements DbFunction<Resource, Boolean> {
+ private ReadGraph graph;
+ private final Resource listBaseRelation;
+ public Layer0 L0;
+ public Resource result;
+
+ PossibleOwnerList(ReadGraph graph, Resource listBaseRelation) {
+ this.graph = graph;
+ this.listBaseRelation = listBaseRelation;
+ this.L0 = Layer0.getInstance(graph);
+ }
+
+ @Override
+ public Boolean apply(Resource t) throws DatabaseException {
+ Set<Resource> types = graph.getTypes(t);
+ if (types.contains(L0.OrderedSet) && types.contains(listBaseRelation)) {
+ if (result != null) {
+ result = null;
+ return false;
+ }
+ result = t;
+ }
+ return true;
+ }
+ }
+
+ /**
+ * Retrieves a possible single owner list the specified list element
+ *
+ * @param g
+ * @param el
+ * a possible element of a list of the specified type
+ * @param listBaseRelation
+ * a base relation of the list to look for
+ * @return <code>null</code> if there is zero or more than one owner lists
+ * with specified base relation
+ */
+ public static Resource getPossibleOwnerList(ReadGraph g, Resource el, Resource listBaseRelation) throws DatabaseException {
+ PossibleOwnerList proc = new PossibleOwnerList(g, listBaseRelation);
+ forSubjects(g, el, proc);
+ return proc.result;
+ }
+
+}