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;
23 * Accessor for mapped collections.
25 * - Getter: returns the collection.
26 * - Adder: adds one item into the collection.
27 * - Remover: removes one item from the collection.
29 * @author Marko Luukkainen <marko.luukkainen@vtt.fi>
33 public class CollectionAccessor<Range,T> implements IRangeAccessor<Range,Collection<T>> {
35 private Method getter;
37 private Method remover;
39 public CollectionAccessor(Method getter, Method adder, Method remover) {
42 this.remover = remover;
45 @SuppressWarnings("unchecked")
46 public java.util.Collection<T> get(Object element) throws MappingException {
48 return (Collection<T>) getter.invoke(element);
49 } catch (IllegalArgumentException e) {
50 throw new MappingException(e);
51 } catch (IllegalAccessException e) {
52 throw new MappingException(e);
53 } catch (InvocationTargetException e) {
54 throw new MappingException(e.getCause());
59 public boolean set(Range element, Collection<T> value)
60 throws MappingException {
61 java.util.Collection<T> current = get(element);
62 Collection<T> adding = new ArrayList<T>();
63 Collection<T> removing = new ArrayList<T>();
65 if (!value.contains(e))
69 if (!current.contains(e))
74 for (T e : removing) {
75 remover.invoke(element, e);
79 adder.invoke(element, e);
81 } catch (IllegalArgumentException e) {
82 throw new MappingException(e);
83 } catch (IllegalAccessException e) {
84 throw new MappingException(e);
85 } catch (InvocationTargetException e) {
86 throw new MappingException(e.getCause());
88 return removing.size() > 0 || adding.size() > 0;