KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectstyle > cayenne > query > Ordering


1 /* ====================================================================
2  *
3  * The ObjectStyle Group Software License, version 1.1
4  * ObjectStyle Group - http://objectstyle.org/
5  *
6  * Copyright (c) 2002-2005, Andrei (Andrus) Adamchik and individual authors
7  * of the software. All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in
18  * the documentation and/or other materials provided with the
19  * distribution.
20  *
21  * 3. The end-user documentation included with the redistribution, if any,
22  * must include the following acknowlegement:
23  * "This product includes software developed by independent contributors
24  * and hosted on ObjectStyle Group web site (http://objectstyle.org/)."
25  * Alternately, this acknowlegement may appear in the software itself,
26  * if and wherever such third-party acknowlegements normally appear.
27  *
28  * 4. The names "ObjectStyle Group" and "Cayenne" must not be used to endorse
29  * or promote products derived from this software without prior written
30  * permission. For written permission, email
31  * "andrus at objectstyle dot org".
32  *
33  * 5. Products derived from this software may not be called "ObjectStyle"
34  * or "Cayenne", nor may "ObjectStyle" or "Cayenne" appear in their
35  * names without prior written permission.
36  *
37  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
38  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
39  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
40  * DISCLAIMED. IN NO EVENT SHALL THE OBJECTSTYLE GROUP OR
41  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
43  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
44  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
46  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
47  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
48  * SUCH DAMAGE.
49  * ====================================================================
50  *
51  * This software consists of voluntary contributions made by many
52  * individuals and hosted on ObjectStyle Group web site. For more
53  * information on the ObjectStyle Group, please see
54  * <http://objectstyle.org/>.
55  */

56 package org.objectstyle.cayenne.query;
57
58 import java.io.PrintWriter JavaDoc;
59 import java.io.Serializable JavaDoc;
60 import java.io.StringWriter JavaDoc;
61 import java.util.Collections JavaDoc;
62 import java.util.Comparator JavaDoc;
63 import java.util.List JavaDoc;
64
65 import org.apache.commons.collections.ComparatorUtils;
66 import org.objectstyle.cayenne.exp.Expression;
67 import org.objectstyle.cayenne.util.ConversionUtil;
68 import org.objectstyle.cayenne.util.XMLEncoder;
69 import org.objectstyle.cayenne.util.XMLSerializable;
70
71 /**
72  * Defines a Comparator for Java Beans. Ordering can be used either
73  * to define ORDER BY clause of a query in terms of object properties,
74  * or as a Comparator for in-memory Java Beans sorting.
75  *
76  * @author Andrei Adamchik
77  * @author Craig Miskell
78  */

