| 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.OrderComparator; |
| 26 | import org.springframework.core.Ordered; |
| 27 | |
| 28 | /** |
| 29 | * @author Dave Syer |
| 30 | * |
| 31 | */ |
| 32 | class OrderedComposite { |
| 33 | |
| 34 | private List unordered = new ArrayList(); |
| 35 | |
| 36 | private Collection ordered = new TreeSet(new OrderComparator()); |
| 37 | |
| 38 | private List list = new ArrayList(); |
| 39 | |
| 40 | /** |
| 41 | * Public setter for the listeners. |
| 42 | * |
| 43 | * @param items |
| 44 | */ |
| 45 | public void setItems(Object[] items) { |
| 46 | unordered.clear(); |
| 47 | ordered.clear(); |
| 48 | for (int i = 0; i < items.length; i++) { |
| 49 | add(items[i]); |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * Register additional item. |
| 55 | * |
| 56 | * @param item |
| 57 | */ |
| 58 | public void add(Object item) { |
| 59 | if (item instanceof Ordered) { |
| 60 | if (!ordered.contains(item)) { |
| 61 | ordered.add(item); |
| 62 | } |
| 63 | } |
| 64 | else { |
| 65 | if (!unordered.contains(item)) { |
| 66 | unordered.add(item); |
| 67 | } |
| 68 | } |
| 69 | list.clear(); |
| 70 | list.addAll(ordered); |
| 71 | list.addAll(unordered); |
| 72 | } |
| 73 | |
| 74 | /** |
| 75 | * Public getter for the list of items. The {@link Ordered} items come |
| 76 | * first, followed by any unordered ones. |
| 77 | * @return an iterator over the list of items |
| 78 | */ |
| 79 | public Iterator iterator() { |
| 80 | return new ArrayList(list).iterator(); |
| 81 | } |
| 82 | |
| 83 | /** |
| 84 | * Public getter for the list of items in reverse. The {@link Ordered} items come |
| 85 | * last, after any unordered ones. |
| 86 | * @return an iterator over the list of items |
| 87 | */ |
| 88 | public Iterator reverse() { |
| 89 | ArrayList result = new ArrayList(list); |
| 90 | Collections.reverse(result); |
| 91 | return result.iterator(); |
| 92 | } |
| 93 | |
| 94 | } |