ReplaceMultiValues implements Action { @Override public String doAction(@Nonnull Resource resource) throws PersistenceException { ModifiableValueMap properties = resource.adaptTo(ModifiableValueMap.class); if (properties != null) { String[] currentValues = properties.get(name, String[].class); List<String> valuesList = new ArrayList<>(); if (currentValues != null && currentValues.length > 0) { Collections.addAll(valuesList, currentValues); } String warning = (oldValues.length != newValues.length) ? "WARNING: old values and new values length mismatch (old: " + Arrays.toString(oldValues) + " , new: " + Arrays.toString(newValues) + ")" + " -> the smaller length will be considered\n" : ""; for (int i = 0; i < oldValues.length && i < newValues.length; i++) { Collections.replaceAll(valuesList, oldValues[i], newValues[i]); } properties.put(name, valuesList.toArray(new String[] {})); return warning + "Replacing values " + Arrays.toString(oldValues) + " with values " + Arrays.toString(newValues) + " for multi-value property " + name + ": " + Arrays.toString(currentValues) + " results in " + valuesList + " for resource " + resource.getPath(); } return "WARNING: could not get ModifiableValueMap for resource " + resource.getPath(); } ReplaceMultiValues(@Nonnull String name, @Nonnull String[] oldValues, @Nonnull String[] newValues); @Override String doAction(@Nonnull Resource resource);  }
@Test public void doAction() throws PersistenceException { ReplaceMultiValues action = new ReplaceMultiValues(ATTR, new String[] {VAL1, VAL2}, new String[] {VAL3, VAL4}); action.doAction(resource); verify(valueMap, times(1)).put(ATTR, new String[] {}); }
@Test public void doAction_existingAttribute() throws PersistenceException { when(valueMap.get(ATTR, String[].class)).thenReturn(new String[] {VAL5, VAL2}); ReplaceMultiValues action = new ReplaceMultiValues(ATTR, new String[] {VAL1, VAL2}, new String[] {VAL3, VAL4}); action.doAction(resource); verify(valueMap, times(1)).put(ATTR, new String[] {VAL5, VAL4}); }
@Test public void doAction_existingAttribute2() throws PersistenceException { when(valueMap.get(ATTR, String[].class)).thenReturn(new String[] {VAL1, VAL2, VAL5}); ReplaceMultiValues action = new ReplaceMultiValues(ATTR, new String[] {VAL1, VAL2}, new String[] {VAL3, VAL4}); action.doAction(resource); verify(valueMap, times(1)).put(ATTR, new String[] {VAL3, VAL4, VAL5}); }