All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ideaaedi.log4j2.defender.conerter.DefenderStrategyConverter Maven / Gradle / Ivy

The newest version!
package com.ideaaedi.log4j2.defender.conerter;

import com.ideaaedi.log4j2.defender.strategy.DefenderStrategy;
import com.ideaaedi.log4j2.defender.util.DefenderUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.GenericConverter;
import org.springframework.lang.NonNull;

import java.util.HashSet;
import java.util.Set;

import static com.ideaaedi.log4j2.defender.constant.DefenderConstant.ENUM_SPLIT_SIGN;

/**
 * DefenderStrategy转换器
 *
 * @author JustryDeng
 * @since 2021/7/23 0:23:46
 */
public class DefenderStrategyConverter implements GenericConverter {
    
    private final ApplicationContext applicationContext;
    
    public DefenderStrategyConverter(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
    
    @Override
    public Set getConvertibleTypes() {
        // String 转换至 DefenderStrategy
        ConvertiblePair convertiblePair = new ConvertiblePair(String.class, DefenderStrategy.class);
        Set convertiblePairSet = new HashSet<>(1);
        convertiblePairSet.add(convertiblePair);
        return convertiblePairSet;
    }
    
    @Override
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        String sourceStr = String.valueOf(source);
        try {
            // 枚举类
            if (StringUtils.isNotBlank(sourceStr) && sourceStr.contains(ENUM_SPLIT_SIGN)) {
                int asSignIndex = sourceStr.indexOf(ENUM_SPLIT_SIGN);
                return DefenderUtil.checkAndGetEnumInstance(sourceStr.substring(0, asSignIndex),
                        sourceStr.substring(asSignIndex + ENUM_SPLIT_SIGN.length()));
            }
            // 普通类
            return DefenderUtil.checkAndGetInstance(sourceStr, DefenderStrategy.class, applicationContext);
        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
            throw new IllegalArgumentException("convert source[" + sourceStr + "] to DesensitizationStrategy Exception!", e);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy