CommUtils
/**
* Copyright 2017-2025 Evergrande Group.
*/
package com.gy.util;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 公共工具
*/
public class CommUtils {
public static final Logger logger = LoggerFactory.getLogger(CommUtils.class);
private CommUtils() {
}
/**
* 生成随机uuid
*
* @return
*/
public static String generateUuid() {
String uuid = UUID.randomUUID().toString();
return uuid.replaceAll("-", "");
}
/**
* 通过图片base64流判断图片等于多少字节 image 图片流
*
* @param image
* @return
*/
public static Integer imageSize(String image) {
if (image.length() <= 22) {
return 0;
}
String str = image.substring(22);
Integer equalIndex = str.indexOf('=');
if (str.indexOf('=') > -1) {
str = str.substring(0, equalIndex);
}
Integer strLength = str.length();
return strLength - (strLength / 8) * 2;
}
/**
* 去掉最后一个分隔符: “,” "-" "/" "——" “_” 等等
* Remove the last separator
*
* @param inputContent
* @return String
* @Methods Name repalceLastSplit
*/
public static String removeLastSeparator(String inputContent) {
StringBuilder build = new StringBuilder(200);
String[] contentSplit = null;
String[] separator = {"-", ",", "/"};
if (inputContent.contains(separator[0])) {
contentSplit = inputContent.split(separator[0]);
for (int i = 0; i < contentSplit.length; i++) {
if (i < (contentSplit.length - 1)) {
build.append(contentSplit[i]).append(separator[0]);
} else {
build.append(contentSplit[i]);
}
}
} return build.toString();
}
/**
* json 转XML
*
* @param json
* @return
*/
public static String getJson2Xml(JSONObject json) {
Iterator<String> it = json.keys();
StringBuilder sb = new StringBuilder();
String key = "";
String value = "";
sb.append("<xml>");
while (it.hasNext()) {
key = it.next();
value = json.optString(key);
if (!"null".equalsIgnoreCase(value)) {
try {
JSONObject jsonSon = JSONObject.fromObject(value);
sb.append("<").append(key).append(">");
sb.append(getJson2Xml(jsonSon));
sb.append(sb.append("</").append(key).append(">"));
} catch (Exception e) {
sb.append("<").append(key).append(">").append(value).append("</").append(key).append(">");
}
}
}
sb.append("</xml>");
return sb.toString();
}
/**
* XML转MAP
*
* @param xmlString
* @return
*/
public static Map<String, Object> transferXMLtoMap(String xmlString) {
Map<String, Object> newMap = new HashMap<String, Object>();
xmlString = xmlString.replaceAll("<\!\[CDATA\[", "");
xmlString = xmlString.replaceAll("\]\]>", "");
xmlString = xmlString.replaceAll("</xml>", "");
xmlString = xmlString.replaceAll("<xml>", "");
Pattern p = Pattern.compile("<([^</]+)>([^</]*)</([^</]+)>");
Matcher m = p.matcher(xmlString);
while (m.find()) {
newMap.put(m.group(1), m.group(2));
}
return newMap;
}
}