View Javadoc
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  
20  package org.apache.myfaces.tobago.internal.component;
21  
22  import org.apache.myfaces.tobago.component.Visual;
23  import org.apache.myfaces.tobago.model.ExpandedState;
24  import org.apache.myfaces.tobago.model.Selectable;
25  import org.apache.myfaces.tobago.model.SelectedState;
26  import org.apache.myfaces.tobago.model.TreeDataModel;
27  import org.apache.myfaces.tobago.model.TreeNodeDataModel;
28  import org.apache.myfaces.tobago.model.TreePath;
29  import org.slf4j.Logger;
30  import org.slf4j.LoggerFactory;
31  
32  import javax.faces.FacesException;
33  import javax.faces.component.ContextCallback;
34  import javax.faces.component.UIComponent;
35  import javax.faces.component.visit.VisitCallback;
36  import javax.faces.component.visit.VisitContext;
37  import javax.faces.context.FacesContext;
38  import javax.faces.model.DataModel;
39  import javax.swing.tree.TreeNode;
40  import java.io.IOException;
41  import java.util.List;
42  
43  /**
44   * Base class for sheet and tree.
45   */
46  public abstract class AbstractUIData extends javax.faces.component.UIData implements Visual {
47  
48    private static final Logger LOG = LoggerFactory.getLogger(AbstractUIData.class);
49  
50    /**
51     * @deprecated Since 2.0.0. The marked concept has been replaced by "selected".
52     */
53    @Deprecated
54    public static final String SUFFIX_MARKED = "marked";
55    public static final String SUFFIX_SELECTED = "selected";
56    public static final String SUFFIX_EXPANDED = "expanded";
57  
58    /**
59     * Only for tree model.
60     */
61    private boolean initialized;
62  
63    /**
64     * Only for tree model, other models come from the parent UIData.
65     */
66    private TreeDataModel dataModel;
67  
68    public boolean isTreeModel() {
69      init();
70      return dataModel != null;
71    }
72  
73    public TreeDataModel getTreeDataModel() {
74      if (isTreeModel()) {
75        return dataModel;
76      } else {
77        LOG.warn("Not a tree model");
78        return null;
79      }
80    }
81  
82    @Override
83    protected DataModel getDataModel() {
84      init();
85  
86      if (dataModel != null) {
87        return dataModel;
88      } else {
89        return super.getDataModel();
90      }
91    }
92  
93    private void init() {
94      if (!initialized) {
95        final Object value = getValue();
96        final boolean showRoot = isShowRoot();
97        createTreeDataModel(value, showRoot);
98  
99        initialized = true;
100     }
101   }
102 
103   /**
104    * @deprecated since Tobago 3.0.0, please use {@link #getSelectable}
105    */
106   public Selectable getSelectableAsEnum() {
107     return getSelectable();
108   }
109 
110   public abstract Selectable getSelectable();
111 
112   /**
113    * Creates the TreeDataModel which should be used.
114    * Override this method to use a custom model for an unsupported tree model.
115    * (Currently Tobago supports {@link TreeNode} out of the box.
116    *
117    * @param value    The reference to the data model
118    *                 (comes from the value attribute of the {@link javax.faces.component.UIData})
119    * @param showRoot comes from the showRoot attribute.
120    */
121   protected void createTreeDataModel(final Object value, final boolean showRoot) {
122     // TODO: use a factory
123     if (value instanceof TreeNode) {
124       dataModel = new TreeNodeDataModel((TreeNode) value, showRoot, getExpandedState());
125     }
126   }
127 
128   @Override
129   public void encodeBegin(final FacesContext context) throws IOException {
130     initialized = false;
131     init();
132     if (dataModel != null) {
133       dataModel.reset();
134     }
135 
136     if (getFirst() >= getRowCount()) {
137       LOG.warn("Illegal paging state detected, first='{}' >= rowCount='{}'. Setting first to 0. "
138           + "This might happen because the data model has changed. "
139           + "You may want to manipulate the sheet state in your application after manipulating the model "
140           + "(e. g. filtering) to avoid this warning.", getFirst(), getRowCount());
141       setFirst(0);
142     }
143 
144     super.encodeBegin(context);
145   }
146 
147   public abstract ExpandedState getExpandedState();
148 
149   public abstract SelectedState getSelectedState();
150 
151   public boolean isRowVisible() {
152     init();
153     if (dataModel != null) {
154       return dataModel.isRowVisible();
155     } else {
156       return super.getDataModel().isRowAvailable();
157     }
158   }
159 
160   public String getRowClientId() {
161     init();
162     return dataModel != null ? dataModel.getRowClientId() : null;
163   }
164 
165   public String getRowParentClientId() {
166     init();
167     return dataModel != null ? dataModel.getRowParentClientId() : null;
168   }
169 
170   public abstract boolean isShowRoot();
171 
172   public boolean isShowRootJunction() {
173     return false;
174   }
175 
176   /**
177    * @return Is the (maximum) number of rows to display set to zero?
178    */
179   public boolean isRowsUnlimited() {
180     return getRows() == 0;
181   }
182 
183   /**
184    * The value describes, if the UIData renderer creates container elements to hold the row information.
185    * This information is important for the TreeNodeRenderer to set the visible state in the output or not.
186    * Typically the Sheet returns true and a Tree returns false, because the sheet renders the HTML TR tags,
187    * the the sheet also is responsible for the visible state.
188    */
189   public boolean isRendersRowContainer() {
190     return false;
191   }
192 
193   @Override
194   public boolean invokeOnComponent(
195       final FacesContext facesContext, final String clientId, final ContextCallback callback)
196       throws FacesException {
197     // we may need setRowIndex on UISheet
198     final int oldRowIndex = getRowIndex();
199     try {
200       final String sheetId = getClientId(facesContext);
201       if (clientId.startsWith(sheetId)) {
202         String idRemainder = clientId.substring(sheetId.length());
203         if (LOG.isDebugEnabled()) {
204           LOG.debug("idRemainder = '" + idRemainder + "'");
205         }
206         if (idRemainder.matches("^:\\d+:.*")) {
207           idRemainder = idRemainder.substring(1);
208           final int idx = idRemainder.indexOf(":");
209           try {
210             final int rowIndex = Integer.parseInt(idRemainder.substring(0, idx));
211             if (LOG.isDebugEnabled()) {
212               LOG.debug("set rowIndex = '" + rowIndex + "'");
213             }
214             setRowIndex(rowIndex);
215           } catch (final NumberFormatException e) {
216             LOG.warn("idRemainder = '" + idRemainder + "'", e);
217           }
218         } else {
219           if (LOG.isDebugEnabled()) {
220             LOG.debug("no match for '^:\\d+:.*'");
221           }
222         }
223       }
224 
225       return super.invokeOnComponent(facesContext, clientId, callback);
226 
227     } finally {
228       // we should reset rowIndex on UISheet
229       setRowIndex(oldRowIndex);
230     }
231   }
232 
233   /**
234    * @return The TreePath of the current row index.
235    */
236   public TreePath getPath() {
237     if (isTreeModel()) {
238       return ((TreeDataModel) getDataModel()).getPath();
239     } else {
240       LOG.warn("Not a tree model");
241       return null;
242     }
243   }
244 
245   /**
246    * @return Is the current row index representing a folder.
247    */
248   public boolean isFolder() {
249     if (isTreeModel()) {
250       return ((TreeDataModel) getDataModel()).isFolder();
251     } else {
252       LOG.warn("Not a tree model");
253       return false;
254     }
255   }
256 
257   public List<Integer> getRowIndicesOfChildren() {
258     if (isTreeModel()) {
259       return dataModel.getRowIndicesOfChildren();
260     } else {
261       LOG.warn("Not a tree model");
262       return null;
263     }
264   }
265 
266   /**
267    * This is, because we need to visit the UIRow for each row, which is not done in the base implementation.
268    */
269   @Override
270   public boolean visitTree(final VisitContext context, final VisitCallback callback) {
271 
272     if (super.visitTree(context, callback)) {
273       return true;
274     }
275 
276     // save the current row index
277     final int oldRowIndex = getRowIndex();
278     // set row index to -1 to process the facets and to get the rowless clientId
279     setRowIndex(-1);
280     // push the Component to EL
281     pushComponentToEL(context.getFacesContext(), this);
282 
283     try {
284       // iterate over the rows
285       int rowsToProcess = getRows();
286       // if getRows() returns 0, all rows have to be processed
287       if (rowsToProcess == 0) {
288         rowsToProcess = getRowCount();
289       }
290       int rowIndex = getFirst();
291       for (int rowsProcessed = 0; rowsProcessed < rowsToProcess; rowsProcessed++, rowIndex++) {
292         setRowIndex(rowIndex);
293         if (!isRowAvailable()) {
294           return false;
295         }
296         // visit the children of every child of the UIData that is an instance of UIColumn
297         for (int i = 0, childCount = getChildCount(); i < childCount; i++) {
298           final UIComponent child = getChildren().get(i);
299           if (child instanceof AbstractUIRow) {
300             if (child.visitTree(context, callback)) {
301               return true;
302             }
303 
304           }
305         }
306       }
307     } finally {
308       // pop the component from EL and restore the old row index
309       popComponentFromEL(context.getFacesContext());
310       setRowIndex(oldRowIndex);
311     }
312 
313     // Return false to allow the visiting to continue
314     return false;
315   }
316 
317 }