learning_record_doc/java/工具类/JAVA常用工具类.md
2022-08-11 18:10:37 +08:00

14 KiB
Raw Blame History

JAVA常用工具类

HttpRequestUtil

作用对HttpReuquest对象进行操作的工具类
public class HttpRequestUtil {

    /**
     * 获取请求IP地址
     */
    public static String getIpAddr(HttpServletRequest request) throws IOException {
        // 获取请求主机IP地址,如果通过代理进来则透过防火墙获取真实IP地址

        String ip = request.getHeader("X-Forwarded-For");

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } else if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++) {
                String strIp = (String) ips[index];
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }
        return ip;
    }

    /**
     * 获取代理信息
     */
    public static String getAgent(HttpServletRequest request){
        return request.getHeader("user-agent");
    }
}

Base64ToMultipartFile

作用实现了MultipartFile接口 可以接受Base64编码后的文件
/**
 * @author dss
 * @since 2022/8/8
 */
public class Base64ToMultipartFile implements MultipartFile {
    private final byte[] fileContent;

    private final String extension;
    private final String contentType;
    private final String name;

    private final String id = "file_"+ UUID.randomUUID().toString();


    public Base64ToMultipartFile(String base64,String name) {
        if (base64==null) throw new MyException(RestResponse.MSG.UPLOAD_EXCEPTION).setMsg("文件解析失败");
        String[] split = base64.split(",");

        if (split==null||split.length!=2) throw new MyException(RestResponse.MSG.UPLOAD_EXCEPTION).setMsg("文件解析失败");
        String uri = split[0];
        String data = split[1];
        try {
            this.fileContent = Base64.getDecoder().decode(data.getBytes(StandardCharsets.UTF_8));
        }catch (IllegalArgumentException e){
            throw new MyException(RestResponse.MSG.UPLOAD_EXCEPTION).setMsg("文件解析失败");
        }
        this.extension = uri.split(";")[0].split("/")[1];
        this.contentType = uri.split(";")[0].split(":")[1];
        this.name=name;
    }

    /**
     * @param base64
     * @param dataUri     格式类似于: data:image/png;base64
     * @param name
     */
    public Base64ToMultipartFile(String base64, String dataUri, String name) {
        try {
            this.fileContent = Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8));
        }catch (IllegalArgumentException e){
            throw new MyException(RestResponse.MSG.UPLOAD_EXCEPTION).setMsg("文件解析失败");
        }
        this.extension = dataUri.split(";")[0].split("/")[1];
        this.contentType = dataUri.split(";")[0].split(":")[1];
        this.name = name;
    }

    public Base64ToMultipartFile(String base64, String extension, String contentType, String name) {
        try {
            this.fileContent = Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8));
        }catch (IllegalArgumentException e){
            throw new MyException(RestResponse.MSG.UPLOAD_EXCEPTION).setMsg("文件解析失败");
        }
        this.extension = extension;
        this.contentType = contentType;
        this.name = name;
    }

    @Override
    public String getName() {
        if (name==null){
            return id;
        }
        return name;
    }

    @Override
    public String getOriginalFilename() {
        if (name==null){
            return id + "." + extension;
        }
        return name+"."+extension;
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return fileContent == null || fileContent.length == 0;
    }

    @Override
    public long getSize() {
        return fileContent.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return fileContent;
    }

    @Override
    public ByteArrayInputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(fileContent);
    }

    @Override
    public void transferTo(File file) throws IOException, IllegalStateException {
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(fileContent);
        }
    }


    /**
     * 实列
     */
    public static void main(String[] args) {
        StringBuilder s = new StringBuilder("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAM0AAAByCAYAAADwIFXJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAA8jSURBVHhe7Z1bcty4DobPJr2ZeCnxCs55d3kbqTxnAZ49JH1IXCQABHTrltHK4K9ixS2RIKn+P5IWOeP/3Epp+vPnD/z769ev2+/fv+HnVf3zcXt9eb19/BN87vKudcH1t9vP9uPP7y+3l+/9J9bP29uLufbj7fbSrr396B8+bx/fXm6v759wK9Ln+yvFwHhYVghiYhsmifYO7YJ7Og7U8e2jtcjrx6zonn+9t9d5ZpPm/hc0iToLmsgss6GbwLzGJOqahWQLNJiHDQ7tIHNP8qCR1+x9+Kz70+NyO6K+dkm4pNwyPKBwfZDk8ylonkKPg4a/ZEzD6A6yIz9+thBMhurmUYZD08h6hrpcw3tgSmhMO0z/AJBv0vx6RngYNAyLuA75prYWNE+hM2Ya+KIdo3gG9vOiiQcghGkijfEcMNmcIumYsp7+c2+zAAX6O0PnAkDaD42EuQvbj8+hoHkKnbM8c4zaBEYRRpVJw8HQaMDWoeFyXrKzjzWn1rSMFID09vd2qiVmUwxN3N6C5sI663caMJYygPzypdAIngnHUXoFmggGaJ+oewM0Eyw9L7WNYWF4WCE0C/X4ZfozsgNFQfN0Ogsa/rKV4QIDqXtgNI6FMWZIlqAZ4Ztl7m2BBup+bb/LCEB6P9tSTS7NujwAsE/eIIGKQIPrYqDQnwuap9B50EjjLBm6Cco3M/z3f/ivhAIMrkfaeclFqZuKYkQmxbZQGzdBQ4ZV+ah+8zsK5jPJ5LGKoOlS8VScguYpdAiaUroKmkQVNNdUQZOoguaaKmgSVdBcUwVNogqaa6qgSVRBc00VNIkqaK6pgiZRBc01VdAk6iugWdwdp83Lxc1AziM2A7dtKDqboUEe95RBsGm7qKgMbb7KtvgnG0icP9gALWgSdT40ZMp+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artFile base64ToMultipartFile = new Base64ToMultipartFile(s.toString(),null);

        System.out.println(base64ToMultipartFile.getOriginalFilename());
    }
}

