下面列出了怎么用javax.validation.groups.Default的API类实例代码及写法,或者点击链接到github查看源代码。
@PostMapping
protected String createNewCreds(Principal user,
@ModelAttribute("newCreds") @Validated(value = { Default.class, CredentialCreateChecks.class }) CredentialsCommand cc,
BindingResult br, RedirectAttributes redirectAttributes, ModelMap map) {
if (br.hasErrors()) {
map.addAttribute("open_CreateCredsDialog", true);
return "credentialsSettings";
}
UserCredential uc = new UserCredential(user.getName(), cc.getUsername(), cc.getCredential(), cc.getEncoder(), cc.getApp(), "Created by user", cc.getExpirationInstant());
if (!APPS_CREDS_SETTINGS.get(uc.getApp()).getUsernameRequired()) {
uc.setAppUsername(user.getName());
}
boolean success = true;
if (!securityService.createCredential(uc)) {
LOG.warn("Could not create creds for user {}", user.getName());
success = false;
}
redirectAttributes.addFlashAttribute("settings_toast", success);
return "redirect:credentialsSettings.view";
}
@Test
public void credCreation_correct() {
CredentialsCommand cc = new CredentialsCommand("username", "bcrypt", App.AIRSONIC, null, null, null, null, null);
cc.setCredential("c");
cc.setConfirmCredential("c");
assertThat(v.validate(cc, Default.class, CredentialCreateChecks.class)).isEmpty();
cc.setEncoder("legacyhex");
assertThat(v.validate(cc, Default.class, CredentialCreateChecks.class)).isEmpty();
cc.setEncoder("noop");
assertThat(v.validate(cc, Default.class, CredentialCreateChecks.class)).isEmpty();
cc.setApp(App.LASTFM);
assertThat(v.validate(cc, Default.class, CredentialCreateChecks.class)).isEmpty();
}
/**
* 校验多个属性,有一个失败即为失败
*
* @param obj
* @param propertyNames
* @param <T>
* @return
*/
public static <T> ValidationResult validatePropertys(T obj, String... propertyNames) {
ValidationResult result = new ValidationResult();
result.setHasErrors(false);
if (propertyNames != null) {
Set<ConstraintViolation<T>> set;
for (String name : propertyNames) {
set = validator.validateProperty(obj, name, Default.class);
if (set != null && !set.isEmpty()) {
Map<String, String> errorMsg = new HashMap<>();
for (ConstraintViolation<T> cv : set) {
errorMsg.put(name, cv.getMessage());
}
result.setErrorMsg(errorMsg);
result.setHasErrors(true);
break;
}
}
}
return result;
}
@Override
public <T> void beforeMethodInvoke(SwaggerInvocation invocation, SwaggerProducerOperation producerOperation,
Object[] args)
throws ConstraintViolationException {
if (paramValidationEnabled.get()) {
if (null == executableValidator) {
ValidatorFactory factory =
Validation.byDefaultProvider()
.configure()
.parameterNameProvider(new DefaultParameterNameProvider())
.messageInterpolator(messageInterpolator())
.buildValidatorFactory();
executableValidator = factory.getValidator().forExecutables();
}
Set<ConstraintViolation<Object>> violations =
executableValidator.validateParameters(producerOperation.getProducerInstance(),
producerOperation.getProducerMethod(),
args,
Default.class);
if (violations.size() > 0) {
LOGGER.warn("Parameter validation failed : " + violations.toString());
throw new ConstraintViolationException(violations);
}
}
}
private Set<Violation> doValidate(Extension extension) {
ListResult<Extension> result = getDataManager().fetchAll(Extension.class);
ExtensionWithDomain target = new ExtensionWithDomain(extension, result.getItems());
final Set<ConstraintViolation<ExtensionWithDomain>> constraintViolations =
getValidator().validate(target, Default.class, AllValidations.class);
if (!constraintViolations.isEmpty()) {
throw new ConstraintViolationException(constraintViolations);
}
Set<ConstraintViolation<ExtensionWithDomain>> warnings =
getValidator().validate(target, NonBlockingValidations.class);
return warnings.stream()
.map(Violation.Builder::fromConstraintViolation)
.collect(Collectors.toSet());
}
@Deprecated
private void verifyByVersion(Map<String, Object> result) throws T212FormatException {
List<Class> groups = new ArrayList<>();
groups.add(Default.class);
groups.add(T212MapLevelGroup.DataLevel.class);
int flag = 0;
T212Map t212Map;
if(result.containsKey(DataElement.Flag.name())){
String f = (String) result.get(DataElement.Flag.name());
flag = Integer.valueOf(f);
}
if(DataFlag.V0.isMarked(flag)){
t212Map = T212Map.create2017(result);
}else{
t212Map = T212Map.create2005(result);
}
if(DataFlag.D.isMarked(flag)){
groups.add(ModeGroup.UseSubPacket.class);
}
Set<ConstraintViolation<T212Map>> constraintViolationSet = validator.validate(t212Map,groups.toArray(new Class[]{}));
if(!constraintViolationSet.isEmpty()) {
create_format_exception(constraintViolationSet,result);
}
}
@Deprecated
private void verifyByVersion(Map<String, String> result) throws T212FormatException {
List<Class> groups = new ArrayList<>();
groups.add(Default.class);
groups.add(T212MapLevelGroup.DataLevel.class);
int flag = 0;
T212Map t212Map;
if(result.containsKey(DataElement.Flag.name())){
String f = result.get(DataElement.Flag.name());
flag = Integer.valueOf(f);
}
if(DataFlag.V0.isMarked(flag)){
t212Map = T212Map.create2017(result);
}else{
t212Map = T212Map.create2005(result);
}
if(DataFlag.D.isMarked(flag)){
groups.add(ModeGroup.UseSubPacket.class);
}
Set<ConstraintViolation<T212Map>> constraintViolationSet = validator.validate(t212Map,groups.toArray(new Class[]{}));
if(!constraintViolationSet.isEmpty()) {
create_format_exception(constraintViolationSet,result);
}
}
private void verify(Data result) throws T212FormatException {
List<Class> groups = new ArrayList<>();
groups.add(Default.class);
if(DataFlag.V0.isMarked(result.getDataFlag())){
groups.add(VersionGroup.V2017.class);
}else{
groups.add(VersionGroup.V2005.class);
}
if(DataFlag.D.isMarked(result.getDataFlag())){
groups.add(ModeGroup.UseSubPacket.class);
}
Set<ConstraintViolation<Data>> constraintViolationSet =
validator.validate(result,groups.toArray(new Class[]{}));
if(!constraintViolationSet.isEmpty()) {
if(THROW_ERROR_VERIFICATION_FAILED.enabledIn(verifyFeature)){
create_format_exception(constraintViolationSet,result);
}else{
//TODO set context
}
}
}
@Test
public void testDataLevelFalse(){
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Map m = dataLevel.entrySet()
.stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
kv -> kv.getValue() + "---------------"
));
T212Map t212Map = T212Map.createDataLevel(m);
Set<ConstraintViolation<T212Map>> e2005 = validator.validate(t212Map,Default.class,
VersionGroup.V2005.class);
assertTrue(e2005.size() > 0);
Set<ConstraintViolation<T212Map>> e2017 = validator.validate(t212Map,Default.class,
VersionGroup.V2017.class);
assertTrue(e2017.size() > 0);
}
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception {
String methodClassName = clazz.getName() + "$" + toUpperMethoName(methodName);
Class<?> methodClass = null;
try {
methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader());
} catch (ClassNotFoundException e) {
}
Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>();
Method method = clazz.getMethod(methodName, parameterTypes);
Object parameterBean = getMethodParameterBean(clazz, method, arguments);
if (parameterBean != null) {
if (methodClass != null) {
violations.addAll(validator.validate(parameterBean, Default.class, clazz, methodClass));
} else {
violations.addAll(validator.validate(parameterBean, Default.class, clazz));
}
}
for (Object arg : arguments) {
validate(violations, arg, clazz, methodClass);
}
if (violations.size() > 0) {
throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations);
}
}
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception {
String methodClassName = clazz.getName() + "$" + toUpperMethoName(methodName);
Class<?> methodClass = null;
try {
methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader());
} catch (ClassNotFoundException e) {
}
Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>();
Method method = clazz.getMethod(methodName, parameterTypes);
Object parameterBean = getMethodParameterBean(clazz, method, arguments);
if (parameterBean != null) {
if (methodClass != null) {
violations.addAll(validator.validate(parameterBean, Default.class, clazz, methodClass));
} else {
violations.addAll(validator.validate(parameterBean, Default.class, clazz));
}
}
for (Object arg : arguments) {
validate(violations, arg, clazz, methodClass);
}
if (violations.size() > 0) {
throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations);
}
}
@Test
public void shouldAddExtraLoggingDetailsForClientDataValidationError() {
ConstraintViolation<Object> violation1 = setupConstraintViolation(SomeValidatableObject.class, "path.to.violation1", NotNull.class, "MISSING_EXPECTED_CONTENT");
ConstraintViolation<Object> violation2 = setupConstraintViolation(Object.class, "path.to.violation2", NotEmpty.class, "TYPE_CONVERSION_ERROR");
ClientDataValidationError ex = new ClientDataValidationError(
Arrays.asList(new SomeValidatableObject("someArg1", "someArg2"), new Object()),
Arrays.asList(violation1, violation2),
new Class<?>[] {Default.class, SomeValidationGroup.class}
);
List<Pair<String, String>> extraLoggingDetails = new ArrayList<>();
listener.processClientDataValidationError(ex, extraLoggingDetails);
assertThat(extraLoggingDetails, containsInAnyOrder(
Pair.of("client_data_validation_failed_objects", SomeValidatableObject.class.getName() + "," + Object.class.getName()),
Pair.of("validation_groups_considered", Default.class.getName() + "," + SomeValidationGroup.class.getName()),
Pair.of("constraint_violation_details",
"SomeValidatableObject.path.to.violation1|javax.validation.constraints.NotNull|MISSING_EXPECTED_CONTENT,Object.path.to.violation2|org.hibernate.validator.constraints" +
".NotEmpty|TYPE_CONVERSION_ERROR"))
);
}
@Test
public void testDefaultGroupDisable() throws Exception {
final Injector injector = Guice.createInjector(new ValidationModule()
.strictGroupsDeclaration());
final Service service = injector.getInstance(Service.class);
// default group not applied - no validation errors
service.call(new Model("sample", null, null));
// verify default group would fail
injector.getInstance(ValidationContext.class).doWithGroups(new GroupAction<Object>() {
@Override
public Object call() throws Throwable {
try {
service.call(new Model("sample", null, null));
} catch (ConstraintViolationException ex) {
Set<String> props = PropFunction.convert(ex.getConstraintViolations());
Assert.assertEquals(1, props.size());
Assert.assertEquals(Sets.newHashSet("def"), props);
}
return null;
}
}, Default.class);
}
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception {
String methodClassName = clazz.getName() + "$" + toUpperMethoName(methodName);
Class<?> methodClass = null;
try {
methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader());
} catch (ClassNotFoundException e) {
}
Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>();
Method method = clazz.getMethod(methodName, parameterTypes);
Object parameterBean = getMethodParameterBean(clazz, method, arguments);
if (parameterBean != null) {
if (methodClass != null) {
violations.addAll(validator.validate(parameterBean, Default.class, clazz, methodClass));
} else {
violations.addAll(validator.validate(parameterBean, Default.class, clazz));
}
}
for (Object arg : arguments) {
validate(violations, arg, clazz, methodClass);
}
if (violations.size() > 0) {
throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations);
}
}
@Override
public void accept(Object value) {
Validator validator = beanValidation.getValidator();
Class[] groups = this.validationGroups;
if (groups == null || groups.length == 0) {
groups = new Class[]{Default.class, UiComponentChecks.class};
}
@SuppressWarnings("unchecked")
Set<ConstraintViolation> violations = validator.validateValue(beanClass, beanProperty, value, groups);
if (!violations.isEmpty()) {
List<CompositeValidationException.ViolationCause> causes = new ArrayList<>(violations.size());
for (ConstraintViolation violation : violations) {
causes.add(new BeanPropertyValidator.BeanValidationViolationCause(violation));
}
String validationMessage = this.validationErrorMessage;
if (validationMessage == null) {
validationMessage = getDefaultErrorMessage();
}
throw new CompositeValidationException(validationMessage, causes);
}
}
public void validate(Class clazz, String methodName, Class<?>[] parameterTypes, Object[] arguments)
throws Exception {
String methodClassName = clazz.getName() + "_" + toUpperMethoName(methodName);
Class<?> methodClass = null;
try {
methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader());
} catch (ClassNotFoundException e) {
}
Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>();
Method method = clazz.getMethod(methodName, parameterTypes);
Object parameterBean = getMethodParameterBean(clazz, method, arguments);
if (parameterBean != null) {
if (methodClass != null) {
violations.addAll(validator.validate(parameterBean, Default.class, clazz, methodClass));
} else {
violations.addAll(validator.validate(parameterBean, Default.class, clazz));
}
}
for (Object arg : arguments) {
validate(violations, arg, clazz, methodClass);
}
if (violations.size() > 0) {
throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: "
+ methodName + ", cause: " + violations, violations);
}
}
@PutMapping
protected String updateCreds(Principal user,
@ModelAttribute("command") @Validated(value = { Default.class, CredentialUpdateChecks.class }) CredentialsManagementCommand cmc,
BindingResult br, RedirectAttributes redirectAttributes) {
if (br.hasErrors()) {
return "credentialsSettings";
}
List<Boolean> failures = new ArrayList<>();
List<UserCredential> creds = securityService.getCredentials(user.getName(), App.values());
cmc.getCredentials().forEach(c -> {
creds.parallelStream().filter(sc -> StringUtils.equals(String.valueOf(sc.hashCode()), c.getHash()))
.findAny().ifPresent(dbCreds -> {
if (c.getMarkedForDeletion()) {
if (!securityService.deleteCredential(dbCreds)) {
LOG.warn("Could not delete creds for user {}", dbCreds.getUsername());
failures.add(true);
}
} else {
UserCredential newCreds = new UserCredential(dbCreds);
newCreds.setEncoder(c.getEncoder());
newCreds.setExpiration(c.getExpirationInstant());
if (!securityService.updateCredentials(dbCreds, newCreds, "User updated", false)) {
LOG.warn("Could not update creds for user {}", dbCreds.getUsername());
failures.add(true);
}
}
});
});
redirectAttributes.addFlashAttribute("settings_toast", failures.isEmpty());
return "redirect:credentialsSettings.view";
}
@Test
public void credCreation_emptyUser() {
CredentialsCommand cc = new CredentialsCommand(null, "bcrypt", App.AIRSONIC, null, null, null, null, null);
cc.setCredential("c");
cc.setConfirmCredential("c");
assertThat(v.validate(cc, Default.class, CredentialCreateChecks.class)).isNotEmpty();
cc.setUsername(" ");
assertThat(v.validate(cc, Default.class, CredentialCreateChecks.class)).isNotEmpty();
}
@Test
public void credCreation_mismatchedPasswords() {
CredentialsCommand cc = new CredentialsCommand("username", "bcrypt", App.AIRSONIC, null, null, null, null, null);
cc.setCredential("c");
cc.setConfirmCredential("p");
assertThat(v.validate(cc, Default.class, CredentialCreateChecks.class)).isNotEmpty();
}
@Test
public void credCreation_emptyPassword() {
CredentialsCommand cc = new CredentialsCommand("username", "bcrypt", App.AIRSONIC, null, null, null, null, null);
assertThat(v.validate(cc, Default.class, CredentialCreateChecks.class)).isNotEmpty();
cc.setCredential(" ");
cc.setConfirmCredential(" ");
assertThat(v.validate(cc, Default.class, CredentialCreateChecks.class)).isNotEmpty();
}
@Test
public void credCreation_unknownApp() {
CredentialsCommand cc = new CredentialsCommand("username", "bcrypt", null, null, null, null, null, null);
cc.setCredential("c");
cc.setConfirmCredential("c");
assertThat(v.validate(cc, Default.class, CredentialCreateChecks.class)).isNotEmpty();
}
@Test
public void credCreation_unknownEncoder() {
CredentialsCommand cc = new CredentialsCommand("username", "bcrypt2", App.AIRSONIC, null, null, null, null, null);
cc.setCredential("c");
cc.setConfirmCredential("c");
assertThat(v.validate(cc, Default.class, CredentialCreateChecks.class)).isNotEmpty();
cc.setEncoder(null);
assertThat(v.validate(cc, Default.class, CredentialCreateChecks.class)).isNotEmpty();
}
@Test
public void credCreation_wrongEncoderForApp() {
CredentialsCommand cc = new CredentialsCommand("username", "bcrypt", App.LASTFM, null, null, null, null, null);
cc.setCredential("c");
cc.setConfirmCredential("c");
assertThat(v.validate(cc, Default.class, CredentialCreateChecks.class)).isNotEmpty();
}
@Test
public void credUpdate_nested_incorrect() {
CredentialsCommand cc = new CredentialsCommand(null, "bcrypt2", null, null, null, null, null, "hash");
assertThat(v.validate(new CredentialsManagementCommand(Collections.singletonList(cc)), Default.class, CredentialUpdateChecks.class)).isNotEmpty();
cc.setEncoder("bcrypt");
cc.setHash(null);
assertThat(v.validate(new CredentialsManagementCommand(Collections.singletonList(cc)), Default.class, CredentialUpdateChecks.class)).isNotEmpty();
}
@Override
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception {
List<Class<?>> groups = new ArrayList<Class<?>>();
String methodClassName = clazz.getName() + "$" + toUpperMethoName(methodName);
Class<?> methodClass = null;
try {
methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader());
groups.add(methodClass);
} catch (ClassNotFoundException e) {
}
Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>();
Method method = clazz.getMethod(methodName, parameterTypes);
Class<?>[] methodClasses = null;
if (method.isAnnotationPresent(MethodValidated.class)){
methodClasses = method.getAnnotation(MethodValidated.class).value();
groups.addAll(Arrays.asList(methodClasses));
}
// add into default group
groups.add(0, Default.class);
groups.add(1, clazz);
// convert list to array
Class<?>[] classgroups = groups.toArray(new Class[0]);
Object parameterBean = getMethodParameterBean(clazz, method, arguments);
if (parameterBean != null) {
violations.addAll(validator.validate(parameterBean, classgroups ));
}
for (Object arg : arguments) {
validate(violations, arg, classgroups);
}
if (!violations.isEmpty()) {
logger.error("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations);
throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations);
}
}
@Transactional(rollbackFor = {})
@Override
public void add(E entity) {
if (repository.existsById(entity.getFdId())) {
throw new RecordExistException();
}
doInit(entity);
beforeSaveOrUpdate(entity, true);
doValidate(entity, AddGroup.class, Default.class);
repository.save(entity);
afterSaveOrUpdate(entity, true);
applicationContext
.publishEvent(new EntityAddEvent(entity));
}
@Transactional(rollbackFor = {})
@Override
public void update(E entity) {
beforeSaveOrUpdate(entity, false);
doValidate(entity, UpdateGroup.class, Default.class);
repository.save(entity);
afterSaveOrUpdate(entity, false);
applicationContext
.publishEvent(new EntityUpdateEvent(entity));
}
@Transactional(rollbackFor = {})
@Override
public void add(E entity) {
if (repository.existsById(entity.getFdId())) {
throw new RecordExistException();
}
doInit(entity);
beforeSaveOrUpdate(entity, true);
doValidate(entity, AddGroup.class, Default.class);
repository.save(entity);
afterSaveOrUpdate(entity, true);
//TODO 日志 add-处理
applicationContext
.publishEvent(new EntityAddEvent(entity));
}
@Transactional(rollbackFor = {})
@Override
public void update(E entity) {
beforeSaveOrUpdate(entity, false);
doValidate(entity, UpdateGroup.class, Default.class);
repository.save(entity);
afterSaveOrUpdate(entity, false);
applicationContext
.publishEvent(new EntityUpdateEvent(entity));
}
/**
* 校验实体参数,返回第一条错误信息
*
* @param t
* @param <T>
* @return
*/
public static <T> String validate(T t) {
if (t == null){
return "参数不能为空!";
}
Set<ConstraintViolation<T>> validationSet = validator.validate(t, Default.class);
String message = null;
if (validationSet != null && validationSet.size() > 0) {
ConstraintViolation<T> violation = validationSet.iterator().next();
message = violation.getMessage();
}
return message;
}