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;
023
024import javax.validation.constraints.Digits;
025import java.lang.reflect.Parameter;
026
027public class DigitsInterceptor implements Interceptor {
028
029    @Override
030    public void intercept(Invocation inv) {
031        Parameter[] parameters = inv.getMethod().getParameters();
032        for (int index = 0; index < parameters.length; index++) {
033            Digits digits = parameters[index].getAnnotation(Digits.class);
034            if (digits == null) {
035                continue;
036            }
037
038            Object validObject = inv.getArg(index);
039            if (validObject != null && !matchesDigits(digits, validObject)) {
040                String reason = parameters[index].getName() + " not matches @Digits at method: " + ClassUtil.buildMethodString(inv.getMethod());
041                Ret paras = Ret.by("integer", digits.integer()).set("fraction", digits.fraction());
042                ValidUtil.throwValidException(parameters[index].getName(), digits.message(), paras, reason);
043            }
044        }
045
046        inv.invoke();
047    }
048
049    private boolean matchesDigits(Digits digits, Object validObject) {
050        String validString = validObject.toString();
051        String[] valids = validString.split("\\.");
052
053        int integer = removeStartZero(valids[0]).length();
054        int fraction = valids[0].length() == 1 ? 0 : removeEndZero(valids[1]).length();
055
056        return integer <= digits.integer() && fraction <= digits.fraction();
057    }
058
059    private String removeStartZero(String string) {
060        while (string.startsWith("0")) {
061            string = string.substring(1);
062        }
063        return string;
064    }
065
066
067    private String removeEndZero(String string) {
068        while (string.endsWith("0")) {
069            string = string.substring(0, string.length() - 1);
070        }
071        return string;
072    }
073
074
075}