View Javadoc
1   /*
2   Copyright (c) 2010 James Ahlborn
3   
4   Licensed under the Apache License, Version 2.0 (the "License");
5   you may not use this file except in compliance with the License.
6   You may obtain a copy of the License at
7   
8       http://www.apache.org/licenses/LICENSE-2.0
9   
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  */
17  
18  package com.healthmarketscience.jackcess.util;
19  
20  import java.io.IOException;
21  import java.util.Arrays;
22  
23  import com.healthmarketscience.jackcess.DataType;
24  import com.healthmarketscience.jackcess.Table;
25  import com.healthmarketscience.jackcess.impl.ColumnImpl;
26  import org.apache.commons.lang.ObjectUtils;
27  
28  /**
29   * Simple concrete implementation of ColumnMatcher which tests for equality.
30   * If initial comparison fails, attempts to coerce the values to a common type
31   * for comparison.
32   *
33   * @author James Ahlborn
34   * @usage _general_class_
35   */
36  public class SimpleColumnMatcher implements ColumnMatcher {
37  
38    public static final SimpleColumnMatcher INSTANCE = new SimpleColumnMatcher();
39  
40    public SimpleColumnMatcher() {
41    }
42  
43    public boolean matches(Table table, String columnName, Object value1,
44                           Object value2)
45    {
46      if(equals(value1, value2)) {
47        return true;
48      }
49  
50      if((value1 != null) && (value2 != null) && 
51         (value1.getClass() != value2.getClass())) {
52  
53        // the values aren't the same type, try coercing them to "internal"
54        // values and try again
55        DataType dataType = table.getColumn(columnName).getType();
56        try {
57          Object internalV1 = ColumnImpl.toInternalValue(dataType, value1);
58          Object internalV2 = ColumnImpl.toInternalValue(dataType, value2);
59          
60          return equals(internalV1, internalV2);
61        } catch(IOException e) {
62          // ignored, just go with the original result
63        }
64      }
65      return false;
66    }
67  
68    /**
69     * Returns {@code true} if the two objects are equal, handling {@code null}
70     * and objects of type {@code byte[]}.
71     */
72    private static boolean equals(Object o1, Object o2)
73    {
74      return (ObjectUtils.equals(o1, o2) || 
75              ((o1 instanceof byte[]) && (o2 instanceof byte[]) &&
76               Arrays.equals((byte[])o1, (byte[])o2)));
77    }
78  
79  }