| 1 | |
package org.talos.impl; |
| 2 | |
|
| 3 | |
import java.util.Arrays; |
| 4 | |
import java.util.Collection; |
| 5 | |
import java.util.Collections; |
| 6 | |
import java.util.HashMap; |
| 7 | |
import java.util.Map; |
| 8 | |
|
| 9 | |
import org.talos.Container; |
| 10 | |
import org.talos.exception.CloneNotAllowedException; |
| 11 | |
import org.talos.model.NamedObject; |
| 12 | |
|
| 13 | |
|
| 14 | |
|
| 15 | |
|
| 16 | |
|
| 17 | |
|
| 18 | |
|
| 19 | |
|
| 20 | |
|
| 21 | |
|
| 22 | |
public abstract class AbstractContainer<T extends NamedObject> implements |
| 23 | |
Container<T> { |
| 24 | |
|
| 25 | 1199 | protected Map<String, T> elements = new HashMap<String, T>(); |
| 26 | |
|
| 27 | |
|
| 28 | |
|
| 29 | |
|
| 30 | |
|
| 31 | |
|
| 32 | |
protected abstract void remove(T element); |
| 33 | |
|
| 34 | |
|
| 35 | |
|
| 36 | |
|
| 37 | |
|
| 38 | |
|
| 39 | |
|
| 40 | 13 | protected AbstractContainer(Map<String, T> elements) { |
| 41 | 13 | this.elements = elements; |
| 42 | 13 | } |
| 43 | |
|
| 44 | |
|
| 45 | |
|
| 46 | |
|
| 47 | |
|
| 48 | |
|
| 49 | |
|
| 50 | |
|
| 51 | 1186 | protected AbstractContainer(Collection<T> elements) { |
| 52 | 1186 | for (T element : elements) { |
| 53 | 1639 | this.elements.put(element.getName(), element); |
| 54 | |
} |
| 55 | 1186 | } |
| 56 | |
|
| 57 | |
public void remove() { |
| 58 | 28 | for (String key : this.elements.keySet()) { |
| 59 | 30 | remove(elements.get(key)); |
| 60 | |
} |
| 61 | 26 | elements.clear(); |
| 62 | 26 | } |
| 63 | |
|
| 64 | |
public boolean isEmpty() { |
| 65 | 4 | return elements.isEmpty(); |
| 66 | |
} |
| 67 | |
|
| 68 | |
public Collection<T> list() { |
| 69 | 235 | return Collections.unmodifiableCollection(this.elements.values()); |
| 70 | |
} |
| 71 | |
|
| 72 | |
public boolean contains(String name) { |
| 73 | 72 | return this.elements.containsKey(name); |
| 74 | |
} |
| 75 | |
|
| 76 | |
public boolean containsAll(String... names) { |
| 77 | 9 | if (names != null && names.length > 0) { |
| 78 | 8 | return this.elements.keySet().containsAll(Arrays.asList(names)); |
| 79 | |
} else { |
| 80 | 1 | throw new IllegalArgumentException("names can't be empty or null"); |
| 81 | |
} |
| 82 | |
} |
| 83 | |
|
| 84 | |
public T getElement(String name) { |
| 85 | 118 | return this.elements.get(name); |
| 86 | |
} |
| 87 | |
|
| 88 | |
public int size() { |
| 89 | 55 | return elements.size(); |
| 90 | |
} |
| 91 | |
|
| 92 | |
|
| 93 | |
|
| 94 | |
|
| 95 | |
|
| 96 | |
|
| 97 | |
|
| 98 | |
protected T getFirstElement() { |
| 99 | 38 | for (T result : this.elements.values()) { |
| 100 | 37 | return result; |
| 101 | |
} |
| 102 | 1 | return null; |
| 103 | |
} |
| 104 | |
|
| 105 | |
|
| 106 | |
|
| 107 | |
|
| 108 | |
|
| 109 | |
|
| 110 | |
protected void checkCloneAllowed() throws CloneNotAllowedException { |
| 111 | 33 | if (this.size() != 1) { |
| 112 | 5 | throw new CloneNotAllowedException(this.size()); |
| 113 | |
} |
| 114 | 28 | } |
| 115 | |
} |