01: /*
02: * Copyright (c) 2002-2003 by OpenSymphony
03: * All rights reserved.
04: */
05: package com.opensymphony.webwork.util;
06:
07: import com.opensymphony.xwork.Action;
08: import org.apache.commons.logging.LogFactory;
09:
10: import java.util.*;
11:
12: /**
13: * A bean that takes a source and comparator then attempt to sort the source
14: * utilizing the comparator. It is being used in SortIteratorTag.
15: *
16: * @author Rickard �berg (rickard@middleware-company.com)
17: * @author tm_jee ( tm_jee(at)yahoo.co.uk )
18: * @version $Revision: 1417 $
19: * @see com.opensymphony.webwork.views.jsp.iterator.SortIteratorTag
20: */
21: public class SortIteratorFilter extends IteratorFilterSupport implements
22: Iterator, Action {
23:
24: Comparator comparator;
25: Iterator iterator;
26: List list;
27:
28: // Attributes ----------------------------------------------------
29: Object source;
30:
31: public void setComparator(Comparator aComparator) {
32: this .comparator = aComparator;
33: }
34:
35: public List getList() {
36: return list;
37: }
38:
39: // Public --------------------------------------------------------
40: public void setSource(Object anIterator) {
41: source = anIterator;
42: }
43:
44: // Action implementation -----------------------------------------
45: public String execute() {
46: if (source == null) {
47: return ERROR;
48: } else {
49: try {
50: if (!MakeIterator.isIterable(source)) {
51: LogFactory.getLog(
52: SortIteratorFilter.class.getName()).warn(
53: "Cannot create SortIterator for source "
54: + source);
55:
56: return ERROR;
57: }
58:
59: list = new ArrayList();
60:
61: Iterator i = MakeIterator.convert(source);
62:
63: while (i.hasNext()) {
64: list.add(i.next());
65: }
66:
67: // Sort it
68: Collections.sort(list, comparator);
69: iterator = list.iterator();
70:
71: return SUCCESS;
72: } catch (Exception e) {
73: LogFactory.getLog(SortIteratorFilter.class.getName())
74: .warn("Error creating sort iterator.", e);
75:
76: return ERROR;
77: }
78: }
79: }
80:
81: // Iterator implementation ---------------------------------------
82: public boolean hasNext() {
83: return (source == null) ? false : iterator.hasNext();
84: }
85:
86: public Object next() {
87: return iterator.next();
88: }
89:
90: public void remove() {
91: throw new UnsupportedOperationException(
92: "Remove is not supported in SortIteratorFilter.");
93: }
94: }
|