admin
2022-08-25 264b5dea5b74c4b5ba54a90caba7e709858a037e
src/main/java/com/yeshi/buwan/util/StringUtil.java
@@ -1,354 +1,369 @@
package com.yeshi.buwan.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.gson.*;
import javax.persistence.Entity;
import javax.servlet.http.HttpServletRequest;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
import java.lang.reflect.Type;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 *
 * @author Administrator
 *
 */
@Entity
public class StringUtil {
   // 判断是否为电话号码
   public static boolean isMobile(String mobile) {
    // 判断是否为电话号码
    public static boolean isMobile(String mobile) {
      String regex = "^((13[0-9])|(17[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(mobile);
        String regex = "^((13[0-9])|(17[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(mobile);
      if (mobile == null || mobile.equals("") || mobile.length() != 11) {
        if (mobile == null || mobile.equals("") || mobile.length() != 11) {
            return false;
        } else {
            return m.find();
        }
    }
         return false;
      } else {
         return m.find();
      }
   }
    /**
     * 连接数组内的元素
     *
     * @param srcList
     * @param seperate
     * @return
     */
    public static String join(List srcList, String seperate) {
        String st = "";
        for (int i = 0; i < srcList.size(); i++) {
            st += srcList.get(i) + seperate;
        }
        if (st.endsWith(seperate)) {
            st = st.substring(0, st.length() - seperate.length());
        }
        return st;
    }
   /**
    * 随机码生成
    *
    * @return
    */
   public static String getRandomCode() {
      String sts = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      String code = "";
      for (int i = 0; i < 10; i++) {
         int p = (int) (Math.random() * 26);
         code += sts.charAt(p);
      }
      return code;
   }
   /**
    * 验证码生成
    *
    * @return
    */
   public static String getVerifyCode() {
      String sts = "0123456789";
      String code = "";
      for (int i = 0; i < 6; i++) {
         int p = (int) (Math.random() * 10);
         code += sts.charAt(p);
      }
      return code;
   }
    public static String join(Collection srcList, String seperate) {
        String st = "";
        for (Iterator<String> its = srcList.iterator(); its.hasNext(); ) {
            st += its.next() + seperate;
        }
        if (st.endsWith(seperate)) {
            st = st.substring(0, st.length() - seperate.length());
        }
        return st;
    }
   public static String getVerifyCode(int number) {
      String sts = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
      String code = "";
      for (int i = 0; i < number; i++) {
         int p = (int) (Math.random() * sts.length());
         code += sts.charAt(p);
      }
      return code;
   }
    /**
     * 随机码生成
     *
     * @return
     */
    public static String getRandomCode() {
        String sts = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String code = "";
        for (int i = 0; i < 10; i++) {
            int p = (int) (Math.random() * 26);
            code += sts.charAt(p);
        }
        return code;
    }
   // 获取短信发送的格式
   public static String getMessageStyle(String code) {
    /**
     * 验证码生成
     *
     * @return
     */
    public static String getVerifyCode() {
        return getNumberVerifyCode(6);
    }
      return "校验码:" + code + ",用于账号注册。【请勿向任何人提供您收到的短信校验码】";
   }
    public static String getNumberVerifyCode(int number) {
        String sts = "0123456789";
        String code = "";
        for (int i = 0; i < number; i++) {
            int p = (int) (Math.random() * 10);
            code += sts.charAt(p);
        }
        return code;
    }
   // 是否是空的字符串
   public static boolean isNullOrEmpty(String text) {
      if (text == null || text.length() == 0 || text.equals("null")) {
         return true;
      }
      return false;
   }
    public static String getVerifyCode(int number) {
        String sts = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String code = "";
        for (int i = 0; i < number; i++) {
            int p = (int) (Math.random() * sts.length());
            code += sts.charAt(p);
        }
        return code;
    }
   // 32位MD5加密
   public static String Md5(String st) {
      try {
         MessageDigest md = MessageDigest.getInstance("MD5");
         try {
            md.update(st.getBytes("UTF-8"));
         } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
         byte b[] = md.digest();
    // 获取短信发送的格式
    public static String getMessageStyle(String code) {
         int i;
        return "校验码:" + code + ",用于账号注册。【请勿向任何人提供您收到的短信校验码】";
    }
         StringBuffer buf = new StringBuffer("");
         for (int offset = 0; offset < b.length; offset++) {
            i = b[offset];
            if (i < 0)
               i += 256;
            if (i < 16)
               buf.append("0");
            buf.append(Integer.toHexString(i));
         }
         LogUtil.i("MD5加密后的值:" + buf.toString());
         return buf.toString();
         // LogUtil.i("result: " + buf.toString());// 32位的加密
         // LogUtil.i("result: " + buf.toString().substring(8,
         // 24));// 16位的加密
      } catch (NoSuchAlgorithmException e) {
         e.printStackTrace();
      }
      return null;
   }
    // 是否是空的字符串
    public static boolean isNullOrEmpty(String text) {
        if (text == null || text.length() == 0 || text.equals("null")) {
            return true;
        }
        return false;
    }
   public static String getString(String st) {
      return isNullOrEmpty(st) ? "" : st;
   }
    // 32位MD5加密
    public static String Md5(String st) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            try {
                md.update(st.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            byte b[] = md.digest();
   public static String getString(int i) {
      return getString(i + "");
   }
            int i;
   public static String getString(long i) {
      return getString(i + "");
   }
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            LogUtil.i("MD5加密后的值:" + buf.toString());
            return buf.toString();
            // LogUtil.i("result: " + buf.toString());// 32位的加密
            // LogUtil.i("result: " + buf.toString().substring(8,
            // 24));// 16位的加密
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
   // 输出JSON的数据格式
    public static String getString(String st) {
        return isNullOrEmpty(st) ? "" : st;
    }
   public static String outPutResultJson(Object o) {
      if (o instanceof String) {
         return o.toString();
      } else {
         Gson gson = new GsonBuilder().enableComplexMapKeySerialization().excludeFieldsWithoutExposeAnnotation()
               .setDateFormat(DateFormat.LONG).setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)// 会把字段首字母大写
               .setPrettyPrinting().setVersion(1.0).create();
         String st = gson.toJson(o);
         return Utils.JsonFilter(st);
      }
   }
    public static String getString(int i) {
        return getString(i + "");
    }
   // 输出JSON的数据格式
    public static String getString(long i) {
        return getString(i + "");
    }
   public static JsonArray outPutResultJson(List<Object> list) {
      Gson gson = new GsonBuilder().enableComplexMapKeySerialization().excludeFieldsWithoutExposeAnnotation()
            .setDateFormat(DateFormat.LONG).setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)// 会把字段首字母大写
            .setPrettyPrinting().setVersion(1.0).create();
    // 输出JSON的数据格式
      JsonParser parser = new JsonParser();
      JsonElement el = parser.parse(gson.toJson(list).toString());
    public static String outPutResultJson(Object o) {
        if (o instanceof String) {
            return o.toString();
        } else {
            Gson gson = new GsonBuilder().enableComplexMapKeySerialization().excludeFieldsWithoutExposeAnnotation()
                    .setDateFormat(DateFormat.LONG).registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
                        @Override
                        public JsonElement serialize(Date value, Type theType, JsonSerializationContext context) {
                            if (value == null) {
                                return new JsonPrimitive("0");
                            } else {
                                return new JsonPrimitive(value.getTime());
                            }
                        }
                    }).setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)// 会把字段首字母大写
                    .setPrettyPrinting().setVersion(1.0).create();
            String st = gson.toJson(o);
            return Utils.JsonFilter(st);
        }
    }
      // 把JsonElement对象转换成JsonObject
      JsonObject jsonObj = null;
      if (el.isJsonObject()) {
         jsonObj = el.getAsJsonObject();
      }
    // 输出JSON的数据格式
      // 把JsonElement对象转换成JsonArray
      JsonArray jsonArray = null;
      if (el.isJsonArray()) {
         jsonArray = el.getAsJsonArray();
      }
      return jsonArray;
   }
    public static JsonArray outPutResultJson(List<Object> list) {
        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().excludeFieldsWithoutExposeAnnotation()
                .setDateFormat(DateFormat.LONG).setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)// 会把字段首字母大写
                .setPrettyPrinting().setVersion(1.0).create();
   /*
    * 获取中间带星号的电话号码
    */
   public static String getSubMobile(String mobile) {
      if (!StringUtil.isNullOrEmpty(mobile) && mobile.length() > 10) {
         return mobile.subSequence(0, 3).toString() + "****" + mobile.subSequence(7, mobile.length()).toString();
      } else
         return mobile;
   }
        JsonParser parser = new JsonParser();
        JsonElement el = parser.parse(gson.toJson(list).toString());
   public static String formatNumber(String number) {
      if (!isNullOrEmpty(number)) {
         float f = Float.parseFloat(number);
         if (f % 1.0 == 0) {
            return ((int) f + "");
         } else if (f % 0.1 == 0) {
            return (NumberUtil.get1PointNumber(f) + "");
         }
         return f + "";
      } else {
         return 0 + "";
      }
   }
        // 把JsonElement对象转换成JsonObject
        JsonObject jsonObj = null;
        if (el.isJsonObject()) {
            jsonObj = el.getAsJsonObject();
        }
   public static String getAbsoluteUrl(HttpServletRequest request, String url) {
      if (StringUtil.isNullOrEmpty(url))
         return "";
      if (url.startsWith("http://") || url.startsWith("https://"))
         return url;
      else
         return "http://" + Constant.WEBSITE + "/BuWan" + url;
   }
        // 把JsonElement对象转换成JsonArray
        JsonArray jsonArray = null;
        if (el.isJsonArray()) {
            jsonArray = el.getAsJsonArray();
        }
        return jsonArray;
    }
   public static int getPage(String page) {
      if (StringUtil.isNullOrEmpty(page)) {
         return 0;
      } else {
         try {
            return Integer.parseInt(page);
         } catch (Exception e) {
            return 0;
         }
      }
   }
    /*
     * 获取中间带星号的电话号码
     */
    public static String getSubMobile(String mobile) {
        if (!StringUtil.isNullOrEmpty(mobile) && mobile.length() > 10) {
            return mobile.subSequence(0, 3).toString() + "****" + mobile.subSequence(7, mobile.length()).toString();
        } else
            return mobile;
    }
   public static String getBase64(String str) {
      byte[] b = null;
      String s = null;
      try {
         b = str.getBytes("utf-8");
      } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
      }
      if (b != null) {
         s = new BASE64Encoder().encode(b);
      }
      return s;
   }
    public static String formatNumber(String number) {
        if (!isNullOrEmpty(number)) {
            float f = Float.parseFloat(number);
            if (f % 1.0 == 0) {
                return ((int) f + "");
            } else if (f % 0.1 == 0) {
                return (NumberUtil.get1PointNumber(f) + "");
            }
            return f + "";
        } else {
            return 0 + "";
        }
    }
   public static String getBase64FromByte(byte[] b) {
    public static String getAbsoluteUrl(HttpServletRequest request, String url) {
        if (StringUtil.isNullOrEmpty(url))
            return "";
        if (url.startsWith("http://") || url.startsWith("https://"))
            return url;
        else
            return "http://" + Constant.WEBSITE + "/BuWan" + url;
    }
      String s = null;
      if (b != null) {
         s = new BASE64Encoder().encode(b);
      }
      return s;
   }
    public static int getPage(String page) {
        if (StringUtil.isNullOrEmpty(page)) {
            return 0;
        } else {
            try {
                return Integer.parseInt(page);
            } catch (Exception e) {
                return 0;
            }
        }
    }
   // 解密
   public static String getFromBase64(String s) {
      byte[] b = null;
      String result = null;
      if (s != null) {
         BASE64Decoder decoder = new BASE64Decoder();
         try {
            b = decoder.decodeBuffer(s);
            result = new String(b, "utf-8");
         } catch (Exception e) {
            e.printStackTrace();
         }
      }
      return result;
   }
    public static String getBase64(String str) {
        byte[] b = null;
        String s = null;
        try {
            b = str.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (b != null) {
            s = Base64.getEncoder().encodeToString(b);
        }
        return s;
    }
   public static byte[] getFromBase64Byte(String s) {
      byte[] b = null;
      if (s != null) {
         BASE64Decoder decoder = new BASE64Decoder();
         try {
            b = decoder.decodeBuffer(s);
            return b;
         } catch (Exception e) {
            e.printStackTrace();
         }
      }
      return null;
   }
    public static String getBase64FromByte(byte[] b) {
   public static String getNumberFromString(String st) {
      String number = "";
      Pattern p = Pattern.compile("[0-9\\.]+");
      Matcher m = p.matcher(st);
        String s = null;
        if (b != null) {
            s = Base64.getEncoder().encodeToString(b);
        }
        return s;
    }
      while (m.find()) {
         number += (m.group() + ",");
      }
      return number;
   }
    // 解密
    public static String getFromBase64(String s) {
        String result = null;
        if (s != null) {
            byte[] b = Base64.getDecoder().decode(s);
            try {
                result = new String(b, "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
   public static String getNotNullString(String st) {
      if (isNullOrEmpty(st))
         return "";
      else
         return st;
   }
    public static byte[] getFromBase64Byte(String s) {
        return Base64.getDecoder().decode(s);
    }
   public static String getUTF8String(String resource, String chactor) {
      if (!isNullOrEmpty(resource)) {
         try {
            return new String(resource.getBytes(chactor), "UTF-8");
         } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
      }
      return "";
   }
    public static String getNumberFromString(String st) {
        String number = "";
        Pattern p = Pattern.compile("[0-9\\.]+");
        Matcher m = p.matcher(st);
   @SuppressWarnings("restriction")
   public static boolean generateImageFromBase64(String imgStr, String imgFilePath) { // 对字节数组字符串进行Base64解码并生成图片
      if (!new File(imgFilePath).exists())
         try {
            new File(imgFilePath).createNewFile();
         } catch (IOException e1) {
            e1.printStackTrace();
         }
      if (imgStr == null) // 图像数据为空
         return false;
      BASE64Decoder decoder = new BASE64Decoder();
      try {
         // Base64解码
         byte[] b = decoder.decodeBuffer(imgStr);
         for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {// 调整异常数据
               b[i] += 256;
            }
         }
         OutputStream out = new FileOutputStream(imgFilePath);
         out.write(b);
         out.flush();
         out.close();
         return true;
      } catch (Exception e) {
         return false;
      }
   }
        while (m.find()) {
            number += (m.group() + ",");
        }
        return number;
    }
   public static boolean match(String regix, String src) {
      Pattern p = Pattern.compile(regix);
      Matcher m = p.matcher(src);
      return m.find();
   }
    public static String getNotNullString(String st) {
        if (isNullOrEmpty(st))
            return "";
        else
            return st;
    }
    public static String getUTF8String(String resource, String chactor) {
        if (!isNullOrEmpty(resource)) {
            try {
                return new String(resource.getBytes(chactor), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return "";
    }
    @SuppressWarnings("restriction")
    public static boolean generateImageFromBase64(String imgStr, String imgFilePath) { // 对字节数组字符串进行Base64解码并生成图片
        if (!new File(imgFilePath).exists())
            try {
                new File(imgFilePath).createNewFile();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        if (imgStr == null) // 图像数据为空
            return false;
        try {
            // Base64解码
            byte[] b = Base64.getDecoder().decode(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    public static boolean match(String regix, String src) {
        Pattern p = Pattern.compile(regix);
        Matcher m = p.matcher(src);
        return m.find();
    }
}