PatchUtil { public static <A, B> Map<A, B> setMap(Map<A, B> instance, Map<A, B> newValues, boolean patch) { if (patch) { if (newValues == null || newValues.size() == 0) { return instance; } } if (instance == null) { instance = new HashMap<>(); } if (patch) { for (Map.Entry<A, B> entry : newValues.entrySet()) { if (entry.getValue() == null || realValue(entry.getValue()) == null) { instance.remove(entry.getKey()); } else { instance.put(entry.getKey(), entry.getValue()); } } } else { instance.clear(); instance.putAll(safe(newValues)); } return instance; }  static boolean set(Object instance, String fieldName, Object value, boolean patch); static Map<A, B> setMap(Map<A, B> instance, Map<A, B> newValues, boolean patch); static T realValue(T value);  }
@Test public void check_a_patch_can_update_a_value() throws Exception { Map<String, String> patch = new HashMap<String, String>() {{ put("a", "2"); }}; PatchUtil.setMap(testObject.getMap(), patch, true); assertThat(testObject.getMap()).containsEntry("a","2").containsEntry("b", "2"); }
@Test public void check_a_patch_can_add_an_entry() throws Exception { Map<String, String> patch = new HashMap<String, String>() {{ put("c", "3"); }}; PatchUtil.setMap(testObject.getMap(), patch, true); assertThat(testObject.getMap()).containsEntry("a","1").containsEntry("b", "2").containsEntry("c", "3"); }
@Test public void check_a_patch_can_remove_a_value_1() throws Exception { Map<String, String> patch = new HashMap<String, String>() {{ put("a", null); }}; PatchUtil.setMap(testObject.getMap(), patch, true); assertThat(testObject.getMap()).hasSize(1); assertThat(testObject.getMap()).containsEntry("b", "2"); }
@Test public void check_a_patch_can_remove_a_value_2() throws Exception { Map<String, String> patch = new HashMap<String, String>() {{ put("a", "null"); }}; PatchUtil.setMap(testObject.getMap(), patch, true); assertThat(testObject.getMap()).hasSize(1); assertThat(testObject.getMap()).containsEntry("b", "2"); }
@Test public void check_an_update_override_everything() throws Exception { Map<String, String> patch = new HashMap<String, String>() {{ put("d", "4"); }}; PatchUtil.setMap(testObject.getMap(), patch, false); assertThat(testObject.getMap()).hasSize(1); assertThat(testObject.getMap()).containsEntry("d", "4"); }