01: package xdoclet.modules.ojb.model;
02:
03: /* Copyright 2004-2005 The Apache Software Foundation
04: *
05: * Licensed under the Apache License, Version 2.0 (the "License");
06: * you may not use this file except in compliance with the License.
07: * You may obtain a copy of the License at
08: *
09: * 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;
19: import java.util.Comparator;
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 {
29: /**
30: * Contains the actual fields
31: */
32: private HashMap _fields = null;
33:
34: /**
35: * Creates a new comparator object.
36: *
37: * @param fields The actual fields
38: */
39: public FieldWithIdComparator(HashMap fields) {
40: _fields = fields;
41: }
42:
43: /**
44: * Compares two fields given by their names.
45: *
46: * @param objA The name of the first field
47: * @param objB The name of the second field
48: * @return
49: * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
50: */
51: public int compare(Object objA, Object objB) {
52: String idAStr = ((FieldDescriptorDef) _fields.get(objA))
53: .getProperty("id");
54: String idBStr = ((FieldDescriptorDef) _fields.get(objB))
55: .getProperty("id");
56: int idA;
57: int idB;
58:
59: try {
60: idA = Integer.parseInt(idAStr);
61: } catch (Exception ex) {
62: return 1;
63: }
64: try {
65: idB = Integer.parseInt(idBStr);
66: } catch (Exception ex) {
67: return -1;
68: }
69: return idA < idB ? -1 : (idA > idB ? 1 : 0);
70: }
71:
72: }
|