package com.ruoyi.common.utils;

import com.alibaba.fastjson2.JSON;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;

/**
 * @author LinQiLong
 * @date 2023/4/26 10:19
 */
public class StringDataTypeUtils {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String str1 = "45";
        String str2 = "wangningwei";
        String str3 = "{cd:\"wangningwei\"}";
        String str4 = "<av>fvbfdyr</av>";
        System.out.println("string1::" + getType(str1));
        System.out.println("string2::" + getType(str2));
        System.out.println("string3::" + getType(str3));
        System.out.println("string4::" + getType(str4));
    }

    public static String getType(String string) {
        if (isNumber(string)) {
            return "NUMBER";
        } else if (isJson(string)) {
            return "JSON";
        } else if (isXML(string)) {
            return "XML";
        } else {
            return "STRING";
        }
    }

    /**
     * 判断字符串是否是数字
     */
    public static boolean isNumber(String value) {
        return isInteger(value) || isDouble(value);
    }

    /**
     * 判断字符串是否是整数
     */
    public static boolean isInteger(String value) {
        try {
            Integer.parseInt(value);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 判断字符串是否是浮点数
     */
    public static boolean isDouble(String value) {
        try {
            Double.parseDouble(value);
            return value.contains(".");
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 判断是否是json结构
     */
    public static boolean isJson(String value) {
        try {
            JSON.parse(value);
        } catch (Throwable e) {
            return false;
        }
        return true;
    }

    /**
     * 判断是否是xml结构
     */
    public static boolean isXML(String value) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader(value));
            builder.parse(is);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
