1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19 package javax.faces.model;
20
21 /**
22 * see Javadoc of <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/index.html">JSF Specification</a>
23 *
24 * @author Thomas Spiegl (latest modification by $Author: bommel $)
25 * @version $Revision: 1187700 $ $Date: 2011-10-22 07:19:37 -0500 (Sat, 22 Oct 2011) $
26 */
27 public class ArrayDataModel<E> extends DataModel<E>
28 {
29 // FIELDS
30 private int _rowIndex = -1;
31 private E[] _data;
32
33 // CONSTRUCTORS
34 public ArrayDataModel()
35 {
36 super();
37 }
38
39 public ArrayDataModel(E[] array)
40 {
41 if (array == null)
42 throw new NullPointerException("array");
43 setWrappedData(array);
44 }
45
46 // METHODS
47 @Override
48 public int getRowCount()
49 {
50 if (_data == null)
51 {
52 return -1;
53 }
54 return _data.length;
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 _data[_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.length;
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 Object 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 }
118 else
119 {
120 _data = (E[])data;
121 _rowIndex = -1;
122 setRowIndex(0);
123 }
124 }
125
126 }