+ public static boolean synchronizeList(WriteGraph g, Resource element, Resource relation, Resource listType, List<Resource> value, boolean deleteExtraObjects) throws DatabaseException {
+ final Layer0 L0 = Layer0.getInstance(g);
+
+ // Return value
+ boolean modified = false;
+
+ // Get the list - create a new one, if necessary
+ Resource currentList = g.getPossibleObject(element, relation);
+ if (currentList == null) {
+ currentList = ListUtils.create(g, listType);
+ g.claim(element, relation, currentList);
+ modified = true;
+ }
+
+ // Synchronize elements
+ List<Resource> currentNodes = ListUtils.getListNodes(g, currentList);
+ int i = 0, j = 0;
+ while (i < currentNodes.size()) {
+ Resource node = currentNodes.get(i);
+ Resource v = g.getSingleObject(node, L0.List_Element);
+ if (j < value.size() && v.equals(value.get(j))) {
+ i++;
+ j++;
+ }
+ else if (value.indexOf(v) > j) {
+ // Insert new element in the middle
+ insertElementBefore(g, L0, node, value.get(j));
+ modified = true;
+ j++;
+ }
+ else {
+ // Remove deleted element
+ if (deleteExtraObjects) g.deny(v);
+ removeNode(g, L0, node);
+ modified = true;
+ i++;
+ }
+ }
+
+ // Add new elements at end
+ while (j < value.size()) {
+ // Add tailing elements
+ insertElementBefore(g, L0, currentList, value.get(j));
+ modified = true;
+ j++;
+ }
+
+ return modified;
+ }
+
+ private static Resource insertElementBefore(WriteGraph g, final Layer0 L0, Resource node, final Resource val)
+ throws NoSingleResultException, ManyObjectsForFunctionalRelationException, ServiceException {
+ Resource prev = g.getSingleObject(node, L0.List_Previous);
+ g.deny(prev, L0.List_Next, L0.List_Previous, node);
+
+ Resource newNode = g.newResource();
+ g.claim(newNode, L0.InstanceOf, L0.List_Entry);
+ g.claim(prev, L0.List_Next, L0.List_Previous, newNode);
+ g.claim(newNode, L0.List_Next, L0.List_Previous, node);
+ g.claim(newNode, L0.List_Element, val);
+ return newNode;
+ }
+
+ private static void removeNode(WriteGraph g, final Layer0 L0, Resource node)
+ throws NoSingleResultException, ManyObjectsForFunctionalRelationException, ServiceException {
+ Resource prev = g.getSingleObject(node, L0.List_Previous);
+ Resource next = g.getSingleObject(node, L0.List_Next);
+ g.claim(prev, L0.List_Next, L0.List_Previous, next);
+ g.deny(node);
+ }
+