com.github.dennisit.vplus.data.utils.ValidateUtils Maven / Gradle / Ivy
/*--------------------------------------------------------------------------
* Copyright (c) 2010-2020, Elon.su All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the elon developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: Elon.su, you can also mail [email protected]
*--------------------------------------------------------------------------
*/
package com.github.dennisit.vplus.data.utils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* @author Elon.su
*/
@Deprecated
public final class ValidateUtils {
private ValidateUtils() {
}
/**
* 从校验结果中抽取第一个错误的描述内容
*
* @param result 校验结果
* @return 原因描述集合中的第一个
*/
public static String wrapErrorFirst(BindingResult result) {
List errors = wrapErrorList(result);
return CollectionUtils.isNotEmpty(errors) ? errors.get(0) : StringUtils.EMPTY;
}
/**
* 从校验结果中抽取所有的校验不通过的描述原因
*
* @param result 校验结果
* @return 原因描述集合
*/
public static List wrapErrorList(BindingResult result) {
Map map = wrapErrorMap(result);
if (MapUtils.isEmpty(map)) {
return Lists.newArrayList();
}
return Lists.newArrayList(map.values());
}
/**
* 从校验结果集中抽取参数以及说明
*
* @param result 校验结果集合
* @return 属性与校验结果映射
*/
public static Map wrapErrorMap(BindingResult result) {
if (!result.hasErrors()) {
return Maps.newHashMap();
}
List list = result.getFieldErrors();
if (CollectionUtils.isEmpty(list)) {
return Maps.newHashMap();
}
Map map = Maps.newHashMap();
list.forEach(li -> {
map.put(li.getField(), li.getDefaultMessage());
});
return map;
}
}