KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > xdoclet > modules > ojb > model > FieldWithIdComparator


1 package xdoclet.modules.ojb.model;
2
3 /* Copyright 2004-2005 The Apache Software Foundation
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17
18 import java.util.HashMap JavaDoc;
19 import java.util.Comparator JavaDoc;
20
21 /**
22  * Comparator used for sorting collections that compares field names according to the id properties of the corresponding
23  * fields.
24  *
25  * @author <a HREF="mailto:tomdz@users.sourceforge.net">Thomas Dudziak (tomdz@users.sourceforge.net)</a>
26  * @created April 20, 2003
27  */

28 public class FieldWithIdComparator implements Comparator JavaDoc
29 {
30     /**
31      * Contains the actual fields
32      */

33     private HashMap JavaDoc _fields = null;
34
35     /**
36      * Creates a new comparator object.
37      *
38      * @param fields The actual fields
39      */

40     public FieldWithIdComparator(HashMap JavaDoc fields)
41     {
42         _fields = fields;
43     }
44
45     /**
46      * Compares two fields given by their names.
47      *
48      * @param objA The name of the first field
49      * @param objB The name of the second field
50      * @return
51      * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
52      */

53     public int compare(Object JavaDoc objA, Object JavaDoc objB)
54     {
55         String JavaDoc idAStr = ((FieldDescriptorDef)_fields.get(objA)).getProperty("id");
56         String JavaDoc idBStr = ((FieldDescriptorDef)_fields.get(objB)).getProperty("id");
57         int idA;
58         int idB;
59
60         try
61         {
62             idA = Integer.parseInt(idAStr);
63         }
64         catch (Exception JavaDoc ex)
65         {
66             return 1;
67         }
68         try
69         {
70             idB = Integer.parseInt(idBStr);
71         }
72         catch (Exception JavaDoc ex)
73         {
74             return -1;
75         }
76         return idA < idB ? -1 : (idA > idB ? 1 : 0);
77     }
78
79 }
80
Popular Tags