001package ca.uhn.fhir.util; 002 003/*- 004 * #%L 005 * HAPI FHIR - Core Library 006 * %% 007 * Copyright (C) 2014 - 2021 Smile CDR, Inc. 008 * %% 009 * Licensed under the Apache License, Version 2.0 (the "License"); 010 * you may not use this file except in compliance with the License. 011 * You may obtain a copy of the License at 012 * 013 * http://www.apache.org/licenses/LICENSE-2.0 014 * 015 * Unless required by applicable law or agreed to in writing, software 016 * distributed under the License is distributed on an "AS IS" BASIS, 017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 018 * See the License for the specific language governing permissions and 019 * limitations under the License. 020 * #L% 021 */ 022 023import org.hl7.fhir.instance.model.api.IPrimitiveType; 024 025import java.lang.reflect.Field; 026import java.util.function.BiPredicate; 027 028/** 029 * Boolean-value function for comparing two FHIR primitives via <code>.equals()</code> method on the instance 030 * internal values. 031 */ 032public class PrimitiveTypeEqualsPredicate implements BiPredicate { 033 034 /** 035 * Returns true if both bases are of the same type and hold the same values. 036 */ 037 @Override 038 public boolean test(Object theBase1, Object theBase2) { 039 if (theBase1 == null) { 040 return theBase2 == null; 041 } 042 if (theBase2 == null) { 043 return false; 044 } 045 if (!theBase1.getClass().equals(theBase2.getClass())) { 046 return false; 047 } 048 049 for (Field f : theBase1.getClass().getDeclaredFields()) { 050 Class<?> fieldClass = f.getType(); 051 052 if (!IPrimitiveType.class.isAssignableFrom(fieldClass)) { 053 continue; 054 } 055 056 IPrimitiveType<?> val1, val2; 057 058 f.setAccessible(true); 059 try { 060 val1 = (IPrimitiveType<?>) f.get(theBase1); 061 val2 = (IPrimitiveType<?>) f.get(theBase2); 062 } catch (Exception e) { 063 // swallow 064 continue; 065 } 066 067 if (val1 == null && val2 == null) { 068 continue; 069 } 070 071 if (val1 == null || val2 == null) { 072 return false; 073 } 074 075 Object actualVal1 = val1.getValue(); 076 Object actualVal2 = val2.getValue(); 077 078 if (actualVal1 == null && actualVal2 == null) { 079 continue; 080 } 081 if (actualVal1 == null) { 082 return false; 083 } 084 if (!actualVal1.equals(actualVal2)) { 085 return false; 086 } 087 } 088 089 return true; 090 } 091}