79 public class Ordering implements Comparator JavaDoc, Serializable JavaDoc, XMLSerializable {
80
81     /**
82      * Symbolic representation of ascending ordering criterion.
83      */

84     public static final boolean ASC = true;
85
86     /**
87      * Symbolic representation of descending ordering criterion.
88      */

89     public static final boolean DESC = false;
90
91     protected Expression sortSpec;
92     protected boolean ascending;
93     protected boolean caseInsensitive;
94
95     /**
96      * Orders a given list of objects, using a List of Orderings
97      * applied according the default iteration order of the Orderings list.
98      * I.e. each Ordering with lower index is more significant than any other
99      * Ordering with higer index. List being ordered is modified in place.
100      */

101     public static void orderList(List JavaDoc objects, List JavaDoc orderings) {
102         Collections.sort(objects, ComparatorUtils.chainedComparator(orderings));
103     }
104
105     public Ordering() {
106     }
107
108     public Ordering(String JavaDoc sortPathSpec, boolean ascending) {
109         this(sortPathSpec, ascending, false);
110     }
111
112     public Ordering(String JavaDoc sortPathSpec, boolean ascending, boolean caseInsensitive) {
113         setSortSpecString(sortPathSpec);
114         this.ascending = ascending;
115         this.caseInsensitive = caseInsensitive;
116     }
117
118     public Ordering(Expression sortExpression, boolean ascending) {
119         this(sortExpression, ascending, false);
120     }
121
122     public Ordering(
123         Expression sortExpression,
124         boolean ascending,
125         boolean caseInsensitive) {
126         setSortSpec(sortExpression);
127         this.ascending = ascending;
128         this.caseInsensitive = caseInsensitive;
129     }
130
131     /**
132      * Sets sortSpec to be an expression represented by string argument.
133      *
134      * @since 1.1
135      */

136     public void setSortSpecString(String JavaDoc sortSpecString) {
137         this.sortSpec =
138             (sortSpecString != null) ? Expression.fromString(sortSpecString) : null;
139     }
140
141     /**
142      * Returns sortSpec string representation.
143      *
144      * @since 1.1
145      */

146     public String JavaDoc getSortSpecString() {
147         return (sortSpec != null) ? sortSpec.toString() : null;
148     }
149
150     /** Returns true if sorting is done in ascending order. */
151     public boolean isAscending() {
152         return ascending;
153     }
154
155     /** Sets <code>ascending</code> property of this Ordering. */
156     public void setAscending(boolean ascending) {
157         this.ascending = ascending;
158     }
159
160     /** Returns true if the sorting is case insensitive */
161     public boolean isCaseInsensitive() {
162         return caseInsensitive;
163     }
164
165     /** Sets <code>caseInsensitive</code> property of this Ordering. */
166     public void setCaseInsensitive(boolean caseInsensitive) {
167         this.caseInsensitive = caseInsensitive;
168     }
169
170     /**
171      * Returns the expression defining a ordering Java Bean property.
172      */

173     public Expression getSortSpec() {
174         return sortSpec;
175     }
176
177     /**
178      * Sets the expression defining a ordering Java Bean property.
179      */

180     public void setSortSpec(Expression sortSpec) {
181         this.sortSpec = sortSpec;
182     }
183
184     /**
185      * Orders the given list of objects according to the ordering that this
186      * object specifies. List is modified in-place.
187      *
188      * @param objects a List of objects to be sorted
189      */

190     public void orderList(List JavaDoc objects) {
191         Collections.sort(objects, this);
192     }
193
194     /**
195      * Comparable interface implementation. Can compare two
196      * Java Beans based on the stored expression.
197      */

198     public int compare(Object JavaDoc o1, Object JavaDoc o2) {
199         Object JavaDoc value1 = sortSpec.evaluate(o1);
200         Object JavaDoc value2 = sortSpec.evaluate(o2);
201
202         // nulls first policy... maybe make this configurable as some DB do
203
if (value1 == null) {
204             return (value2 == null) ? 0 : -1;
205         }
206         else if (value2 == null) {
207             return 1;
208         }
209
210         if (this.caseInsensitive) {
211             // TODO: to upper case should probably be defined as a separate expression type
212
value1 = ConversionUtil.toUpperCase(value1);
213             value2 = ConversionUtil.toUpperCase(value2);
214         }
215
216         int compareResult =
217             ConversionUtil.toComparable(value1).compareTo(
218                 ConversionUtil.toComparable(value2));
219         return (ascending) ? compareResult : -compareResult;
220     }
221
222     /**
223      * Encodes itself as a query ordering.
224      *
225      * @since 1.1
226      */

227     public void encodeAsXML(XMLEncoder encoder) {
228         encoder.print("<ordering");
229
230         if (!ascending) {
231             encoder.print(" descending=\"true\"");
232         }
233
234         if (caseInsensitive) {
235             encoder.print(" ignore-case=\"true\"");
236         }
237
238         encoder.print(">");
239         if (sortSpec != null) {
240             sortSpec.encodeAsXML(encoder);
241         }
242         encoder.println("</ordering>");
243     }
244
245     public String JavaDoc toString() {
246         StringWriter JavaDoc buffer = new StringWriter JavaDoc();
247         PrintWriter JavaDoc pw = new PrintWriter JavaDoc(buffer);
248         XMLEncoder encoder = new XMLEncoder(pw);
249         encodeAsXML(encoder);
250         pw.close();
251         buffer.flush();
252         return buffer.toString();
253     }
254 }
255
Popular Tags