01: /*
02: * Copyright 2006-2007, Unitils.org
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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: package org.unitils.reflectionassert;
17:
18: import java.util.Map;
19: import java.util.Stack;
20:
21: /**
22: * todo javadoc
23: *
24: * @author Tim Ducheyne
25: * @author Filip Neven
26: */
27: public class LenientNumberComparator extends ReflectionComparator {
28:
29: // todo javadoc
30: public LenientNumberComparator(
31: ReflectionComparator chainedComparator) {
32: super (chainedComparator);
33: }
34:
35: // todo javadoc
36: public boolean canHandle(Object left, Object right) {
37: return (left != null && right != null)
38: && (left instanceof Character || left instanceof Number)
39: && (right instanceof Character || right instanceof Number);
40: }
41:
42: // todo javadoc
43: @Override
44: protected Difference doGetDifference(Object left, Object right,
45: Stack<String> fieldStack,
46: Map<TraversedInstancePair, Boolean> traversedInstancePairs) {
47: // check if right and left have same number value (including NaN and Infinity)
48: Double leftDouble = getDoubleValue(left);
49: Double rightDouble = getDoubleValue(right);
50: if (leftDouble.equals(rightDouble)) {
51: return null;
52: }
53: return new Difference("Different primitive values.", left,
54: right, fieldStack);
55: }
56:
57: /**
58: * Gets the double value for the given left Character or Number instance.
59: *
60: * @param object the Character or Number, not null
61: * @return the value as a Double (this way NaN and infinity can be compared)
62: */
63: private Double getDoubleValue(Object object) {
64: if (object instanceof Number) {
65: return ((Number) object).doubleValue();
66: }
67: return (double) ((Character) object).charValue();
68: }
69: }
|