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 com.jfinal.kit.Ret;
021import io.jboot.components.valid.ValidUtil;
022import io.jboot.utils.ClassUtil;
023import io.jboot.utils.StrUtil;
024
025import javax.validation.constraints.Size;
026import java.lang.reflect.Parameter;
027
028
029public class SizeInterceptor implements Interceptor {
030
031    @Override
032    public void intercept(Invocation inv) {
033        Parameter[] parameters = inv.getMethod().getParameters();
034
035        for (int index = 0; index < parameters.length; index++) {
036            Size size = parameters[index].getAnnotation(Size.class);
037            if (size == null) {
038                continue;
039            }
040
041            Object validObject = inv.getArg(index);
042
043            //不指定 @Size(min=xxx),值配置了 max,则跳过空数据的内容
044            if (size.min() == 0 && (validObject == null || (validObject instanceof String && StrUtil.isBlank((String) validObject)))) {
045                continue;
046            }
047
048            if (validObject == null) {
049                String reason = parameters[index].getName() + " need size is " + size.min() + " ~ " + size.max()
050                        + ", but current value is null at method: " + ClassUtil.buildMethodString(inv.getMethod());
051                Ret paras = Ret.by("max", size.max()).set("min", size.min());
052                ValidUtil.throwValidException(parameters[index].getName(), size.message(), paras, reason);
053                return;
054            }
055
056            long len = Util.getObjectLen(validObject);
057            
058            if (len < size.min() || len > size.max()) {
059                String reason = parameters[index].getName() + " need size is " + size.min() + " ~ " + size.max()
060                        + ", but current value size (or length) is " + len + " at method: " + ClassUtil.buildMethodString(inv.getMethod());
061                Ret paras = Ret.by("max", size.max()).set("min", size.min());
062                ValidUtil.throwValidException(parameters[index].getName(), size.message(), paras, reason);
063            }
064        }
065
066        inv.invoke();
067    }
068
069
070}