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