SpringContextUtil

作用使用静态方法从Spring容器中获取Bean对象
@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //通过name获取 Bean.
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    //通过class获取Bean.
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}

TransactionUtil

作用:手动事务控制
@Component
@Scope("prototype")
public class TransactionUtils {
    private TransactionStatus status;

    private final DataSourceTransactionManager dataSourceTransactionManager;

    public TransactionUtils(DataSourceTransactionManager dataSourceTransactionManager){

        this.dataSourceTransactionManager = dataSourceTransactionManager;
    }

    //开始事务
    public TransactionStatus begin() {

        status = dataSourceTransactionManager.getTransaction(new DefaultTransactionAttribute());
        return status;
    }
    //提交事务
    public void commit(TransactionStatus transaction) {
        dataSourceTransactionManager.commit(transaction);
    }
    //回滚事务
    public void rollback() {
        dataSourceTransactionManager.rollback(status);
    }
}

ReflectionUtils

作用:通过反射获取某个类的所有属性
public class ReflectionUtils {

    /**
     * 获取某个一个类所有的属性(包括所有父类)
     * @param clazz 目标类
     * @return 所有属性集合
     */
    public static <T> List<Field> reflectForField(Class<T> clazz) {
        Class tmpClazz = clazz;
        List<Field> fieldList = new ArrayList<>();
        while (tmpClazz != null) {
            if (tmpClazz.equals(Object.class)) {
                tmpClazz = tmpClazz.getSuperclass();
                continue;
            }
            fieldList.addAll(new ArrayList<>(Arrays.asList(tmpClazz.getDeclaredFields())));
            tmpClazz = tmpClazz.getSuperclass();
        }
        return fieldList;
    }

    /**
     * 获取某个类的某个属性(包括父类)
     * @param clazz 目标类
     * @param filedName 属性名称
     * @return 属性
     */
    public static<T> Field getDeclaredField(Class<T> clazz,String filedName){
        List<Field> fieldList = reflectForField(clazz);

        for (int i = 0; i < fieldList.size(); i++) {
            if (fieldList.get(i).getName().equals(filedName)){
                return fieldList.get(i);
            }
        }
        return null;
    }
}