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.interceptor;
017
018import com.jfinal.aop.Interceptor;
019import com.jfinal.aop.Invocation;
020import io.jboot.components.valid.ValidUtil;
021import io.jboot.utils.ClassUtil;
022
023import javax.validation.ConstraintViolation;
024import javax.validation.Valid;
025import java.lang.reflect.Parameter;
026import java.util.Set;
027
028public class ValidInterceptor implements Interceptor {
029
030
031    @Override
032    public void intercept(Invocation inv) {
033
034        Parameter[] parameters = inv.getMethod().getParameters();
035
036        for (int index = 0; index < parameters.length; index++) {
037            if (parameters[index].getAnnotation(Valid.class) != null) {
038                Object validObject = inv.getArg(index);
039                if (validObject == null) {
040                    continue;
041                }
042                Set<ConstraintViolation<Object>> constraintViolations = ValidUtil.validate(validObject);
043                if (constraintViolations != null && constraintViolations.size() > 0) {
044                    StringBuilder msg = new StringBuilder();
045                    for (ConstraintViolation<?> cv : constraintViolations) {
046                        msg.append(cv.getRootBeanClass().getName())
047                                .append(".")
048                                .append(cv.getPropertyPath())
049                                .append(cv.getMessage());
050                    }
051                    String reason = parameters[index].getName() + " is valid failed at method: " + ClassUtil.buildMethodString(inv.getMethod());
052                    ValidUtil.throwValidException(parameters[index].getName(), msg.toString(), reason);
053
054                }
055            }
056        }
057
058        inv.invoke();
059    }
060
061
062}