View Javadoc

1   /*
2    * Copyright 2002,2004 The Apache Software Foundation.
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  
17  package org.apache.commons.jelly.tags.util;
18  
19  import java.util.ArrayList;
20  import java.util.Collections;
21  import java.util.List;
22  
23  import org.apache.commons.beanutils.BeanComparator;
24  import org.apache.commons.jelly.JellyTagException;
25  import org.apache.commons.jelly.MissingAttributeException;
26  import org.apache.commons.jelly.TagSupport;
27  import org.apache.commons.jelly.XMLOutput;
28  
29  public class SortTag extends TagSupport {
30  
31      /*** things to sort */
32      private List items;
33      
34      /*** the variable to store the result in */
35      private String var;
36      
37      /*** property of the beans to sort on, if any */
38      private String property;
39      
40      // Tag interface
41      //-------------------------------------------------------------------------
42      public void doTag(final XMLOutput output) throws JellyTagException {
43          if (var == null)
44          {
45              throw new MissingAttributeException("var");
46          }
47          
48          if (items == null) {
49              throw new MissingAttributeException("items");
50          }
51          
52          List sorted = new ArrayList(items);
53          if (property == null) {
54              Collections.sort(sorted);
55          } else {
56              BeanComparator comparator = new BeanComparator(property);
57              Collections.sort(sorted, comparator);
58          }
59          context.setVariable(var, sorted);
60      }
61      
62      /***
63       * Set the items to be sorted
64       * @param newItems some collection
65       */
66      public void setItems(List newItems) {
67          items = newItems;
68      }
69      
70      /***
71       * The variable to hold the sorted collection.
72       * @param newVar the name of the variable.
73       */
74      public void setVar(String newVar) {
75          var = newVar;
76      }
77      
78      public void setProperty(String newProperty)
79      {
80          property = newProperty;
81      }
82  }