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.*;
19:
20: /**
21: * todo javadoc
22: *
23: * @author Tim Ducheyne
24: * @author Filip Neven
25: */
26: public class LenientOrderCollectionComparator extends
27: CollectionComparator {
28:
29: // todo javadoc
30: public LenientOrderCollectionComparator(
31: ReflectionComparator chainedComparator) {
32: super (chainedComparator);
33: }
34:
35: // todo javadoc
36: @Override
37: protected Difference doGetDifference(Object left, Object right,
38: Stack<String> fieldStack,
39: Map<TraversedInstancePair, Boolean> traversedInstancePairs) {
40: // Convert to list and compare as collection
41: Collection<?> leftCollection = convertToCollection(left);
42: Collection<?> rightCollection = convertToCollection(right);
43:
44: if (leftCollection.size() != rightCollection.size()) {
45: return new Difference(
46: "Different array/collection sizes. Left size: "
47: + leftCollection.size() + ", right size: "
48: + rightCollection.size(), left, right,
49: fieldStack);
50: }
51:
52: // Create copy from which we can remove elements.
53: List<Object> rightCopy = new ArrayList<Object>(rightCollection);
54:
55: for (Object lhsValue : leftCollection) {
56: boolean found = false;
57: Iterator<Object> rhsIterator = rightCopy.iterator();
58: while (rhsIterator.hasNext()) {
59: Object rhsValue = rhsIterator.next();
60:
61: // Compare values using reflection
62: Difference difference = rootComparator.getDifference(
63: lhsValue, rhsValue, new Stack<String>(),
64: traversedInstancePairs);
65: if (difference == null) {
66: rhsIterator.remove();
67: found = true;
68: break;
69: }
70: }
71:
72: if (!found) {
73: return new Difference(
74: "Left value not found in right collection/array. Left value: "
75: + lhsValue, left, right, fieldStack);
76: }
77: }
78: return null;
79: }
80:
81: }
|