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.xml;
18  
19  import org.apache.commons.jelly.JellyTagException;
20  import org.apache.commons.jelly.XMLOutput;
21  import org.apache.commons.jelly.MissingAttributeException;
22  import org.apache.commons.jelly.xpath.XPathComparator;
23  import org.apache.commons.jelly.xpath.XPathTagSupport;
24  import org.jaxen.XPath;
25  import org.jaxen.JaxenException;
26  
27  import java.util.List;
28  import java.util.Collections;
29  
30  /*** A tag that can sort a list of xml nodes via an xpath expression.
31    *
32    * @author <a href="mailto:jason@jhorman.org">Jason Horman</a>
33    * @version $Id: SortTag.java 155420 2005-02-26 13:06:03Z dirkv $
34    */
35  
36  public class SortTag extends XPathTagSupport {
37  
38      /*** The list to sort */
39      private List list = null;
40  
41      /*** Xpath comparator for sorting */
42      private XPathComparator xpCmp = null;
43  
44      public void doTag(XMLOutput output) throws MissingAttributeException, JellyTagException {
45          if (xpCmp == null) {
46              throw new MissingAttributeException( "xpCmp" );
47          }
48          if (list == null) {
49              throw new MissingAttributeException( "list" );
50          }
51  
52          Collections.sort(list, xpCmp);
53      }
54  
55      /*** Set the list to sort. */
56      public void setList(List list) {
57          this.list = list;
58      }
59  
60      /*** Sets the xpath expression to use to sort selected nodes.
61       */
62      public void setSort(XPath sortXPath) throws JaxenException {
63          if (xpCmp == null) xpCmp = new XPathComparator();
64          xpCmp.setXpath(sortXPath);
65      }
66  
67      /***
68       * Set whether to sort ascending or descending.
69       */
70      public void setDescending(boolean descending) {
71          if (xpCmp == null) xpCmp = new XPathComparator();
72          xpCmp.setDescending(descending);
73      }
74  }