1 | /* |
2 | * Copyright 2006-2007 the original author or authors. |
3 | * |
4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
5 | * you may not use this file except in compliance with the License. |
6 | * You may obtain a copy of the License at |
7 | * |
8 | * http://www.apache.org/licenses/LICENSE-2.0 |
9 | * |
10 | * Unless required by applicable law or agreed to in writing, software |
11 | * distributed under the License is distributed on an "AS IS" BASIS, |
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13 | * See the License for the specific language governing permissions and |
14 | * limitations under the License. |
15 | */ |
16 | package org.springframework.batch.core.listener; |
17 | |
18 | import java.util.ArrayList; |
19 | import java.util.Collection; |
20 | import java.util.Collections; |
21 | import java.util.Iterator; |
22 | import java.util.List; |
23 | import java.util.TreeSet; |
24 | |
25 | import org.springframework.core.Ordered; |
26 | import org.springframework.core.annotation.AnnotationAwareOrderComparator; |
27 | |
28 | /** |
29 | * @author Dave Syer |
30 | * |
31 | */ |
32 | class OrderedComposite<S> { |
33 | |
34 | private List<S> unordered = new ArrayList<S>(); |
35 | |
36 | @SuppressWarnings("unchecked") |
37 | private Collection<S> ordered = new TreeSet<S>(new AnnotationAwareOrderComparator()); |
38 | |
39 | private List<S> list = new ArrayList<S>(); |
40 | |
41 | /** |
42 | * Public setter for the listeners. |
43 | * |
44 | * @param items |
45 | */ |
46 | public void setItems(List<? extends S> items) { |
47 | unordered.clear(); |
48 | ordered.clear(); |
49 | for (S s : items) { |
50 | add(s); |
51 | } |
52 | } |
53 | |
54 | /** |
55 | * Register additional item. |
56 | * |
57 | * @param item |
58 | */ |
59 | public void add(S item) { |
60 | if (item instanceof Ordered) { |
61 | if (!ordered.contains(item)) { |
62 | ordered.add(item); |
63 | } |
64 | } |
65 | else { |
66 | if (!unordered.contains(item)) { |
67 | unordered.add(item); |
68 | } |
69 | } |
70 | list.clear(); |
71 | list.addAll(ordered); |
72 | list.addAll(unordered); |
73 | } |
74 | |
75 | /** |
76 | * Public getter for the list of items. The {@link Ordered} items come |
77 | * first, followed by any unordered ones. |
78 | * @return an iterator over the list of items |
79 | */ |
80 | public Iterator<S> iterator() { |
81 | return new ArrayList<S>(list).iterator(); |
82 | } |
83 | |
84 | /** |
85 | * Public getter for the list of items in reverse. The {@link Ordered} items come |
86 | * last, after any unordered ones. |
87 | * @return an iterator over the list of items |
88 | */ |
89 | public Iterator<S> reverse() { |
90 | ArrayList<S> result = new ArrayList<S>(list); |
91 | Collections.reverse(result); |
92 | return result.iterator(); |
93 | } |
94 | |
95 | } |