KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > za > org > coefficient > util > common > HibernatePager


1 /*
2  * Coefficient - facilitates project based collaboration
3  * Copyright (C) 2003, Dylan Etkin, CSIR icomtek
4  * PO Box 395
5  * Pretoria 0001, RSA
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18  */

19
20 package za.org.coefficient.util.common;
21
22 import za.org.coefficient.core.Constants;
23 import za.org.coefficient.interfaces.Pager;
24
25 import java.util.ArrayList JavaDoc;
26 import java.util.HashMap JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.List JavaDoc;
29
30 /**
31  * DOCUMENT ME!
32  *
33  * @author $author$
34  * @version $Revision: 1.5 $
35  */

36 public class HibernatePager implements Pager, java.io.Serializable JavaDoc {
37     //~ Static fields/initializers =============================================
38

39     private static final String JavaDoc AND = "and";
40     private static final String JavaDoc OR = "or";
41
42     //~ Instance fields ========================================================
43

44     private ArrayList JavaDoc andVals = new ArrayList JavaDoc();
45     private ArrayList JavaDoc orVals = new ArrayList JavaDoc();
46     private ArrayList JavaDoc page = new ArrayList JavaDoc();
47     private Class JavaDoc pagerClass;
48     private String JavaDoc orderByField;
49     private String JavaDoc userQuery;
50     private StringBuffer JavaDoc andConstraints = new StringBuffer JavaDoc("");
51     private StringBuffer JavaDoc fromClause = new StringBuffer JavaDoc("");
52     private StringBuffer JavaDoc orConstraints = new StringBuffer JavaDoc("");
53     private Object JavaDoc[] userValues;
54     private boolean ascending = true;
55     private boolean hasNext = false;
56     private int currentPageNumber = 1;
57     private int pageSize = Constants.MAX_ELEMENTS_PER_PAGE;
58     private int total = 0;
59
60     //~ Constructors ===========================================================
61

62     public HibernatePager() {
63     }
64
65     public HibernatePager(String JavaDoc searchQuery, Object JavaDoc[] values) throws Exception JavaDoc {
66         userQuery = searchQuery;
67         userValues = values;
68         this.initialize();
69     }
70
71     public HibernatePager(String JavaDoc searchQuery, Object JavaDoc[] values, int pageSize)
72         throws Exception JavaDoc {
73         userQuery = searchQuery;
74         userValues = values;
75         this.pageSize = pageSize;
76         this.initialize();
77     }
78
79     public HibernatePager(Class JavaDoc pageClass, String JavaDoc orderByField)
80         throws Exception JavaDoc {
81         this.pagerClass = pageClass;
82         this.orderByField = orderByField;
83         this.initialize();
84     }
85
86     public HibernatePager(Class JavaDoc pageClass, String JavaDoc orderByField,
87         boolean orderByAscending) throws Exception JavaDoc {
88         this.pagerClass = pageClass;
89         this.orderByField = orderByField;
90         this.ascending = orderByAscending;
91         this.initialize();
92     }
93
94     public HibernatePager(Class JavaDoc pageClass, String JavaDoc orderByField, int pageSize)
95         throws Exception JavaDoc {
96         this.pagerClass = pageClass;
97         this.orderByField = orderByField;
98         this.pageSize = pageSize;
99         this.initialize();
100     }
101
102     public HibernatePager(Class JavaDoc pageClass, String JavaDoc orderByField, int pageSize,
103         boolean orderByAscending) throws Exception JavaDoc {
104         this.pagerClass = pageClass;
105         this.orderByField = orderByField;
106         this.ascending = orderByAscending;
107         this.pageSize = pageSize;
108         this.initialize();
109     }
110
111     public HibernatePager(Class JavaDoc pageClass, String JavaDoc orderByField,
112         boolean orderByAscending, HashMap JavaDoc andSearchParams) throws Exception JavaDoc {
113         this.pagerClass = pageClass;
114         this.orderByField = orderByField;
115         this.ascending = orderByAscending;
116         this.setAndSearchParams(andSearchParams);
117     }
118
119     public HibernatePager(Class JavaDoc pageClass, String JavaDoc orderByField,
120         boolean orderByAscending, HashMap JavaDoc andSearchParams,
121         HashMap JavaDoc orSearchParams) throws Exception JavaDoc {
122         this.pagerClass = pageClass;
123         this.orderByField = orderByField;
124         this.ascending = orderByAscending;
125         this.setAndSearchParams(andSearchParams);
126         this.setOrSearchParams(orSearchParams);
127     }
128
129     public HibernatePager(Class JavaDoc pageClass, String JavaDoc orderByField, int pageSize,
130         HashMap JavaDoc andSearchParams) throws Exception JavaDoc {
131         this.pagerClass = pageClass;
132         this.orderByField = orderByField;
133         this.pageSize = pageSize;
134         this.setAndSearchParams(andSearchParams);
135     }
136
137     public HibernatePager(Class JavaDoc pageClass, String JavaDoc orderByField, int pageSize,
138         HashMap JavaDoc andSearchParams, HashMap JavaDoc orSearchParams) throws Exception JavaDoc {
139         this.pagerClass = pageClass;
140         this.orderByField = orderByField;
141         this.pageSize = pageSize;
142         this.setAndSearchParams(andSearchParams);
143         this.setOrSearchParams(orSearchParams);
144     }
145
146     public HibernatePager(Class JavaDoc pageClass, String JavaDoc orderByField, int pageSize,
147         HashMap JavaDoc andSearchParams, boolean orderByAscending) throws Exception JavaDoc {
148         this.pagerClass = pageClass;
149         this.orderByField = orderByField;
150         this.ascending = orderByAscending;
151         this.pageSize = pageSize;
152         this.setAndSearchParams(andSearchParams);
153     }
154
155     public HibernatePager(Class JavaDoc pageClass, String JavaDoc orderByField, int pageSize,
156         HashMap JavaDoc andSearchParams, HashMap JavaDoc orSearchParams,
157         boolean orderByAscending) throws Exception JavaDoc {
158         this.pagerClass = pageClass;
159         this.orderByField = orderByField;
160         this.ascending = orderByAscending;
161         this.pageSize = pageSize;
162         this.setAndSearchParams(andSearchParams);
163         this.setOrSearchParams(orSearchParams);
164     }
165
166     //~ Methods ================================================================
167

168     /**
169      * Use this to constrain the result set by doing a field 'like' value
170      * for the key-value pairs in the hashmap all pairs being And'ed together
171      *
172      * @param searchParams must contain a string key which is the element
173      * name on the class this pager is for and an Object
174      * representing the value of this field to constrain
175      * by. If null it will clear the old params.
176      * @exception exception is thrown if a named element does not exist on
177      * the pager class or if a Hibernate Type can not
178      * be determined for it
179      */

180     public void setAndSearchParams(HashMap JavaDoc searchParams) throws Exception JavaDoc {
181         setSearchParams(searchParams, AND);
182     }
183
184     /**
185      * Returns the current page number
186      * @return is the current page number
187      */

188     public int getCurrentPageNumber() {
189         return currentPageNumber;
190     }
191
192     /**
193      * Use fromElements to add elments to the from portion of the query
194      */

195     public void setFromClauses(HashMap JavaDoc fromElements) throws Exception JavaDoc {
196         fromClause = new StringBuffer JavaDoc();
197         if (fromElements != null) {
198             for (Iterator JavaDoc it = fromElements.keySet()
199                                            .iterator(); it.hasNext();) {
200                 String JavaDoc key = (String JavaDoc) it.next();
201                 String JavaDoc val = (String JavaDoc) fromElements.get(key);
202                 fromClause.append(" , ");
203                 fromClause.append(key);
204                 if (val != null) {
205                     fromClause.append(" in ");
206                     fromClause.append(" objs.");
207                     fromClause.append(val);
208                 }
209             }
210         }
211         this.initialize();
212     }
213
214     public void setFromWhereAndInitialize(HashMap JavaDoc andSearchParams,
215         HashMap JavaDoc orSearchParams, HashMap JavaDoc fromElements) throws Exception JavaDoc {
216         this.setFromClauses(fromElements);
217         this.setAndSearchParams(andSearchParams);
218         this.setOrSearchParams(orSearchParams);
219         this.initialize();
220     }
221
222     /**
223      * Returns the maximum number of pages
224      * @return is the maximum number of pages
225      */

226     public int getMaxPageNumber() {
227         return (int) (Math.ceil(((double) total) / pageSize));
228     }
229
230     /**
231      * Use this to constrain the result set by doing a field 'like' value
232      * for the key-value pairs in the hashmap all pairs being Or'ed together
233      *
234      * @param searchParams must contain a string key which is the element
235      * name on the class this pager is for and an Object
236      * representing the value of this field to constrain
237      * by. If null it will clear the old params.
238      * @exception exception is thrown if a named element does not exist on
239      * the pager class or if a Hibernate Type can not
240      * be determined for it
241      */

242     public void setOrSearchParams(HashMap JavaDoc searchParams) throws Exception JavaDoc {
243         setSearchParams(searchParams, OR);
244     }
245
246     public void setPageSize(int pageSize) {
247         this.pageSize = pageSize;
248     }
249
250     public int getPageSize() {
251         return this.pageSize;
252     }
253
254     public void setQuery(String JavaDoc queryString, Object JavaDoc[] values) {
255         userQuery = queryString;
256         userValues = values;
257         this.initialize();
258     }
259
260     /**
261      * Returns the total number of results found by the query
262      * @returns total # of results
263      */

264     public int getTotalNumberOfResults() {
265         return total;
266     }
267
268     /**
269      * Returns the data in the current page.
270      * @returns The data in the current page.
271      */

272     public List JavaDoc currentPage() {
273         return page;
274     }
275
276     /**
277      * If the submitted page is in range then the pager will jump to that
278      * page otherwise it will stay where it is
279      *
280      * @param pageNumber is the page to move to
281      * @return list containing data for the page
282      */

283     public List JavaDoc goToPage(int pageNumber) {
284         if (pageNumber <= (Math.ceil(((double) total) / pageSize))) {
285             this.performQuery(((pageNumber - 1) * pageSize));
286             currentPageNumber = pageNumber;
287             hasNext = (currentPageNumber * pageSize) < total;
288         }
289
290         return currentPage();
291     }
292
293     /**
294      * Checks whether there is a "next" page of data
295      * @returns True id there a "next" page of data, false otherwise.
296      */

297     public boolean hasNextPage() {
298         return hasNext;
299     }
300
301     /**
302      * Checks whether there is a "previous" page of data
303      * @returns True id there a "previous" page of data, false otherwise.
304      */

305     public boolean hasPreviousPage() {
306         return currentPageNumber != 1;
307     }
308
309     /**
310      * This will start the pager at the beginning of the search set
311      */

312     public void initialize() {
313         this.performQuery(0);
314         hasNext = (currentPageNumber * pageSize) < total;
315     }
316
317     /**
318      * Moves to the next page of data.
319      */

320     public void next() {
321         if (hasNext) {
322             this.performQuery((currentPageNumber * pageSize));
323             currentPageNumber++;
324             hasNext = (currentPageNumber * pageSize) < total;
325         }
326     }
327
328     /**
329      * Moves to the next page of data, and returns the data in that page.
330      * @returns The data in the next page.
331      */

332     public List JavaDoc nextPage() {
333         this.next();
334
335         return this.currentPage();
336     }
337
338     /**
339      * Moves to the previous page of data.
340      */

341     public void previous() {
342         if (hasPreviousPage()) {
343             page.clear();
344             performQuery((pageSize * (currentPageNumber - 1)) - pageSize);
345             currentPageNumber--;
346             hasNext = true;
347         }
348     }
349
350     /**
351      * Moves to the previous page of data, and returns the data in that page.
352      * @returns The data in the previous page.
353      */

354     public List JavaDoc previousPage() {
355         this.previous();
356
357         return this.currentPage();
358     }
359
360     private void setIntoConstraint(boolean and, String JavaDoc addition) {
361         if (and) {
362             andConstraints.append(addition);
363         } else {
364             orConstraints.append(addition);
365         }
366     }
367
368     private void setIntoVals(boolean and, Object JavaDoc val) {
369         if (and) {
370             andVals.add(val);
371         } else {
372             orVals.add(val);
373         }
374     }
375
376     private int getLengthForConstraint(boolean and) {
377         if (and) {
378             return andConstraints.length();
379         } else {
380             return orConstraints.length();
381         }
382     }
383
384     private void setSearchParams(HashMap JavaDoc searchParams, String JavaDoc logicalOperator)
385         throws Exception JavaDoc {
386         boolean and = AND.equals(logicalOperator);
387         if (and) {
388             andConstraints = new StringBuffer JavaDoc("");
389             andVals = new ArrayList JavaDoc();
390         } else {
391             orConstraints = new StringBuffer JavaDoc("");
392             orVals = new ArrayList JavaDoc();
393         }
394
395         if (searchParams != null) {
396             for (Iterator JavaDoc it = searchParams.keySet()
397                                            .iterator(); it.hasNext();) {
398                 String JavaDoc field = (String JavaDoc) it.next();
399                 Object JavaDoc value = searchParams.get(field);
400                 if (getLengthForConstraint(and) != 0) {
401                     if (and) {
402                         andConstraints.append(" and ");
403                     } else {
404                         orConstraints.append(" or ");
405                     }
406                 }
407                 boolean not = false;
408                 String JavaDoc operator = "like";
409                 if (field.startsWith("!")) {
410                     not = true;
411                     field = field.substring(1, field.length());
412                     operator = "!=";
413                 } else if (field.startsWith("<=")) {
414                     operator = "<=";
415                     field = field.substring(2, field.length());
416                 } else if (field.startsWith(">=")) {
417                     operator = ">=";
418                     field = field.substring(2, field.length());
419                 } else if (field.startsWith("<")) {
420                     operator = "<";
421                     field = field.substring(1, field.length());
422                 } else if (field.startsWith(">")) {
423                     operator = ">";
424                     field = field.substring(1, field.length());
425                 }
426
427                 if (value instanceof Boolean JavaDoc) {
428                     if (not) {
429                         setIntoConstraint(and, " objs." + field + " != ? ");
430                     } else {
431                         setIntoConstraint(and, " objs." + field + " = ? ");
432                     }
433                     setIntoVals(and, value);
434                 } else {
435                     if (value == null) {
436                         if (not) {
437                             setIntoConstraint(and,
438                                 " objs." + field + " is not null ");
439                         } else {
440                             setIntoConstraint(and,
441                                 " objs." + field + " is null ");
442                         }
443                     } else {
444                         if(value instanceof String JavaDoc) {
445                             setIntoConstraint(and,
446                                 " upper(objs." + field + ") " + operator + " ? ");
447                             value = ((String JavaDoc)value).toUpperCase();
448                         } else {
449                             setIntoConstraint(and,
450                                 " objs." + field + " " + operator + " ? ");
451                         }
452                         setIntoVals(and, value);
453                     }
454                 }
455             }
456         }
457         this.initialize();
458     }
459
460     private Object JavaDoc[] convertValsToArray() {
461         int i = 0;
462         Object JavaDoc[] oVals = new Object JavaDoc[andVals.size() + orVals.size()];
463         for (Iterator JavaDoc it = andVals.iterator(); it.hasNext(); i++) {
464             Object JavaDoc val = it.next();
465             oVals[i] = val;
466         }
467         for (Iterator JavaDoc it = orVals.iterator(); it.hasNext(); i++) {
468             Object JavaDoc val = it.next();
469             oVals[i] = val;
470         }
471
472         return oVals;
473     }
474
475     private void performQuery(int startElement) {
476         try {
477             Object JavaDoc[] oVals = null;
478             String JavaDoc sql = null;
479             if ((userQuery == null) || (userQuery.length() == 0)) {
480                 oVals = convertValsToArray();
481                 StringBuffer JavaDoc query = new StringBuffer JavaDoc("select objs ");
482                 query.append(" from ");
483                 query.append(pagerClass.getName());
484                 query.append(" as objs");
485                 if (fromClause.length() != 0) {
486                     query.append(fromClause.toString());
487                 }
488                 if (andConstraints.length() != 0) {
489                     query.append(" where ");
490                     query.append(andConstraints.toString());
491                 }
492                 if (orConstraints.length() != 0) {
493                     if (andConstraints.length() == 0) {
494                         query.append(" where ");
495                     } else {
496                         query.append(" and ");
497                     }
498                     query.append(" ( ");
499                     query.append(orConstraints.toString());
500                     query.append(" ) ");
501                 }
502                 query.append(" order by objs.");
503                 query.append(orderByField);
504                 if (!ascending) {
505                     query.append(" desc");
506                 }
507                 sql = query.toString();
508             } else {
509                 sql = userQuery.toString();
510                 oVals = userValues;
511             }
512
513             total = ((Integer JavaDoc)InvokerFactory.getRemoteInvoker()
514                 .invokeMethodOnService("Search", "getPage",
515                                        new Object JavaDoc[]{sql, new Integer JavaDoc(pageSize),
516                                                     new Integer JavaDoc(startElement),
517                                                     oVals, page})).intValue();
518         } catch (Exception JavaDoc e) {
519             System.err.println(
520                 "<< could not execute query from pager for class: "
521                 + pagerClass.getName() + " with orderByField: " + orderByField);
522             e.printStackTrace();
523         }
524     }
525 }
526
Popular Tags