1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package javax.faces.model;
20
21 import java.util.Collection;
22
23 public class CollectionDataModel<E> extends DataModel<E>
24 {
25
26
27 private int _rowIndex = -1;
28 private Collection<E> _data;
29 private E[] _dataArray;
30
31
32 public CollectionDataModel()
33 {
34 super();
35 }
36
37 public CollectionDataModel(Collection<E> collection)
38 {
39 if (collection == null)
40 {
41 throw new NullPointerException("collection");
42 }
43 setWrappedData(collection);
44 }
45
46
47 @Override
48 public int getRowCount()
49 {
50 if (_data == null)
51 {
52 return -1;
53 }
54 return _data.size();
55 }
56
57 @Override
58 public E getRowData()
59 {
60 if (_data == null)
61 {
62 return null;
63 }
64 if (!isRowAvailable())
65 {
66 throw new IllegalArgumentException("row is unavailable");
67 }
68 return _dataArray[_rowIndex];
69 }
70
71 @Override
72 public int getRowIndex()
73 {
74 return _rowIndex;
75 }
76
77 @Override
78 public Object getWrappedData()
79 {
80 return _data;
81 }
82
83 @Override
84 public boolean isRowAvailable()
85 {
86 return _data != null && _rowIndex >= 0 && _rowIndex < _data.size();
87 }
88
89 @Override
90 public void setRowIndex(int rowIndex)
91 {
92 if (rowIndex < -1)
93 {
94 throw new IllegalArgumentException("illegal rowIndex " + rowIndex);
95 }
96 int oldRowIndex = _rowIndex;
97 _rowIndex = rowIndex;
98 if (_data != null && oldRowIndex != _rowIndex)
99 {
100 E data = isRowAvailable() ? getRowData() : null;
101 DataModelEvent event = new DataModelEvent(this, _rowIndex, data);
102 DataModelListener[] listeners = getDataModelListeners();
103 for (int i = 0; i < listeners.length; i++)
104 {
105 listeners[i].rowSelected(event);
106 }
107 }
108 }
109
110 @Override
111 public void setWrappedData(Object data)
112 {
113 if (data == null)
114 {
115 setRowIndex(-1);
116 _data = null;
117 _dataArray = null;
118 }
119 else
120 {
121 _data = (Collection<E>)data;
122 _dataArray = _data.toArray((E[]) new Object[_data.size()]);
123 _rowIndex = -1;
124 setRowIndex(0);
125 }
126 }
127
128 }