1 /*******************************************************************************
\r
2 * Copyright (c) 2012, 2013 Association for Decentralized Information Management in
\r
4 * All rights reserved. This program and the accompanying materials
\r
5 * are made available under the terms of the Eclipse Public License v1.0
\r
6 * which accompanies this distribution, and is available at
\r
7 * http://www.eclipse.org/legal/epl-v10.html
\r
10 * VTT Technical Research Centre of Finland - initial API and implementation
\r
11 *******************************************************************************/
\r
12 package org.simantics.objmap.graph.rules.range;
\r
14 import java.lang.reflect.InvocationTargetException;
\r
15 import java.lang.reflect.Method;
\r
16 import java.util.ArrayList;
\r
17 import java.util.Collection;
\r
19 import org.simantics.objmap.exceptions.MappingException;
\r
20 import org.simantics.utils.datastructures.Pair;
\r
24 * Accessor for mapped collections.
\r
25 * Uses three methods:
\r
26 * - Getter: returns the collection.
\r
27 * - Adder: adds one item into the collection.
\r
28 * - Remover: removes one item from the collection.
\r
30 * @author Marko Luukkainen <marko.luukkainen@vtt.fi>
\r
34 public class ListAccessor<Range,T> implements IRangeAccessor<Range,Collection<T>> {
\r
36 private Method getter;
\r
37 private Method adder;
\r
38 private Method remover;
\r
40 public ListAccessor(Method getter, Method adder, Method remover) {
\r
41 this.getter = getter;
\r
43 this.remover = remover;
\r
46 @SuppressWarnings("unchecked")
\r
47 public java.util.Collection<T> get(Object element) throws MappingException {
\r
49 return (Collection<T>) getter.invoke(element);
\r
50 } catch (IllegalArgumentException e) {
\r
51 throw new MappingException(e);
\r
52 } catch (IllegalAccessException e) {
\r
53 throw new MappingException(e);
\r
54 } catch (InvocationTargetException e) {
\r
55 throw new MappingException(e);
\r
60 public boolean set(Range element, Collection<T> value)
\r
61 throws MappingException {
\r
62 java.util.Collection<T> current = get(element);
\r
63 Collection<Pair<Integer, T>> adding = new ArrayList<Pair<Integer, T>>();
\r
64 Collection<T> removing = new ArrayList<T>();
\r
65 for (T e : current) {
\r
66 if (!value.contains(e))
\r
71 if (!current.contains(e))
\r
72 adding.add(new Pair<Integer, T>(i, e));
\r
77 for (T e : removing) {
\r
78 remover.invoke(element, e);
\r
81 for (Pair<Integer,T> e : adding) {
\r
82 adder.invoke(element, e.first,e.second);
\r
84 } catch (IllegalArgumentException e) {
\r
85 throw new MappingException(e);
\r
86 } catch (IllegalAccessException e) {
\r
87 throw new MappingException(e);
\r
88 } catch (InvocationTargetException e) {
\r
89 throw new MappingException(e);
\r
91 return removing.size() > 0 || adding.size() > 0;
\r