PrivilegesExistValidator extends ConstraintValidatorSupport<PrivilegesExist, Collection<?>> { @Override public boolean isValid(final Collection<?> value, final ConstraintValidatorContext context) { log.trace("Validating privileges exist: {}", value); Set<String> ids = new HashSet<>(); for (Privilege privilege : securitySystem.listPrivileges()) { ids.add(privilege.getId()); } List<Object> missing = new LinkedList<>(); for (Object item : value) { String privilegeId = String.valueOf(item); if (!privilegeId.matches(NamePatternConstants.REGEX_WITH_WILDCARDS)) { context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate( "Invalid privilege id: " + getEscapeHelper().stripJavaEl(privilegeId) + ". " + MESSAGE) .addConstraintViolation(); return false; } if (!ids.contains(item)) { missing.add(getEscapeHelper().stripJavaEl(item.toString())); } } if (missing.isEmpty()) { return true; } context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate("Missing privileges: " + missing) .addConstraintViolation(); return false; } @Inject  PrivilegesExistValidator(final SecuritySystem securitySystem); @Override boolean isValid(final Collection<?> value, final ConstraintValidatorContext context);  }
@Test public void isValid_ignoresJavaElExpression() { ConstraintValidatorContext context = mock(ConstraintValidatorContext.class); when(context.buildConstraintViolationWithTemplate(any())).thenReturn(mock(ConstraintValidatorContext.ConstraintViolationBuilder.class)); assertThat(underTest.isValid(Collections .singleton("dx27e${\"gggggggggggggggggggggggggggggggggggggggggggz\".toString().replace(\"g\", \"q\")}yv5rm"), context), is(false)); verify(context).buildConstraintViolationWithTemplate( "Invalid privilege id: dx27e{\"gggggggggggggggggggggggggggggggggggggggggggz\".toString().replace(\"g\", \"q\")}yv5rm. Only letters, digits, underscores(_), hyphens(-), dots(.), and asterisks(*) are allowed and may not start with underscore or dot."); }
@Test public void isValid_allows_wildcards() { Set<Privilege> validPrivileges = new HashSet<>(); Privilege privilege = mock(Privilege.class); when(privilege.getId()).thenReturn("nx-repository-admin-maven2-maven-public-*"); validPrivileges.add(privilege); when(securitySystem.listPrivileges()).thenReturn(validPrivileges); ConstraintValidatorContext context = mock(ConstraintValidatorContext.class); when(context.buildConstraintViolationWithTemplate(any())) .thenReturn(mock(ConstraintValidatorContext.ConstraintViolationBuilder.class)); assertThat(underTest.isValid(Collections .singleton("nx-repository-admin-maven2-maven-public-*"), context), is(true)); }