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.aop;
017
018import com.jfinal.aop.Interceptor;
019import com.jfinal.aop.Invocation;
020import io.jboot.aop.annotation.AutoLoad;
021import io.jboot.aop.annotation.DefaultValue;
022import io.jboot.core.weight.Weight;
023import io.jboot.utils.ObjectUtil;
024
025import java.lang.reflect.Method;
026import java.lang.reflect.Parameter;
027
028@AutoLoad
029@Weight(999)
030public class DefaultValueInterceptor implements Interceptor, InterceptorBuilder {
031
032    @Override
033    public void intercept(Invocation inv) {
034        Parameter[] parameters = inv.getMethod().getParameters();
035        for (int index = 0; index < parameters.length; index++) {
036            DefaultValue defaultValue = parameters[index].getAnnotation(DefaultValue.class);
037            if (defaultValue != null) {
038                Object arg = inv.getArg(index);
039                if (arg == null || isPrimitiveDefaultValue(arg, parameters[index].getType())) {
040                    Object value = ObjectUtil.convert(defaultValue.value(), parameters[index].getType());
041                    if (value != null) {
042                        inv.setArg(index, value);
043                    }
044                }
045            }
046        }
047
048        inv.invoke();
049    }
050
051    public static boolean isPrimitiveDefaultValue(Object value, Class<?> paraClass) {
052        if (paraClass == int.class || paraClass == long.class || paraClass == float.class || paraClass == double.class || paraClass == short.class) {
053            return ((Number) value).intValue() == 0;
054        } else if (paraClass == boolean.class) {
055            return !(boolean) value;
056        }
057        return false;
058    }
059
060
061    @Override
062    public void build(Class<?> targetClass, Method method, Interceptors interceptors) {
063        Parameter[] parameters = method.getParameters();
064        if (parameters != null && parameters.length > 0) {
065            for (Parameter p : parameters) {
066                if (p.getAnnotation(DefaultValue.class) != null) {
067                    interceptors.addIfNotExist(this);
068                    break;
069                }
070            }
071        }
072
073    }
074}