001/**
002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com).
003 * <p>
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * <p>
008 * http://www.apache.org/licenses/LICENSE-2.0
009 * <p>
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package io.jboot.components.valid;
017
018import com.jfinal.kit.Ret;
019import io.jboot.components.valid.interceptor.SimpleContext;
020import org.hibernate.validator.HibernateValidator;
021
022import javax.validation.*;
023import java.util.Set;
024
025public class ValidUtil {
026
027    /**
028     * ValidatorFactory
029     */
030    private static ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
031            .configure()
032            .failFast(true)
033            .buildValidatorFactory();
034    /**
035     * 验证器:用于数据验证
036     */
037    private static Validator validator = validatorFactory.getValidator();
038
039    /**
040     * 消息处理器: 用于校验消息处理
041     */
042    private static MessageInterpolator messageInterpolator = validatorFactory.getMessageInterpolator();
043
044    private static int errorCode = 400;
045
046
047    public static Validator getValidator() {
048        return validator;
049    }
050
051    public static void setValidator(Validator validator) {
052        ValidUtil.validator = validator;
053    }
054
055
056    public static int getErrorCode() {
057        return errorCode;
058    }
059
060    public static void setErrorCode(int errorCode) {
061        ValidUtil.errorCode = errorCode;
062    }
063
064    public static Set<ConstraintViolation<Object>> validate(Object object) {
065        return validator.validate(object);
066    }
067
068
069    public static void throwValidException(String fieldName, String message, String reason) {
070        throwValidException(fieldName, message, null, reason);
071    }
072
073
074    public static void throwValidException(String fieldName, String message, Ret paras, String reason) {
075        if (isParaMessage(message)) {
076            message = fieldName + " " + messageInterpolator.interpolate(message, new SimpleContext(paras));
077        }
078
079        throw new ValidException(message, reason, fieldName);
080    }
081
082
083    private static boolean isParaMessage(String message) {
084        return message != null && message.startsWith("{") && message.endsWith("}");
085    }
086}