org.nervousync.utils.StringUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of utils-jdk11 Show documentation
Show all versions of utils-jdk11 Show documentation
Java utility collections, development by Nervousync Studio (NSYC)
/*
* Licensed to the Nervousync Studio (NSYC) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.nervousync.utils;
import java.io.*;
import java.lang.Character.UnicodeBlock;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.text.ParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;
import org.nervousync.commons.RegexGlobals;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.nervousync.commons.Globals;
import org.nervousync.huffman.HuffmanTree;
import org.w3c.dom.Document;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.SchemaFactory;
/**
* String utilities
*
* Current utilities implements features:
* Encode byte arrays using Base32/Base64
* Decode Base32/Base64 string to byte arrays
* Encode string to Huffman tree
* Trim given string
* Match given string is MD5 value/UUID/phone number/e-mail address etc.
* Check given string is empty/notNull/notEmpty/contains string etc.
* Tokenize string by given delimiters
* Substring given input string by rule
* Validate given string is match code type
*
* 字符串工具集
*
* 此工具集实现以下功能:
* 使用Base32/Base64编码给定的二进制字节数组
* 将给定的Base32/Base64编码字符串解码为二进制字节数组
* 将给定的字符串编码为霍夫曼树结果实例对象
* 去除字符串中的空格
* 检查给定的字符串是否为MD5值/UUID/电话号码/电子邮件地址等
* 检查给定的字符串是否为空/非空/包含字符串等
* 使用给定的分隔符分割字符串
* 根据规则截取字符串
* 验证给定的字符串是否符合代码类型
*
*
* @author Steven Wee [email protected]
* @version $Revision: 1.2.0 $ $Date: Jan 13, 2010 15:53:41 $
*/
public final class StringUtils {
/**
* Logger instance
* 日志实例
*/
private static final LoggerUtils.Logger LOGGER = LoggerUtils.getLogger(StringUtils.class);
/**
* Top folder path
* 上级目录路径
*/
private static final String TOP_PATH = "..";
/**
* Current folder path
* 当前目录路径
*/
private static final String CURRENT_PATH = ".";
/**
* Mask bytes using for convert number to unsigned number
* 掩码字节用于转换数字为无符号整形
*/
private static final int MASK_BYTE_UNSIGNED = 0xFF;
/**
* Padding byte of Base32/Base64
* Base32/Base64的填充字节
*/
private static final int PADDING = '=';
/**
* Character string for Base32
* Base32用到的字符
*/
private static final String BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
/**
* Character string for Base64
* Base64用到的字符
*/
private static final String BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* Character string for authenticate code
* 验证码用到的字符
*/
private static final String AUTHORIZATION_CODE_ITEMS = "23456789ABCEFGHJKLMNPQRSTUVWXYZ";
/**
* End character of China ID code
* 中国身份证号的结尾字符
*/
private static final String CHN_ID_CARD_CODE = "0123456789X";
/**
* End character of China Social Credit code
* 中国统一信用代码的结尾字符
*/
private static final String CHN_SOCIAL_CREDIT_CODE = "0123456789ABCDEFGHJKLMNPQRTUWXY";
/**
* XML Schema file mapping resource path
* XML约束文档的资源映射文件
*/
private static final String SCHEMA_MAPPING_RESOURCE_PATH = "META-INF/nervousync.schemas";
/**
* Registered schema mapping
* 注册的约束文档与资源文件的映射
*/
private static final Map SCHEMA_MAPPING = new HashMap<>();
static {
try {
ClassUtils.getDefaultClassLoader().getResources(SCHEMA_MAPPING_RESOURCE_PATH)
.asIterator()
.forEachRemaining(StringUtils::REGISTER_SCHEMA);
} catch (IOException e) {
LOGGER.error("Load_Schema_Mapping_Error");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Stack_Message_Error", e);
}
}
}
/**
* Encode byte arrays using Base32
*
* Will return zero length string for given byte arrays is null
or arrays length is 0.
*
* 使用Base32编码给定的二进制字节数组
* 如果给定的二进制字节数组为null
或长度为0,将返回长度为0的空字符串
*
* StringUtils.base32Encode(null) = ""
* StringUtils.base32Encode([]) = ""
* StringUtils.base32Encode([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]) = "JBSWY3DPEBLW64TMMQ"
*
*
* @param bytes byte arrays
* 二进制字节数组
*
* @return Encoded base32 string
* 编码后的Base32字符串
*/
public static String base32Encode(final byte[] bytes) {
return base32Encode(bytes, Boolean.FALSE);
}
/**
* Encode byte arrays using Base32
*
* Will append padding character at end if parameter padding is true
* and result string length % 5 != 0.
* Will return zero length string for given byte arrays is null
or arrays length is 0.
*
* 使用Base32编码给定的二进制字节数组
*
* 如果参数padding设置为true
,并且结果字符串长度非5的整数倍,则自动追加填充字符到结果末尾。
* 如果给定的二进制字节数组为null
或长度为0,将返回长度为0的空字符串
*
*
* StringUtils.base32Encode(null, true) = ""
* StringUtils.base32Encode([], true) = ""
* StringUtils.base32Encode([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100], true) = "JBSWY3DPEBLW64TMMQ=="
*
*
* @param bytes byte arrays
* 二进制字节数组
* @param padding append padding character status
* 是否追加填充字符到结果末尾
*
* @return Encoded base32 string
* 编码后的Base32字符串
*/
public static String base32Encode(final byte[] bytes, boolean padding) {
if (bytes == null) {
return Globals.DEFAULT_VALUE_STRING;
}
StringBuilder stringBuilder = new StringBuilder();
int i = 0, index = 0;
int currentByte, nextByte, digit;
while (i < bytes.length) {
currentByte = bytes[i] >= 0 ? bytes[i] : bytes[i] + 256;
if (index > 3) {
if ((i + 1) < bytes.length) {
nextByte = bytes[i + 1] >= 0 ? bytes[i + 1] : bytes[i + 1] + 256;
} else {
nextByte = 0;
}
digit = currentByte & (MASK_BYTE_UNSIGNED >> index);
index = (index + 5) % 8;
digit = (digit << index) | nextByte >> (8 - index);
i++;
} else {
digit = (currentByte >> (8 - (index + 5))) & 0x1F;
index = (index + 5) % 8;
if (index == 0) {
i++;
}
}
stringBuilder.append(BASE32.charAt(digit));
}
if (padding) {
while (stringBuilder.length() % 5 > 0) {
stringBuilder.append((char) PADDING);
}
}
return stringBuilder.toString();
}
/**
* Decode given Base32 string to byte arrays
*
* Will return a zero-length array for given base64 string is null
or string length is 0.
*
* 将给定的Base32编码字符串解码为二进制字节数组
* 如果给定的字符串长度为0,则返回长度为0的二进制字节数组
*
* StringUtils.base32Decode(null) = []
* StringUtils.base32Decode("") = []
* StringUtils.base32Decode("JBSWY3DPEBLW64TMMQ") = [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
*
*
* @param string Encoded base32 string
* 编码后的Base32字符串
*
* @return Decoded byte array
* 解码后的二进制字节数组
*/
public static byte[] base32Decode(String string) {
if (string == null || string.isEmpty()) {
return new byte[0];
}
while (string.charAt(string.length() - 1) == PADDING) {
string = string.substring(0, string.length() - 1);
}
byte[] bytes = new byte[string.length() * 5 / 8];
int index = 0;
StringBuilder stringBuilder = new StringBuilder(8);
StringBuilder temp;
for (String c : string.split("")) {
if (BASE32.contains(c)) {
int current = BASE32.indexOf(c);
temp = new StringBuilder(5);
for (int i = 0; i < 5; i++) {
temp.append(current & 1);
current >>>= 1;
}
temp.reverse();
if (stringBuilder.length() >= 3) {
int currentLength = 8 - stringBuilder.length();
stringBuilder.append(temp.substring(0, currentLength));
bytes[index] = (byte) Integer.valueOf(stringBuilder.toString(), 2).intValue();
index++;
stringBuilder = new StringBuilder(8);
stringBuilder.append(temp.substring(currentLength));
} else {
stringBuilder.append(temp);
}
}
}
return bytes;
}
/**
* Encode byte arrays using Base64
*
* Will return zero length string for given byte arrays is null
or arrays length is 0.
*
* 使用Base64编码给定的二进制字节数组
* 如果给定的二进制字节数组为null
或长度为0,将返回长度为0的空字符串
*
* StringUtils.base64Encode(null) = ""
* StringUtils.base64Encode([]) = ""
* StringUtils.base64Encode([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]) = "SGVsbG8gV29ybGQ="
*
*
* @param bytes byte arrays
* 二进制字节数组
*
* @return Encoded Base64 string
* 编码后的Base64字符串
*/
public static String base64Encode(final byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return Globals.DEFAULT_VALUE_STRING;
}
int length = bytes.length;
byte[] tempBytes;
if (length % 3 == 0) {
tempBytes = bytes;
} else {
while (length % 3 != 0) {
length++;
}
tempBytes = new byte[length];
System.arraycopy(bytes, 0, tempBytes, 0, bytes.length);
for (int i = bytes.length; i < length; i++) {
tempBytes[i] = 0;
}
}
StringBuilder stringBuilder = new StringBuilder();
int index = 0;
while ((index * 3) < length) {
stringBuilder.append(BASE64.charAt((tempBytes[index * 3] >> 2) & 0x3F));
stringBuilder.append(BASE64.charAt(((tempBytes[index * 3] << 4)
| ((tempBytes[index * 3 + 1] & MASK_BYTE_UNSIGNED) >> 4)) & 0x3F));
if (index * 3 + 1 < bytes.length) {
stringBuilder.append(BASE64.charAt(((tempBytes[index * 3 + 1] << 2)
| ((tempBytes[index * 3 + 2] & MASK_BYTE_UNSIGNED) >> 6)) & 0x3F));
}
if (index * 3 + 2 < bytes.length) {
stringBuilder.append(BASE64.charAt(tempBytes[index * 3 + 2] & 0x3F));
}
index++;
}
while (stringBuilder.length() % 3 > 0) {
stringBuilder.append((char) PADDING);
}
return stringBuilder.toString();
}
/**
* Decode given Base64 string to byte arrays
*
* Will return a zero-length array for given base64 string is null
or string length is 0.
*
* 将给定的Base64编码字符串解码为二进制字节数组
* 如果给定的字符串长度为0,则返回长度为0的二进制字节数组
*
* StringUtils.base64Decode(null) = []
* StringUtils.base64Decode("") = []
* StringUtils.base64Decode("SGVsbG8gV29ybGQ=") = [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
*
*
* @param string Encoded Base64 string
* 编码后的Base64字符串
*
* @return Decoded byte array
* 解码后的二进制字节数组
*/
public static byte[] base64Decode(final String string) {
if (StringUtils.isEmpty(string)) {
return new byte[0];
}
String origString = string;
while (origString.charAt(origString.length() - 1) == PADDING) {
origString = origString.substring(0, origString.length() - 1);
}
byte[] bytes = new byte[origString.length() * 3 / 4];
int index = 0;
for (int i = 0; i < origString.length(); i += 4) {
int index1 = BASE64.indexOf(origString.charAt(i + 1));
bytes[index * 3] = (byte) (((BASE64.indexOf(origString.charAt(i)) << 2) | (index1 >> 4)) & MASK_BYTE_UNSIGNED);
if (index * 3 + 1 >= bytes.length) {
break;
}
int index2 = BASE64.indexOf(origString.charAt(i + 2));
bytes[index * 3 + 1] = (byte) (((index1 << 4) | (index2 >> 2)) & MASK_BYTE_UNSIGNED);
if (index * 3 + 2 >= bytes.length) {
break;
}
bytes[index * 3 + 2] = (byte) (((index2 << 6) | BASE64.indexOf(origString.charAt(i + 3))) & MASK_BYTE_UNSIGNED);
index++;
}
return bytes;
}
/**
* Encoding given string to Huffman Tree string using given code mapping
* 使用给定的编码映射表将给定的字符串编码为霍夫曼树结果字符串
*
* @param codeMapping Code mapping table
* 编码映射表
* @param content Content string
* 内容字符串
*
* @return Generated huffman result string or zero length string if content string is empty
* 生成的霍夫曼树编码字符串,当内容字符串为空字符串时返回长度为0的空字符串
*/
public static String encodeWithHuffman(final Hashtable codeMapping, final String content) {
return HuffmanTree.encodeString(codeMapping, content);
}
/**
* Convert given string to Huffman Tree result instance
* 将给定的字符串编码为霍夫曼树结果实例对象
*
* @param content Content string
* 内容字符串
*
* @return Generated huffman result instance or null if content string is empty
* 生成的霍夫曼结果实例对象,当内容字符串为空字符串时返回null
*/
public static HuffmanTree.Result encodeWithHuffman(final String content) {
HuffmanTree huffmanTree = new HuffmanTree();
String temp = content;
List checkedStrings = new ArrayList<>();
while (!temp.isEmpty()) {
String keyword = temp.substring(0, 1);
if (!checkedStrings.contains(keyword)) {
huffmanTree.insertNode(new HuffmanTree.Node(keyword,
StringUtils.countOccurrencesOf(content, keyword)));
checkedStrings.add(keyword);
}
temp = temp.substring(1);
}
huffmanTree.build();
return huffmanTree.encodeString(content);
}
/**
* Check that the given string is MD5 value
* 检查给定的字符串是否符合MD5结果字符串格式
*
* @param string The given string will check
* 将要检查的字符串
*
* @return true
if matched or false
not match
* 检查匹配返回true
,不匹配返回false
*/
@Deprecated
public static boolean isMD5(final String string) {
return StringUtils.notBlank(string) && StringUtils.matches(string.toLowerCase(), RegexGlobals.MD5_VALUE);
}
/**
* Check that the given string is UUID value
* 检查给定的字符串是否符合UUID结果字符串格式
*
* @param string The given string will check
* 将要检查的字符串
*
* @return true
if matched or false
not match
* 检查匹配返回true
,不匹配返回false
*/
public static boolean isUUID(final String string) {
return StringUtils.notBlank(string) && StringUtils.matches(string.toLowerCase(), RegexGlobals.UUID);
}
/**
* Check that the given string is XML string
* 检查给定的字符串是否符合XML字符串格式
*
* @param string The given string will check
* 将要检查的字符串
*
* @return true
if matched or false
not match
* 检查匹配返回true
,不匹配返回false
*/
public static boolean isXML(final String string) {
return StringUtils.notBlank(string) && StringUtils.matches(string, RegexGlobals.XML);
}
/**
* Check that the given string is Luhn string
* 检查给定的字符串是否符合Luhn字符串格式
*
* @param string The given string will check
* 将要检查的字符串
*
* @return true
if matched or false
not match
* 检查匹配返回true
,不匹配返回false
*/
public static boolean isLuhn(final String string) {
return StringUtils.validateCode(string, CodeType.Luhn);
}
/**
* Check that the given string is China Social Credit Code string
* 检查给定的字符串是否符合中国统一信用代码字符串格式
*
* @param string The given string will check
* 将要检查的字符串
*
* @return true
if matched or false
not match
* 检查匹配返回true
,不匹配返回false
*/
public static boolean isChnSocialCredit(final String string) {
return StringUtils.validateCode(string, CodeType.CHN_Social_Code);
}
/**
* Check that the given string is China ID Code string
* 检查给定的字符串是否符合中国身份证号字符串格式
*
* @param string The given string will check
* 将要检查的字符串
*
* @return true
if matched or false
not match
* 检查匹配返回true
,不匹配返回false
*/
public static boolean isChnId(final String string) {
return StringUtils.validateCode(string, CodeType.CHN_ID_Code);
}
/**
* Check that the given string is phone number string
* Support country code start with 00 or +
* 检查给定的字符串是否符合电话号码字符串格式
* 支持国家代码以00或+开头
*
* @param string The given string will check
* 将要检查的字符串
*
* @return true
if matched or false
not match
* 检查匹配返回true
,不匹配返回false
*/
public static boolean isPhoneNumber(final String string) {
return StringUtils.notBlank(string) && StringUtils.matches(string, RegexGlobals.PHONE_NUMBER);
}
/**
* Check that the given string is E-Mail string
* 检查给定的字符串是否符合电子邮件字符串格式
*
* @param string The given string will check
* 将要检查的字符串
*
* @return true
if matched or false
not match
* 检查匹配返回true
,不匹配返回false
*/
public static boolean isEMail(final String string) {
return StringUtils.notBlank(string) && StringUtils.matches(string, RegexGlobals.EMAIL_ADDRESS);
}
/**
* Check that the given CharSequence is null
or length 0.
* Will return true
for a CharSequence that purely consists of blank.
* 检查给定的 CharSequence 是否为 null
或长度为 0。
* 对于完全由空白组成的 CharSequence 将返回 true
。
*
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty(Globals.DEFAULT_VALUE_STRING) = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("Hello") = false
*
*
* @param str The CharSequence to check (maybe null
)
* 要检查的 CharSequence (可能 null
)
*
* @return true
if the CharSequence is null or length 0.
* 如果 CharSequence 为 null 或长度为 0,则 true
*/
public static boolean isEmpty(final CharSequence str) {
return !StringUtils.hasLength(str);
}
/**
* Check that the given CharSequence is neither null
nor of length 0.
* Will return true
for a CharSequence that purely consists of blank.
* 检查给定的 CharSequence 既不是 null
也不是长度为 0。
* 对于完全由空白组成的 CharSequence 将返回 true
。
*
*
* StringUtils.notNull(null) = false
* StringUtils.notNull(Globals.DEFAULT_VALUE_STRING) = false
* StringUtils.notNull(" ") = true
* StringUtils.notNull("Hello") = true
*
*
* @param str The CharSequence to check (maybe null
)
* 要检查的 CharSequence (可能 null
)
*
* @return true
if the CharSequence is not null
and has length.
* 如果 CharSequence 不为null
并且有长度,则为 true
*/
public static boolean notNull(final CharSequence str) {
return (str != null && str.length() > 0);
}
/**
* Check that the given CharSequence is neither null
nor only blank character.
* Will return true
for a CharSequence that purely consists of blank.
* 检查给定的 CharSequence 既不是 null
也不是空白字符。
* 对于完全由空白组成的 CharSequence 将返回 true
。
*
*
* StringUtils.notBlank(null) = false
* StringUtils.notBlank(Globals.DEFAULT_VALUE_STRING) = false
* StringUtils.notBlank(" ") = false
* StringUtils.notBlank("Hello") = true
*
*
* @param str the String to check (maybe null
)
* 要检查的字符串(可能 null
)
*
* @return true
if the CharSequence is not null
or blank character and has length.
* 如果 CharSequence 不是null
或空白字符并且有长度,则true
*/
public static boolean notBlank(final String str) {
return (str != null && !str.trim().isEmpty());
}
/**
* Check that the given CharSequence is neither null
nor of length 0.
* Will return true
for a CharSequence that purely consists of blank.
* 检查给定的 CharSequence 既不是 null
也不是长度为 0
* 对于完全由空白组成的 CharSequence 将返回 true
。
*
*
* StringUtils.hasLength(null) = false
* StringUtils.hasLength(Globals.DEFAULT_VALUE_STRING) = false
* StringUtils.hasLength(" ") = true
* StringUtils.hasLength("Hello") = true
*
*
* @param str The CharSequence to check (maybe null
)
* 要检查的 CharSequence (可能 null
)
*
* @return true
if the CharSequence is not null
and has length.
* 如果 CharSequence 不为 null
并且有长度,则为 true
。
*/
public static boolean hasLength(final CharSequence str) {
return (str != null && str.length() > 0);
}
/**
* Check whether the given CharSequence has actual text.
*
* More specifically, returns true
if the string not null
,
* its length is greater than 0, and it contains at least one non-blank character.
*
* 检查给定的 CharSequence 是否具有实际文本。
*
* 更具体地说,如果字符串不为 null
、其长度大于 0,并且至少包含一个非空白字符,则返回 true
。
*
* @see java.lang.Character#isWhitespace java.lang.Character#isWhitespace
*
* StringUtils.hasText(null) = false
* StringUtils.hasText(Globals.DEFAULT_VALUE_STRING) = false
* StringUtils.hasText(" ") = false
* StringUtils.hasText("12345") = true
* StringUtils.hasText(" 12345 ") = true
*
*
* @param str The CharSequence to check (maybe null
)
* 要检查的 CharSequence (可能 null
)
*
* @return
* true
if the CharSequence is not null
, its length is greater than 0,
* and it does not contain blank only
*
* true
如果 CharSequence 不为 null
,其长度大于 0,且不包含空白
*/
public static boolean hasText(final CharSequence str) {
if (hasLength(str)) {
return Boolean.FALSE;
}
int strLen = str.length();
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return Boolean.TRUE;
}
}
return Boolean.FALSE;
}
/**
* returns the length of the string by detect encoding
*
* returns the length of the string by wrapping it in a byte buffer with
* the appropriate charset of the input string and returns the limit of the
* byte buffer
*
* 通过检测编码返回字符串的长度
* 通过使用输入字符串的适当字符集将字符串包装在字节缓冲区中来返回字符串的长度,并返回字节缓冲区的限制
*
* @param strIn the string
* 输入字符串
*
* @return length of the string
* 字符串长度
*/
public static int encodedStringLength(final String strIn) {
return encodedStringLength(strIn, detectCharset(strIn));
}
/**
* returns the length of the string in the input encoding
* 返回输入编码中字符串的长度
*
* @param strIn the string
* 输入字符串
* @param charset charset encoding
* charset encoding
*
* @return
* length of the string
* 字符串长度
*/
public static int encodedStringLength(final String strIn, final String charset) {
if (StringUtils.isEmpty(strIn)) {
return Globals.INITIALIZE_INT_VALUE;
}
if (StringUtils.isEmpty(charset)) {
return Globals.DEFAULT_VALUE_INT;
}
ByteBuffer byteBuffer;
try {
byteBuffer = ByteBuffer.wrap(strIn.getBytes(charset));
} catch (UnsupportedEncodingException e) {
byteBuffer = ByteBuffer.wrap(strIn.getBytes(Charset.defaultCharset()));
}
return byteBuffer.limit();
}
/**
* Detects the encoding charset for the input string
* 检测输入字符串的编码字符集
*
* @param strIn the string
* 输入字符串
*
* @return charset for the String
* 字符串的字符集
*/
public static String detectCharset(final String strIn) {
if (StringUtils.isEmpty(strIn)) {
return Globals.DEFAULT_VALUE_STRING;
}
try {
String tempString = new String(strIn.getBytes(Globals.CHARSET_CP850), Globals.CHARSET_CP850);
if (strIn.equals(tempString)) {
return Globals.CHARSET_CP850;
}
tempString = new String(strIn.getBytes(Globals.CHARSET_GBK), Globals.CHARSET_GBK);
if (strIn.equals(tempString)) {
return Globals.CHARSET_GBK;
}
tempString = new String(strIn.getBytes(Globals.DEFAULT_ENCODING), Globals.DEFAULT_ENCODING);
if (strIn.equals(tempString)) {
return Globals.DEFAULT_ENCODING;
}
} catch (Exception e) {
LOGGER.error("Detect_Charset_Error", strIn);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Stack_Message_Error", e);
}
}
return Globals.DEFAULT_SYSTEM_CHARSET;
}
/**
* Check whether the given CharSequence contains any blank characters.
* 检查给定的 CharSequence 是否包含任何空白字符。
* @see java.lang.Character#isWhitespace java.lang.Character#isWhitespace
*
* @param str The CharSequence to check (maybe null
)
* 要检查的 CharSequence (可能 null
)
*
* @return true
if the CharSequence is not empty and contains at least 1 blank character
* 如果 CharSequence 不为空且包含至少 1 个空白字符,则为 true
*/
public static boolean containsWhitespace(final CharSequence str) {
if (hasLength(str)) {
return false;
}
int strLen = str.length();
for (int i = 0; i < strLen; i++) {
if (Character.isWhitespace(str.charAt(i))) {
return true;
}
}
return false;
}
/**
* Check whether the given String contains any blank characters.
* 检查给定的字符串是否包含任何空白字符。
* @see #containsWhitespace(CharSequence) #containsWhitespace(CharSequence)
*
* @param str the String to check (maybe null
)
* 要检查的字符串(可能 null
)
*
* @return true
if the String is not empty and contains at least 1 blank character.
* 如果字符串不为空且至少包含 1 个空白字符,则为 true
*/
public static boolean containsWhitespace(final String str) {
return containsWhitespace((CharSequence) str);
}
/**
* Check whether the given String contains any blank characters.
* 修剪给定字符串的前导和尾随空白。
* @see java.lang.Character#isWhitespace java.lang.Character#isWhitespace
*
* @param str the String to check
* 要检查的字符串
*
* @return the trimmed String
* 修剪后的字符串
*/
public static String trimWhitespace(final String str) {
String string = StringUtils.trimLeadingWhitespace(str);
string = StringUtils.trimTrailingWhitespace(string);
return string;
}
/**
* Trim all blank from the given String: leading, trailing, and in between characters.
* 修剪给定字符串中的所有空白:前导、尾随和字符之间。
* @see java.lang.Character#isWhitespace java.lang.Character#isWhitespace
*
* @param str the String to check
* 要检查的字符串
*
* @return the trimmed String
* 修剪后的字符串
*/
public static String trimAllWhitespace(final String str) {
if (hasLength(str)) {
return str;
}
StringBuilder buf = new StringBuilder(str);
int index = 0;
while (buf.length() > index) {
if (Character.isWhitespace(buf.charAt(index))) {
buf.deleteCharAt(index);
} else {
index++;
}
}
return buf.toString();
}
/**
* Trim leading blank from the given String.
* 修剪给定字符串中的前导空白。
* @see java.lang.Character#isWhitespace java.lang.Character#isWhitespace
*
* @param str the String to check
* 要检查的字符串
*
* @return the trimmed String
* 修剪后的字符串
*/
public static String trimLeadingWhitespace(final String str) {
if (hasLength(str)) {
return str;
}
StringBuilder buf = new StringBuilder(str);
while (buf.length() > 0 && Character.isWhitespace(buf.charAt(0))) {
buf.deleteCharAt(0);
}
return buf.toString();
}
/**
* Trim trailing blank from the given String.
* 修剪给定字符串中的尾随空白。
*
* @see java.lang.Character#isWhitespace java.lang.Character#isWhitespace
*
* @param str the String to check
* 要检查的字符串
*
* @return the trimmed String
* 修剪后的字符串
*/
public static String trimTrailingWhitespace(final String str) {
if (hasLength(str)) {
return str;
}
StringBuilder buf = new StringBuilder(str);
while (buf.length() > 0 && Character.isWhitespace(buf.charAt(buf.length() - 1))) {
buf.deleteCharAt(buf.length() - 1);
}
return buf.toString();
}
/**
* Trim all occurrences of the supplied leading character from the given String.
* 修剪给定字符串中所有出现的所提供的前导字符。
*
* @param str the String to check
* 要检查的字符串
* @param leadingCharacter the leading character to be trimmed
* 要修剪的前导字符
*
* @return the trimmed String
* 修剪后的字符串
*/
public static String trimLeadingCharacter(final String str, final char leadingCharacter) {
if (hasLength(str)) {
return str;
}
StringBuilder buf = new StringBuilder(str);
while (buf.length() > 0 && buf.charAt(0) == leadingCharacter) {
buf.deleteCharAt(0);
}
return buf.toString();
}
/**
* Trim all occurrences of the supplied trailing character from the given String.
* 修剪给定字符串中所有出现的所提供的尾随字符。
*
* @param str the String to check
* 要检查的字符串
* @param trailingCharacter the trailing character to be trimmed
* 要修剪的尾随字符
*
* @return the trimmed String
* 修剪后的字符串
*/
public static String trimTrailingCharacter(final String str, final char trailingCharacter) {
if (hasLength(str)) {
return str;
}
StringBuilder buf = new StringBuilder(str);
while (buf.length() > 0 && buf.charAt(buf.length() - 1) == trailingCharacter) {
buf.deleteCharAt(buf.length() - 1);
}
return buf.toString();
}
/**
* Test if the given String starts with the specified prefix, ignoring the upper/lower case.
* 测试给定的字符串是否以指定的前缀开头,忽略大小写。
* @see java.lang.String#startsWith java.lang.String#startsWith
*
* @param str the String to check
* 要检查的字符串
* @param prefix the prefix to look for
* 要查找的前缀
*
* @return check result
* 检查结果
*/
public static boolean startsWithIgnoreCase(final String str, final String prefix) {
if (str == null || prefix == null) {
return false;
}
if (str.startsWith(prefix)) {
return true;
}
if (str.length() < prefix.length()) {
return false;
}
String lcStr = str.substring(0, prefix.length()).toLowerCase();
String lcPrefix = prefix.toLowerCase();
return lcStr.equals(lcPrefix);
}
/**
* Test if the given String ends with the specified suffix, ignoring the upper/lower case.
* 测试给定的字符串是否以指定的后缀结尾,忽略大小写。
* @see java.lang.String#endsWith java.lang.String#endsWith
*
* @param str the String to check
* 要检查的字符串
* @param suffix the suffix to look for
* 要查找的后缀
*
* @return check result
* 检查结果
*/
public static boolean endsWithIgnoreCase(final String str, final String suffix) {
if (str == null || suffix == null) {
return false;
}
if (str.endsWith(suffix)) {
return true;
}
if (str.length() < suffix.length()) {
return false;
}
String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();
String lcSuffix = suffix.toLowerCase();
return lcStr.equals(lcSuffix);
}
/**
* Check given string contains emoji information.
* 检查给定字符串是否包含表情符号信息。
*
* @param str the String to check
* 要检查的字符串
*
* @return check result
* 检查结果
*/
public static boolean containsEmoji(final String str) {
if (StringUtils.notBlank(str)) {
int length = str.length();
for (int i = 0; i < length; i++) {
char c = str.charAt(i);
if (0xd800 <= c && c <= 0xdbff) {
if (length > 1) {
char next = str.charAt(i + 1);
int result = ((c - 0xd800) * 0x400) + (next - 0xdc00) + 0x10000;
if (0x1d000 <= result && result <= 0x1f77f) {
return true;
}
}
} else {
if ((0x2100 <= c && c <= 0x27ff && c != 0x263b)
|| (0x2805 <= c && c <= 0x2b07)
|| (0x3297 <= c && c <= 0x3299)
|| c == 0xa9 || c == 0xae || c == 0x303d
|| c == 0x3030 || c == 0x2b55 || c == 0x2b1c
|| c == 0x2b1b || c == 0x2b50) {
return true;
}
if (length > 1 && i < (length - 1)) {
char next = str.charAt(i + 1);
if (next == 0x20e3) {
return true;
}
}
}
}
}
return Boolean.FALSE;
}
/**
* Test whether the given string matches the given substring at the given index.
* 测试给定字符串是否与给定索引处的给定子字符串匹配。
*
* @param str the original string (or StringBuilder)
* 原始字符串(或 StringBuilder)
* @param index the index in the original string to start matching against
* 原始字符串中开始匹配的索引
* @param substring the substring to match at the given index
* 在给定索引处匹配的子字符串
*
* @return check result
* 检查结果
*/
public static boolean substringMatch(final CharSequence str, final int index, final CharSequence substring) {
for (int j = 0; j < substring.length(); j++) {
int i = index + j;
if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {
return false;
}
}
return true;
}
/**
* Count the occurrences of the substring in search string.
* 计算搜索字符串中子字符串的出现次数。
*
* @param str string to search in. Return 0 if this is null.
* 搜索的字符串。如果为 null,则返回 0。
* @param sub string to search for. Return 0 if this is null.
* 要搜索的子字符串。如果为 null,则返回 0。
*
* @return count result
* 计数结果
*/
public static int countOccurrencesOf(final String str, final String sub) {
if (str == null || sub == null || str.isEmpty() || sub.isEmpty()) {
return 0;
}
int count = 0, pos = 0, idx;
while ((idx = str.indexOf(sub, pos)) != -1) {
++count;
pos = idx + sub.length();
}
return count;
}
/**
* Replace all occurrences of a substring within a string with another string.
* 将字符串中所有出现的子字符串替换为另一个字符串。
*
* @param inString String to examine
* 要检查的字符串
* @param oldPattern String to replace
* 要替换的字符串
* @param newPattern String to insert
* 替换后的字符串
*
* @return String with the replacements
* 替换后的字符串
*/
public static String replace(final String inString, final String oldPattern, final String newPattern) {
if (inString == null || oldPattern == null || newPattern == null) {
return Globals.DEFAULT_VALUE_STRING;
}
StringBuilder stringBuilder = new StringBuilder();
// output StringBuilder we'll build up
int pos = 0; // our position in the old string
int index = inString.indexOf(oldPattern);
// the index of an occurrence we've found, or -1
int patLen = oldPattern.length();
while (index >= 0) {
stringBuilder.append(inString, pos, index);
stringBuilder.append(newPattern);
pos = index + patLen;
index = inString.indexOf(oldPattern, pos);
}
stringBuilder.append(inString.substring(pos));
// remember to append any characters to the right of a match
return stringBuilder.toString();
}
/**
* Delete all occurrences of the given substring.
* 删除所有出现的给定子字符串。
*
* @param inString String to examine
* 要检查的字符串
* @param pattern the pattern to delete all occurrences of
* 要删除的出现模式
*
* @return String with the deleted
* 删除后的字符串
*/
public static String delete(final String inString, final String pattern) {
return replace(inString, pattern, Globals.DEFAULT_VALUE_STRING);
}
/**
* Delete any character in a given String.
* 删除给定字符串中的任何字符。
*
* @param inString String to examine
* 要检查的字符串
* @param charsToDelete a set of characters to delete. E.g. "az\n" will delete 'a's, 'z's and new lines.
* 要删除的一组字符。例如。 "az\n" 将删除 'a'、'z' 和换行符。
*
* @return String with the deleted
* 删除后的字符串
*/
public static String deleteAny(final String inString, final String charsToDelete) {
if (hasLength(inString) || hasLength(charsToDelete)) {
return inString;
}
StringBuilder out = new StringBuilder();
for (int i = 0; i < inString.length(); i++) {
char c = inString.charAt(i);
if (charsToDelete.indexOf(c) == -1) {
out.append(c);
}
}
return out.toString();
}
/**
* Quote the given String with single quotes.
* 用单引号引用给定的字符串。
*
* @param str the input String (e.g. "myString")
* 输入字符串(例如"myString")
*
* @return the quoted String (e.g. "'myString'"), or null
if the input was null
* 带引号的字符串(例如“'myString'“),如果输入为 null
,则为 null
*/
public static String quote(final String str) {
return (str != null ? "'" + str + "'" : null);
}
/**
* Turn the given Object into a String with single quotes if it is a String; keeping the Object as-is else.
* 如果给定的对象是字符串,则将其转换为带单引号的字符串;保持对象原样。
*
* @param obj the input Object (e.g. "myString")
* 输入对象(例如"myString")
*
* @return the quoted String (e.g. "'myString'"), or the input object as-is if not a String
* 带引号的字符串(例如"'myString'"),或者如果不是字符串则按原样输入对象
*/
public static Object quoteIfString(final Object obj) {
return (obj instanceof String ? quote((String) obj) : obj);
}
/**
*
* Unqualified a string qualified by a '.' dot character.
* For example, "this.name.is.qualified", returns "qualified".
*
* 返回由“.”分割名称的最后一段字符串。例如,"this.name.is.qualified"返回"qualified"。
*
* @param qualifiedName the qualified name
* 要分割的名称
*
* @return qualified string
* 分割后的字符串
*/
public static String unqualified(final String qualifiedName) {
return unqualified(qualifiedName, '.');
}
/**
*
* Unqualified a string qualified by a separator character.
* For example, "this:name:is:qualified" returns "qualified" if using a ':' separator.
*
* 返回由指定分隔符分割名称的最后一段字符串。例如,"this:name:is:qualified"如果使用":"分割则返回"qualified"。
*
* @param qualifiedName the qualified name
* 要分割的名称
* @param separator the separator
* 分隔符
*
* @return qualified string
* 分割后的字符串
*/
public static String unqualified(final String qualifiedName, final char separator) {
return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);
}
/**
* changing the first letter to the upper case
* 转换字符串的第一个字符为大写
*
* @param str the String to capitalize, maybe null
* 要大写的字符串,可能为 null
*
* @return the capitalized String, or null
if parameter str is null
* 大写字符串,如果参数 str 为 null
,则为 null
*/
public static String capitalize(final String str) {
return changeFirstCharacterCase(str, Boolean.TRUE);
}
/**
* changing the first letter to the lower case
* 转换字符串的第一个字符为小写
*
* @param str the String to uncapitalize, maybe null
* 要小写的字符串,可能为 null
*
* @return the uncapitalized String, or null
if parameter str is null
* 小写字符串,如果参数 str 为 null
,则为 null
*/
public static String uncapitalized(final String str) {
return changeFirstCharacterCase(str, Boolean.FALSE);
}
/**
* Extract the filename from the given path, e.g. "mypath/myfile.txt" -> "myfile.txt".
* 从给定路径中提取文件名,例如“mypath/myfile.txt”->“myfile.txt”。
*
* @param path the file path (maybe null
)
* 文件路径(可能null
)
*
* @return the extracted filename, or null
if none
* 提取的文件名,如果没有则为 null
*/
public static String getFilename(final String path) {
if (path == null) {
return null;
}
String cleanPath = cleanPath(path);
int separatorIndex = cleanPath.lastIndexOf(Globals.DEFAULT_PAGE_SEPARATOR);
return (separatorIndex != -1 ? cleanPath.substring(separatorIndex + 1) : cleanPath);
}
/**
* Extract the filename extension from the given path, e.g. "mypath/myfile.txt" -> "txt".
* 从给定路径中提取文件扩展名,例如“mypath/myfile.txt”->“txt”。
*
* @param path the file path (maybe null
)
* 文件路径(可能null
)
*
* @return the extracted filename extension, or null
if none
* 提取的文件扩展名,如果没有则为 null
*/
public static String getFilenameExtension(final String path) {
if (path == null) {
return Globals.DEFAULT_VALUE_STRING;
}
int sepIndex = path.lastIndexOf(Globals.EXTENSION_SEPARATOR);
return (sepIndex != -1 ? path.substring(sepIndex + 1) : Globals.DEFAULT_VALUE_STRING);
}
/**
* Strip the filename extension from the given path, e.g. "mypath/myfile.txt" -> "mypath/myfile".
* 从给定路径中去除文件扩展名,例如“mypath/myfile.txt”->“mypath/myfile”。
*
* @param path the file path (maybe null
)
* 文件路径(可能null
)
*
* @return the path with stripped filename extension, or null
if none
* 剥离文件扩展名后的路径,如果没有则为 null
*/
public static String stripFilenameExtension(final String path) {
if (path == null) {
return null;
}
int sepIndex = path.lastIndexOf(Globals.EXTENSION_SEPARATOR);
return (sepIndex != -1 ? path.substring(0, sepIndex) : path);
}
/**
* Apply the given relative path to the given path, assuming standard Java folder separation (i.e. "/" separators)
* 将给定的相对路径应用于给定的路径,假设标准 Java 文件夹分隔(即“/”分隔符)
*
* @param path the path to start from (usually a full file path)
* 起始路径(通常是完整文件路径)
* @param relativePath the relative path to apply (relative to the full file path above)
* 要应用的相对路径(相对于上面的完整文件路径)
*
* @return the full file path that results from applying the relative path
* 应用相对路径产生的完整文件路径
*/
public static String applyRelativePath(final String path, final String relativePath) {
int separatorIndex = path.lastIndexOf(Globals.DEFAULT_PAGE_SEPARATOR);
if (separatorIndex != -1) {
String newPath = path.substring(0, separatorIndex);
if (!relativePath.startsWith(Globals.DEFAULT_PAGE_SEPARATOR)) {
newPath += Globals.DEFAULT_PAGE_SEPARATOR;
}
return newPath + relativePath;
} else {
return relativePath;
}
}
/**
* Normalize the path by suppressing sequences like "path/.." and inner simple dots.
*
* The result is convenient for path comparison. For other uses, notice that Windows separators ("\") are replaced by simple slashes.
*
* 转换给定字符串中的相对路径为标准路径
* 结果便于路径比较。对于其他用途,请注意 Windows 分隔符(“\”)被简单的斜杠替换。
*
* @param path the original path
* 原始路径
*
* @return the normalized path
* 标准化路径
*/
public static String cleanPath(final String path) {
String pathToUse = path;
// Strip prefix from path to analyze, to not treat it as part of the
// first path element. This is necessary to correctly parse paths like
// "file:core/../core/io/Resource.class", where the ".." Should just
// strip the first "core" directory while keeping the "file:" prefix.
int prefixIndex = pathToUse.indexOf(":");
String prefix = Globals.DEFAULT_VALUE_STRING;
if (prefixIndex != -1) {
prefix = pathToUse.substring(0, prefixIndex + 1);
pathToUse = pathToUse.substring(prefixIndex + 1);
}
String[] pathArray = delimitedListToStringArray(pathToUse, Globals.DEFAULT_PAGE_SEPARATOR);
List pathElements = new LinkedList<>();
int tops = 0;
for (int i = pathArray.length - 1; i >= 0; i--) {
if (!CURRENT_PATH.equals(pathArray[i])) {
if (TOP_PATH.equals(pathArray[i])) {
// Registering the top path found.
tops++;
} else {
if (tops > 0) {
// Merging the path element with corresponding to the top path.
tops--;
} else {
// Normal path element found.
pathElements.add(0, pathArray[i]);
}
}
}
}
// Remaining top paths need to be retained.
for (int i = 0; i < tops; i++) {
pathElements.add(0, TOP_PATH);
}
return prefix + collectionToDelimitedString(pathElements, Globals.DEFAULT_PAGE_SEPARATOR);
}
/**
* Compare two paths after normalization of them.
* 比较标准化后的两条路径。
*
* @param path1 first path for comparison
* 第一条比较路径
* @param path2 second path for comparison
* 第二条比较路径
*
* @return Compare result
* 比较结果
*/
public static boolean pathEquals(final String path1, final String path2) {
return cleanPath(path1).equals(cleanPath(path2));
}
/**
* Parse the given localeString
into a Locale
.
* 将给定的 localeString
解析为 Locale
。
*
* @param localeString
* the locale string, following Locale's
toString()
* format ("en", "en_UK", etc);
* also accepts spaces as separators, as an alternative to underscore
*
*
* 语言环境字符串,遵循 Locale's
toString()
格式(“en”、“en_UK”等);
* 还接受空格作为分隔符替换下划线分隔符
*
*
* @return a corresponding Locale
instance
* 相应的 Locale
实例
*/
public static Locale parseLocaleString(final String localeString) {
if (localeString == null) {
return null;
}
String[] parts = tokenizeToStringArray(localeString, "_", false, false);
if (parts == null) {
return null;
}
String language = (parts.length > 0 ? parts[0] : Globals.DEFAULT_VALUE_STRING);
String country = (parts.length > 1 ? parts[1] : Globals.DEFAULT_VALUE_STRING);
String variant = Globals.DEFAULT_VALUE_STRING;
if (parts.length >= 2) {
// There is definitely a variant, and it is everything after the country
// code sans the separator between the country code and the variant.
int endIndexOfCountryCode = localeString.indexOf(country) + country.length();
// Strip off any leading '_' and blank, what's left is the variant.
variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));
if (variant.startsWith("_")) {
variant = trimLeadingCharacter(variant, '_');
}
}
return (!language.isEmpty() ? new Locale(language, country, variant) : null);
}
//---------------------------------------------------------------------
// Convenience methods for working with String arrays
//---------------------------------------------------------------------
/**
* Append the given String to the given String array
* returning a new array consisting of the input array contents plus the given String.
* 将给定的字符串附加到给定的字符串数组
* 返回一个由输入数组内容加上给定字符串组成的新数组。
*
* @param array the array to append to (can be null
)
* 要附加到的数组(可以为 null
)
* @param str the String to append
* 要附加的字符串
*
* @return the new array (never null
)
* 新数组(不会为null
)
*/
public static String[] addStringToArray(final String[] array, final String str) {
if (CollectionUtils.isEmpty(array)) {
return new String[]{str};
}
String[] newArr = new String[array.length + 1];
System.arraycopy(array, 0, newArr, 0, array.length);
newArr[array.length] = str;
return newArr;
}
/**
* Concatenate the given String arrays into one
* with overlapping array elements included twice. The order of elements in the original arrays is preserved.
* 将给定的字符串数组连接成一个字符串
* 重叠的数组元素包含两次。原始数组中元素的顺序被保留。
*
* @param array1 the first array (can be null
)
*
* @param array2 the second array (can be null
)
* 第二个数组(可以为 null
)
*
* @return the new array (null
if both given arrays were null
)
* 新数组(如果两个给定数组均为 null
,则为 null
)
*/
public static String[] concatenateStringArrays(final String[] array1, final String[] array2) {
if (array1 == null) {
return array2;
}
if (array2 == null) {
return array1;
}
if (CollectionUtils.isEmpty(array1) && CollectionUtils.isEmpty(array2)) {
return new String[0];
}
String[] newArr = new String[array1.length + array2.length];
System.arraycopy(array1, 0, newArr, 0, array1.length);
System.arraycopy(array2, 0, newArr, array1.length, array2.length);
return newArr;
}
/**
* Merge the given String arrays into one
*
* with overlapping array elements only included once.
* The order of elements in the original arrays is preserved
* (except for overlapping elements, which are only included on their first occurrence).
*
* 将给定的字符串数组合并为一个字符串数组
* 重叠的数组元素包含两次。原始数组中元素的顺序被保留(重叠元素除外,这些元素仅在第一次出现时包含在内)。
*
* @param array1 the first array (can be null
)
* 第一个数组(可以为 null
)
* @param array2 the second array (can be null
)
* 第二个数组(可以为 null
)
*
* @return the new array (null
if both given arrays were null
)
* 新数组(如果两个给定数组均为 null
,则为 null
)
*/
public static String[] mergeStringArrays(final String[] array1, final String... array2) {
if (array1 == null) {
return array2;
}
if (array2 == null) {
return array1;
}
if (CollectionUtils.isEmpty(array1) && CollectionUtils.isEmpty(array2)) {
return new String[0];
}
List result = new ArrayList<>(Arrays.asList(array1));
for (String str : array2) {
if (!result.contains(str)) {
result.add(str);
}
}
return toStringArray(result);
}
/**
* Turn given sources String arrays into sorted arrays.
* 将给定的源字符串数组转换为排序数组。
*
* @param array the source array
* 源数组
*
* @return the sorted array (never null
)
* 排序后的数组(不会为null
)
*/
public static String[] sortStringArray(final String[] array) {
if (CollectionUtils.isEmpty(array)) {
return new String[0];
}
Arrays.sort(array);
return array;
}
/**
* Copy the given Collection into a String array. The Collection must contain String elements only.
* 将给定的集合复制到 String 数组中。集合必须仅包含字符串元素。
*
* @param collection the collection to copy
* 要复制的集合
*
* @return the String array (null
if the passed-in collection was null
)
* 字符串数组(如果传入的集合为 null
,则为 null
)
*/
public static String[] toStringArray(final Collection collection) {
if (collection == null) {
return new String[0];
}
return collection.toArray(new String[0]);
}
/**
* Copy the given enumeration into a String array. The enumeration must contain String elements only.
* 将给定的枚举复制到字符串数组中。枚举必须仅包含 String 元素。
*
* @param enumeration the enumeration to copy
* 要复制的枚举
*
* @return the String array (null
if the passed-in enumeration was null
)
* 字符串数组(如果传入的枚举为 null
,则为 null
)
*/
public static String[] toStringArray(final Enumeration enumeration) {
if (enumeration == null) {
return new String[0];
}
List list = Collections.list(enumeration);
return list.toArray(new String[0]);
}
/**
* Trim the elements of the given string array, calling String.trim()
on each of them.
* 修剪给定字符串数组的元素,对每个元素调用 String.trim()
。
*
* @param array the original String array
* 原始字符串数组
*
* @return the resulting array (of the same size) with trimmed elements
* 带有修剪元素的结果数组(相同大小)
*/
public static String[] trimArrayElements(final String[] array) {
if (CollectionUtils.isEmpty(array)) {
return new String[0];
}
String[] result = new String[array.length];
for (int i = 0; i < array.length; i++) {
String element = array[i];
result[i] = (element != null ? element.trim() : null);
}
return result;
}
/**
* Remove duplicate Strings from the given array. Also sorts the array, as it uses a TreeSet.
* 从给定数组中删除重复的字符串。同时对数组进行排序,类似使用 TreeSet。
*
* @param array the String array
* 字符串数组
*
* @return an array without duplicates, in natural sort order
* 没有重复项的数组,按自然排序顺序
*/
public static String[] removeDuplicateStrings(final String[] array) {
if (CollectionUtils.isEmpty(array)) {
return array;
}
Set set = new TreeSet<>();
Collections.addAll(set, array);
return toStringArray(set);
}
/**
* Split a String at the first occurrence of the delimiter. Does not include the delimiter in the result.
* 在第一次出现分隔符时分割字符串。结果中不包含分隔符。
*
* @param toSplit the string to split
* 要分割的字符串
* @param delimiter to split the string up with
* 分割字符串
*
* @return
* a two element array with index 0 being before the delimiter,
* and index 1 being after the delimiter (neither element includes the delimiter);
* or null
if the delimiter wasn't found in the given input String
*
*
* 一个二元素数组,索引 0 位于分隔符之前,索引 1 位于分隔符之后(两个元素都不包含分隔符);
* 或 null
如果在给定的输入字符串中找不到分隔符
*
*/
public static String[] split(final String toSplit, final String delimiter) {
if (hasLength(toSplit) || hasLength(delimiter)) {
return null;
}
int offset = toSplit.indexOf(delimiter);
if (offset < 0) {
return new String[]{toSplit};
}
String beforeDelimiter = toSplit.substring(0, offset);
String afterDelimiter = toSplit.substring(offset + delimiter.length());
return new String[]{beforeDelimiter, afterDelimiter};
}
/**
* Take an array Strings and split each element based on the given delimiter.
*
* A Properties
instance is then generated, with the left of the
* delimiter providing the key, and the right of the delimiter providing the value.
* Will trim both the key and value before adding them to the Properties
instance.
*
* 获取一个字符串数组并根据给定的分隔符分割每个元素。
*
* 生成一个Properties
实例对象,键值为分隔符前方的内容,属性值为分隔符后方的内容。
* 键值和属性值字符串在添加到Properties
对象前执行修剪操作。
*
*
* @param array the array to process
* 要处理的数组
* @param delimiter to split each element using (typically the equals symbol)
* 使用分隔符分割每个元素(通常是等于符号)
*
* @return
* a Properties
instance representing the array contents,
* or null
if the array to process was null or empty.
*
* 表示数组内容的 Properties
实例,如果要处理的数组为 null 或空,则为 null
。
*/
public static Properties splitArrayElementsIntoProperties(final String[] array, final String delimiter) {
return splitArrayElementsIntoProperties(array, delimiter, null);
}
/**
* Take an array Strings and split each element based on the given delimiter.
*
* A Properties
instance is then generated, with the left of the
* delimiter providing the key, and the right of the delimiter providing the value.
* Will trim both the key and value before adding them to the Properties
instance.
*
* 获取一个字符串数组并根据给定的分隔符分割每个元素。
*
* 生成一个Properties
实例对象,键值为分隔符前方的内容,属性值为分隔符后方的内容。
* 键值和属性值字符串在添加到Properties
对象前执行修剪操作。
*
*
* @param array the array to process
* 要处理的数组
* @param delimiter to split each element using (typically the equals symbol)
* 使用分隔符分割每个元素(通常是等于符号)
* @param charsToDelete
* one or more characters to remove from each element prior to attempting
* the split operation (typically the quotation mark symbol),
* or null
if no removal should occur
*
*
* 在尝试拆分操作之前要从每个元素中删除的一个或多个字符(通常是引号符号),如果不应该删除,则为 null
*
*
* @return
* a Properties
instance representing the array contents,
* or null
if the array to process was null or empty.
*
* 表示数组内容的 Properties
实例,如果要处理的数组为 null 或空,则为 null
。
*/
public static Properties splitArrayElementsIntoProperties(final String[] array, final String delimiter,
final String charsToDelete) {
if (CollectionUtils.isEmpty(array)) {
return null;
}
Properties result = new Properties();
for (String string : array) {
String element = string;
if (charsToDelete != null) {
element = deleteAny(string, charsToDelete);
}
String[] splitterElement = split(element, delimiter);
if (splitterElement == null) {
continue;
}
result.setProperty(splitterElement[0].trim(), splitterElement[1].trim());
}
return result;
}
/**
* Tokenize the given String into a String array via a StringTokenizer.
*
* Trims tokens and omits empty tokens.
* The given delimiters string is supposed to consist of any number of
* delimiter characters. Each of those characters can be used to separate
* tokens. A delimiter is always a single character; for multi-character
* delimiters, consider using delimitedListToStringArray
*
* 通过 StringTokenizer 将给定的字符串标记为字符串数组。
*
* 修剪标记并省略空标记。给定的分隔符字符串应该由任意数量的分隔符字符组成。这些字符中的每一个都可以用于分隔标记。
* 分隔符始终是单个字符;对于多字符分隔符,请考虑使用 delimitedListToStringArray
*
* @see java.util.StringTokenizer
* @see java.lang.String#trim() java.lang.String#trim()
* @see StringUtils#tokenizeToStringArray(String, String, boolean, boolean)
*
* @param str the String to tokenize
* 要处理的字符串
* @param delimiters the delimiter characters, assembled as String (each of those characters is individually considered as delimiter).
* 分隔符字符,组装为字符串(每个字符都被单独视为分隔符)。
*
* @return an array of the tokens (null
if the input String was null
)
* 处理后的字符串数组(如果输入字符串为 null
,则为 null
)
*/
public static String[] tokenizeToStringArray(final String str, final String delimiters) {
return tokenizeToStringArray(str, delimiters, Boolean.TRUE, Boolean.TRUE);
}
/**
* Tokenize the given String into a String array via a StringTokenizer.
*
* The given delimiters string is supposed to consist of any number of
* delimiter characters. Each of those characters can be used to separate
* tokens. A delimiter is always a single character; for multi-character
* delimiters, consider using delimitedListToStringArray
*
* 通过 StringTokenizer 将给定的字符串标记为字符串数组。
*
* 给定的分隔符字符串应该由任意数量的分隔符字符组成。这些字符中的每一个都可以用于分隔标记。
* 分隔符始终是单个字符;对于多字符分隔符,请考虑使用 delimitedListToStringArray
*
* @see java.util.StringTokenizer
* @see java.lang.String#trim() java.lang.String#trim()
* @see StringUtils#delimitedListToStringArray
*
* @param str the String to tokenize
* 要处理的字符串
* @param delimiters
* the delimiter characters, assembled as String (each of those characters
* is individually considered as delimiter).
*
* 分隔符字符,组装为字符串(每个字符都被单独视为分隔符)。
* @param trimTokens trim the tokens via String's trim
* 通过 String 的 trim
修剪标记
* @param ignoreEmptyTokens
* omit empty tokens from the result array (only applies to tokens that are empty
* after trimming; StringTokenizer will not consider subsequent delimiters
* as token in the first place).
*
*
* 从结果数组中省略空标记(仅适用于修剪后为空的标记;StringTokenizer 首先不会将后续分隔符视为标记)。
*
*
* @return an array of the tokens (null
if the input String was null
)
* 处理后的字符串数组(如果输入字符串为 null
,则为 null
)
*/
public static String[] tokenizeToStringArray(final String str, final String delimiters, final boolean trimTokens,
final boolean ignoreEmptyTokens) {
if (str == null) {
return null;
}
StringTokenizer st = new StringTokenizer(str, delimiters);
List tokens = new ArrayList<>();
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (trimTokens) {
token = token.trim();
}
if (!ignoreEmptyTokens || !token.isEmpty()) {
tokens.add(token);
}
}
return toStringArray(tokens);
}
/**
* Take a String which is a delimited list and convert it to a String array.
*
* A single delimiter can consist of more than one character: It will still
* be considered as single delimiter string, rather than as a bunch of potential
* delimiter characters - in contrast to tokenizeToStringArray
.
*
* 获取一个分隔列表的字符串并将其转换为字符串数组。
*
* 单个分隔符可以包含多个字符:它仍将被视为单个分隔符字符串,
* 而不是一堆潜在的分隔符 - 与 tokenizeToStringArray
不同。
*
*
* @param str the input String
* 输入字符串
* @param delimiter
* the delimiter between elements (this is a single delimiter,
* rather than a bunch individual delimiter characters)
*
* 元素之间的分隔符(这是单个分隔符,而不是一堆单独的分隔符)
*
* @return an array of the tokens in the list
* 列表中标记的数组
*/
public static String[] delimitedListToStringArray(final String str, final String delimiter) {
return delimitedListToStringArray(str, delimiter, null);
}
/**
* Take a String which is a delimited list and convert it to a String array.
*
* A single delimiter can consist of more than one character: It will still
* be considered as single delimiter string, rather than as a bunch of potential
* delimiter characters - in contrast to tokenizeToStringArray
.
*
* 获取一个分隔列表的字符串并将其转换为字符串数组。
*
* 单个分隔符可以包含多个字符:它仍将被视为单个分隔符字符串,
* 而不是一堆潜在的分隔符 - 与 tokenizeToStringArray
不同。
*
*
* @param str the input String
* 输入字符串
* @param delimiter
* the delimiter between elements (this is a single delimiter,
* rather than a bunch individual delimiter characters)
*
* 元素之间的分隔符(这是单个分隔符,而不是一堆单独的分隔符)
* @param charsToDelete
* a set of characters to delete. Useful for deleting unwanted line breaks:
* e.g. "\r\n\f" will delete all new lines, line feeds in a String.
*
*
* 要删除的一组字符。对于删除不需要的换行符很有用:例如“\r\n\f”将删除字符串中的所有新行、换行符。
*
*
* @return an array of the tokens in the list
* 列表中标记的数组
*/
public static String[] delimitedListToStringArray(final String str, final String delimiter,
final String charsToDelete) {
if (str == null) {
return new String[0];
}
if (delimiter == null) {
return new String[]{str};
}
List result = new ArrayList<>();
if (Globals.DEFAULT_VALUE_STRING.equals(delimiter)) {
for (int i = 0; i < str.length(); i++) {
result.add(deleteAny(str.substring(i, i + 1), charsToDelete));
}
} else {
int pos = 0;
int delPos;
while ((delPos = str.indexOf(delimiter, pos)) != -1) {
result.add(deleteAny(str.substring(pos, delPos), charsToDelete));
pos = delPos + delimiter.length();
}
if (!str.isEmpty() && pos <= str.length()) {
// Add rest of String, but not in case of empty input.
result.add(deleteAny(str.substring(pos), charsToDelete));
}
}
return toStringArray(result);
}
/**
* Convert a CSV list into an array of Strings.
* 将 CSV 列表转换为字符串数组。
*
* @param str the input String
* 输入字符串
*
* @return an array of Strings, or the empty array in case of empty input
* 字符串数组,或者空数组(如果输入为空)
*/
public static String[] commaDelimitedListToStringArray(final String str) {
return delimitedListToStringArray(str, ",");
}
/**
* Convert a CSV list into an array of Strings. Note that this will suppress duplicates.
* 将 CSV 列表转换为字符串数组。请注意,此操作将移除重复项。
*
* @param str the input String
* 输入字符串
*
* @return an array of Strings, or the empty array in case of empty input
* 字符串数组,或者空数组(如果输入为空)
*/
public static Set commaDelimitedListToSet(final String str) {
Set set = new TreeSet<>();
String[] tokens = commaDelimitedListToStringArray(str);
Collections.addAll(set, tokens);
return set;
}
/**
* Convenience method to return a Collection as a delimited (e.g. CSV) String. E.g. useful for toString()
implementations.
* 将集合用分隔连接(例如 CSV)字符串返回的便捷方法。例如。常用于 toString()
实现。
*
* @param coll the Collection to display
* 要显示的集合
*
* @return the delimited String
* 拼接后的字符串
*/
public static String collectionToCommaDelimitedString(final Collection coll) {
return collectionToDelimitedString(coll, ",");
}
/**
* Convenience method to return a Collection as a delimited (e.g. CSV) String. E.g. useful for toString()
implementations.
* 将集合用分隔连接(例如 CSV)字符串返回的便捷方法。例如。常用于 toString()
实现。
*
* @param coll the Collection to display
* 要显示的集合
* @param delimiter the delimiter to use (probably a ",")
* 要使用的分隔符(常见为“,”)
*
* @return the delimited String
* 拼接后的字符串
*/
public static String collectionToDelimitedString(final Collection coll, final String delimiter) {
return collectionToDelimitedString(coll, delimiter, Globals.DEFAULT_VALUE_STRING, Globals.DEFAULT_VALUE_STRING);
}
/**
* Convenience method to return a Collection as a delimited (e.g. CSV) String. E.g. useful for toString()
implementations.
* 将集合用分隔连接(例如 CSV)字符串返回的便捷方法。例如。常用于 toString()
实现。
*
* @param coll the Collection to display
* 要显示的集合
* @param delimiter the delimiter to use (probably a ",")
* 要使用的分隔符(常见为“,”)
* @param prefix the String to start each element with
* 每个元素的开头字符串
* @param suffix the String to end each element with
* 每个元素的结尾字符串
*
* @return the delimited String
* 拼接后的字符串
*/
public static String collectionToDelimitedString(final Collection coll, final String delimiter,
final String prefix, final String suffix) {
if (CollectionUtils.isEmpty(coll)) {
return Globals.DEFAULT_VALUE_STRING;
}
StringBuilder sb = new StringBuilder();
Iterator it = coll.iterator();
while (it.hasNext()) {
sb.append(prefix).append(it.next()).append(suffix);
if (it.hasNext()) {
sb.append(delimiter);
}
}
return sb.toString();
}
/**
* Check the given string contains search string, ignore case
* 检查给定的字符串是否包含搜索字符串,忽略大小写
*
* @param string The given string
* 给定的字符串
* @param search the search string
* 搜索字符串
*
* @return Check result
* 检查结果
*/
public static boolean containsIgnoreCase(final String string, final String search) {
if (string == null || search == null) {
return false;
}
int length = search.length();
int maxLength = string.length() - length;
for (int i = 0; i < maxLength; i++) {
if (string.regionMatches(Boolean.TRUE, i, search, Globals.INITIALIZE_INT_VALUE, length)) {
return Boolean.TRUE;
}
}
return Boolean.FALSE;
}
/**
* Convenience method to return a Object array as a delimited (e.g. CSV) String. E.g. useful for toString()
implementations.
* 将对象数组用分隔连接(例如 CSV)字符串返回的便捷方法。例如。常用于 toString()
实现。
*
* @param arr the String array to display
* 要显示的对象数组
*
* @return the delimited String
* 拼接后的字符串
*/
public static String arrayToCommaDelimitedString(final Object[] arr) {
return arrayToDelimitedString(arr, ",");
}
/**
* Convenience method to return a Object array as a delimited (e.g. CSV) String. E.g. useful for toString()
implementations.
* 将对象数组用分隔连接(例如 CSV)字符串返回的便捷方法。例如。常用于 toString()
实现。
*
* @param arr the String array to display
* 要显示的对象数组
* @param delimiter the delimiter to use (probably a ",")
* 要使用的分隔符(常见为“,”)
*
* @return the delimited String
* 拼接后的字符串
*/
public static String arrayToDelimitedString(final Object[] arr, final String delimiter) {
if (CollectionUtils.isEmpty(arr)) {
return Globals.DEFAULT_VALUE_STRING;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
if (i > 0) {
sb.append(delimiter);
}
sb.append(arr[i]);
}
return sb.toString();
}
/**
* Convenience method to return a JavaBean object as a string.
* 将JavaBean实例对象转换为字符串
*
* @param object JavaBean object
* JavaBean实例对象
* @param stringType Target string type
* 目标字符串类型
* @param formatOutput format output string
* 格式化输出字符串
*
* @return the converted string
* 转换后的字符串
*/
public static String objectToString(final Object object, final StringType stringType, final boolean formatOutput) {
ObjectMapper objectMapper;
switch (stringType) {
case JSON:
objectMapper = new ObjectMapper().disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
break;
case YAML:
objectMapper = new ObjectMapper(new YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER))
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
break;
default:
return Globals.DEFAULT_VALUE_STRING;
}
try {
return formatOutput
? objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object)
: objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
LOGGER.error("Convert_String_Error");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Stack_Message_Error", e);
}
}
return Globals.DEFAULT_VALUE_STRING;
}
/**
* Parse string to target JavaBean instance.
* 解析字符串为目标JavaBean实例对象
*
* @param target JavaBean class
* 目标JavaBean类
* @param string The string will parse
* 要解析的字符串
* @param beanClass target JavaBean class
* 目标JavaBean类
* @param schemaPaths XML schema path(Maybe schema uri or local path)
* XML描述文件路径(可能为描述文件URI或本地文件路径)
*
* @return Converted object instance
* 转换后的实例对象
*/
public static T stringToObject(final String string, final Class beanClass, final String... schemaPaths) {
return stringToObject(string, Globals.DEFAULT_ENCODING, beanClass, schemaPaths);
}
/**
* Parse string to target JavaBean instance.
* 解析字符串为目标JavaBean实例对象
*
* @param target JavaBean class
* 目标JavaBean类
* @param string The string will parse
* 要解析的字符串
* @param stringType The string type
* 字符串类型
* @param beanClass target JavaBean class
* 目标JavaBean类
* @param schemaPaths XML schema path(Maybe schema uri or local path)
* XML描述文件路径(可能为描述文件URI或本地文件路径)
*
* @return Converted object instance
* 转换后的实例对象
*/
public static T stringToObject(final String string, final StringType stringType, final Class beanClass,
final String... schemaPaths) {
return stringToObject(string, stringType, Globals.DEFAULT_ENCODING, beanClass, schemaPaths);
}
/**
* Parse string to target JavaBean instance.
* 解析字符串为目标JavaBean实例对象
*
* @param target JavaBean class
* 目标JavaBean类
* @param string The string will parse
* 要解析的字符串
* @param encoding String charset encoding
* 字符串的字符集编码
* @param beanClass target JavaBean class
* 目标JavaBean类
* @param schemaPaths XML schema path(Maybe schema uri or local path)
* XML描述文件路径(可能为描述文件URI或本地文件路径)
*
* @return Converted object instance
* 转换后的实例对象
*/
public static T stringToObject(final String string, final String encoding,
final Class beanClass, final String... schemaPaths) {
if (StringUtils.isEmpty(string)) {
LOGGER.error("Parse_Empty_String_Error");
return null;
}
if (string.startsWith("<")) {
return stringToObject(string, StringType.XML, encoding, beanClass, schemaPaths);
}
if (string.startsWith("{")) {
return stringToObject(string, StringType.JSON, encoding, beanClass, schemaPaths);
}
return stringToObject(string, StringType.YAML, encoding, beanClass, schemaPaths);
}
/**
* Parse string to target JavaBean instance list.
* 解析字符串为目标JavaBean实例对象列表
*
* @param target JavaBean class
* 目标JavaBean类
* @param string The string will parse
* 要解析的字符串
* @param encoding String charset encoding
* 字符串的字符集编码
* @param beanClass target JavaBean class
* 目标JavaBean类
*
* @return Converted object instance list
* 转换后的实例对象列表
*/
public static List stringToList(final String string, final String encoding, final Class beanClass) {
if (StringUtils.isEmpty(string)) {
LOGGER.error("Parse_Empty_String_Error");
return null;
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Parse_String_Debug", string, encoding, beanClass.getName());
}
String stringEncoding = (encoding == null) ? Globals.DEFAULT_ENCODING : encoding;
try (InputStream inputStream = new ByteArrayInputStream(string.getBytes(stringEncoding))) {
return streamToList(inputStream, beanClass);
} catch (IOException e) {
LOGGER.error("Parse_String_Error");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Stack_Message_Error", e);
}
return new ArrayList<>();
}
}
/**
* Parse file content to target JavaBean instance list.
* 解析文件内容为目标JavaBean实例对象列表
*
* @param target JavaBean class
* 目标JavaBean类
* @param filePath File path
* 文件地址
* @param beanClass target JavaBean class
* 目标JavaBean类
* @param schemaPaths XML schema path(Maybe schema uri or local path)
* XML描述文件路径(可能为描述文件URI或本地文件路径)
*
* @return Converted object instance list
* 转换后的实例对象列表
*/
public static T fileToObject(final String filePath, final Class beanClass, final String... schemaPaths) {
if (StringUtils.isEmpty(filePath) || !FileUtils.isExists(filePath)) {
LOGGER.error("Not_Found_File_Error", filePath);
return null;
}
String extName = StringUtils.getFilenameExtension(filePath);
try (InputStream inputStream = FileUtils.loadFile(filePath)) {
switch (extName.toLowerCase()) {
case "json":
return streamToObject(inputStream, StringType.JSON, beanClass, Globals.DEFAULT_VALUE_STRING);
case "xml":
return streamToObject(inputStream, StringType.XML, beanClass, schemaPaths);
case "yml":
case "yaml":
return streamToObject(inputStream, StringType.YAML, beanClass, Globals.DEFAULT_VALUE_STRING);
default:
return null;
}
} catch (IOException e) {
LOGGER.error("Parse_File_Error");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Stack_Message_Error", e);
}
}
return null;
}
/**
* Parse content of input stream to target JavaBean instance list.
* 解析输入流中的内容为目标JavaBean实例对象列表
*
* @param target JavaBean class
* 目标JavaBean类
* @param inputStream Input stream instance
* 输入流对象实例
* @param beanClass target JavaBean class
* 目标JavaBean类
*
* @return Converted object instance list
* 转换后的实例对象列表
*
* @throws IOException the io exception
* If an error occurs when read data from input stream
* 如果从输入流中读取数据时出现异常
*/
public static List streamToList(final InputStream inputStream, final Class beanClass) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, beanClass);
return objectMapper.readValue(inputStream, javaType);
}
/**
* Parse content of input stream to target JavaBean instance list.
* 解析输入流中的内容为目标JavaBean实例对象列表
*
* @param target JavaBean class
* 目标JavaBean类
* @param inputStream Input stream instance
* 输入流对象实例
* @param stringType The string type
* 字符串类型
* @param beanClass target JavaBean class
* 目标JavaBean类
* @param schemaPaths XML schema path(Maybe schema uri or local path)
* XML描述文件路径(可能为描述文件URI或本地文件路径)
*
* @return Converted object instance list
* 转换后的实例对象列表
*
* @throws IOException the io exception
* If an error occurs when read data from input stream
* 如果从输入流中读取数据时出现异常
*/
public static T streamToObject(final InputStream inputStream, final StringType stringType,
final Class beanClass, final String... schemaPaths) throws IOException {
if (StringType.XML.equals(stringType)) {
try {
Unmarshaller unmarshaller = JAXBContext.newInstance(beanClass).createUnmarshaller();
if (schemaPaths.length > 0) {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schemaFactory.setResourceResolver(new SchemaResourceResolver());
try {
Source[] sources = new Source[schemaPaths.length];
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setNamespaceAware(Boolean.TRUE);
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
for (int i = 0; i < schemaPaths.length; i++) {
String locationPath = SCHEMA_MAPPING.getOrDefault(schemaPaths[i], schemaPaths[i]);
InputStream in = FileUtils.loadFile(locationPath);
Document document = docBuilder.parse(in);
sources[i] = new DOMSource(document, locationPath);
IOUtils.closeStream(in);
}
unmarshaller.setSchema(schemaFactory.newSchema(sources));
} catch (ParserConfigurationException e) {
LOGGER.error("Load_Schemas_Error");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Stack_Message_Error", e);
}
return null;
}
}
return beanClass.cast(unmarshaller.unmarshal(inputStream));
} catch (JAXBException | SAXException e) {
LOGGER.error("Parse_File_Error");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Stack_Message_Error", e);
}
return null;
}
} else {
ObjectMapper objectMapper;
switch (stringType) {
case JSON:
objectMapper = new ObjectMapper().disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
break;
case YAML:
objectMapper = new ObjectMapper(new YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER))
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
break;
default:
return null;
}
return objectMapper.readValue(inputStream, beanClass);
}
}
/**
* Parse string to data map.
* 解析字符串为数据映射表
*
* @param string The string will parse
* 要解析的字符串
* @param stringType The string type
* 字符串类型
*
* @return Converted data map
* 转换后的数据映射表
*/
public static Map dataToMap(final String string, final StringType stringType) {
ObjectMapper objectMapper;
switch (stringType) {
case JSON:
objectMapper = new ObjectMapper().disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
break;
case YAML:
objectMapper = new ObjectMapper(new YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER))
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
break;
default:
return new HashMap<>();
}
try {
return objectMapper.readValue(string, new TypeReference<>() {
});
} catch (Exception e) {
LOGGER.error("Convert_To_Data_Map_Error");
if (StringUtils.LOGGER.isDebugEnabled()) {
StringUtils.LOGGER.debug("Stack_Message_Error", e);
}
}
return new HashMap<>();
}
/**
* Replace special XMl character with converted character in string.
* 替换XML特殊字符为转义字符串
*
* @param sourceString The string will process
* 要处理的字符串
*
* @return Replaced string
* 替换后的字符串
*/
public static String formatTextForXML(final String sourceString) {
if (sourceString == null) {
return null;
}
int strLen;
StringBuilder reString = new StringBuilder();
String deString;
strLen = sourceString.length();
for (int i = 0; i < strLen; i++) {
char ch = sourceString.charAt(i);
switch (ch) {
case '<':
deString = "<";
break;
case '>':
deString = ">";
break;
case '\"':
deString = """;
break;
case '&':
deString = "&";
break;
case 13:
deString = Globals.DEFAULT_VALUE_STRING;
break;
default:
deString = Globals.DEFAULT_VALUE_STRING + ch;
}
reString.append(deString);
}
return reString.toString();
}
/**
* Replace converted character with special XMl character in string.
* 替换转义字符串为XML特殊字符
*
* @param sourceString The string will process
* 要处理的字符串
*
* @return Replaced string
* 替换后的字符串
*/
public static String formatForText(final String sourceString) {
if (StringUtils.isEmpty(sourceString)) {
return sourceString;
}
String replaceString = replace(sourceString, "&", "&");
replaceString = replace(replaceString, "<", "<");
replaceString = replace(replaceString, ">", ">");
replaceString = replace(replaceString, """, "\"");
replaceString = replace(replaceString, "'", "'");
replaceString = replace(replaceString, "\\\\", "\\");
replaceString = replace(replaceString, "\\n", Character.toString(FileUtils.LF));
replaceString = replace(replaceString, "\\r", Character.toString(FileUtils.CR));
replaceString = replace(replaceString, "
", Character.toString(FileUtils.CR));
return replaceString;
}
/**
* Replace special HTML character with converted character in string.
* 替换HTML特殊字符为转义字符串
*
* @param sourceString The string will process
* 要处理的字符串
*
* @return Replaced string
* 替换后的字符串
*/
public static String textToHtml(final String sourceString) {
int strLen;
StringBuilder reString = new StringBuilder();
strLen = sourceString.length();
for (int i = 0; i < strLen; i++) {
char ch = sourceString.charAt(i);
switch (ch) {
case '<':
reString.append("<");
break;
case '>':
reString.append(">");
break;
case '\"':
reString.append(""");
break;
case '&':
reString.append("&");
break;
case '\'':
reString.append("'");
break;
case '\\':
reString.append("\\\\");
break;
case FileUtils.LF:
reString.append("\\n");
break;
case FileUtils.CR:
reString.append("
");
break;
default:
reString.append(Globals.DEFAULT_VALUE_STRING).append(ch);
}
}
return reString.toString();
}
/**
* Match given string with regex string
* 将给定的字符串与给定的正则表达式字符串做匹配
*
* @param str The string will match
* 要匹配的字符串
* @param regex regex string
* 正则表达式字符串
*
* @return Match result
* 匹配结果
*/
public static boolean matches(final String str, final String regex) {
if (StringUtils.isEmpty(str) || StringUtils.isEmpty(regex)) {
return Boolean.FALSE;
}
return str.matches(regex);
}
/**
* Replace template string using matched value from input string by regex
* 使用正则表达式从输入字符串中提取数据并替换模板字符串中对应的值
*
* @param str input string
* 输入字符串
* @param regex regex string
* 正则表达式字符串
* @param template template string
* 模板字符串
*
* @return Replaced string, or null
if input string not matched
* 替换后的字符串,如果输入字符串未匹配则返回null
*/
public static String replaceWithRegex(final String str, final String regex, final String template) {
return replaceWithRegex(str, regex, template, Globals.DEFAULT_VALUE_STRING);
}
/**
* Replace template string using matched value from input string by regex
* 使用正则表达式从输入字符串中提取数据并替换模板字符串中对应的值
*
* @param str input string
* 输入字符串
* @param regex regex string
* 正则表达式字符串
* @param template template string
* 模板字符串
* @param substringPrefix the substring prefix
* 需要去掉的替换值前缀字符
*
* @return Replaced string, or null
if input string not matched
* 替换后的字符串,如果输入字符串未匹配则返回null
*/
public static String replaceWithRegex(final String str, final String regex, final String template,
final String substringPrefix) {
if (!matches(str, regex)) {
return null;
}
String matchResult = template;
Matcher matcher = Pattern.compile(regex).matcher(str);
if (matcher.find()) {
for (int i = 0; i < matcher.groupCount(); i++) {
int index = i + 1;
String matchValue = matcher.group(index);
if (matchValue == null) {
matchValue = Globals.DEFAULT_VALUE_STRING;
} else {
if (StringUtils.notBlank(substringPrefix) && matchValue.startsWith(substringPrefix)) {
matchValue = matchValue.substring(substringPrefix.length());
}
}
matchResult = replace(matchResult, "$" + index, matchValue);
}
return matchResult;
}
return str;
}
/**
* Generate random string by given length
* 根据给定的字符串长度生成随机字符串
*
* @param length string length
* 字符串长度
*
* @return Generated string
* 生成的字符串
*/
public static String randomString(final int length) {
StringBuilder generateKey = new StringBuilder();
SecureRandom random = new SecureRandom();
for (int i = 0; i < length; i++) {
generateKey.append(AUTHORIZATION_CODE_ITEMS.charAt(random.nextInt(AUTHORIZATION_CODE_ITEMS.length())));
}
return generateKey.toString();
}
/**
* Generate random number string by given length
* 根据给定的字符串长度生成随机字符串
*
* @param length string length
* 字符串长度
*
* @return Generated string
* 生成的字符串
*/
public static String randomNumber(final int length) {
StringBuilder generateKey = new StringBuilder();
for (int i = 0; i < length; i++) {
generateKey.append((char) (Math.random() * 10 + '0'));
}
return generateKey.toString();
}
/**
* Generate random index char
* 生成随机索引字符
*
* @param beginIndex the beginning index
* 起始索引
* @param endIndex the end index
* 终止索引
*
* @return Generated character
* 生成的字符
*/
public static char randomIndex(final int beginIndex, final int endIndex) {
return (char) (Math.random() * (endIndex - beginIndex + 1) + beginIndex + '0');
}
/**
* Generate random char
* 生成随机字符
*
* @param beginIndex the beginning index
* 起始索引
* @param endIndex the end index
* 终止索引
*
* @return Generated character
* 生成的字符
*/
public static char randomChar(final int beginIndex, final int endIndex) {
return (char) (Math.random() * (endIndex - beginIndex + 1) + beginIndex + 'a');
}
/**
* Check given character is space
* 检查给定字符是否为空格
*
* @param letter will check for character
* 将要检查的字符
*
* @return Check result
* 检查结果
*/
public static boolean isSpace(final char letter) {
return (letter == 8 || letter == 9 || letter == 10 || letter == 13 || letter == 32 || letter == 160);
}
/**
* Check given character is english character
* 检查给定字符是否为英文字母
*
* @param letter will check for character
* 将要检查的字符
*
* @return Check result
* 检查结果
*/
public static boolean isEnglish(final char letter) {
return (letter > 'a' && letter < 'z') || (letter > 'A' && letter < 'Z');
}
/**
* Check given character is number
* 检查给定字符是否为数字
*
* @param letter will check for character
* 将要检查的字符
*
* @return Check result
* 检查结果
*/
public static boolean isNumber(final char letter) {
return letter >= '0' && letter <= '9';
}
/**
* Check given character is Chinese/Japanese/Korean
* 检查给定字符是否为中文/日文/韩文
*
* @param letter will check for character
* 将要检查的字符
*
* @return Check result
* 检查结果
*/
public static boolean isCJK(final char letter) {
UnicodeBlock unicodeBlock = UnicodeBlock.of(letter);
return (unicodeBlock == UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
|| unicodeBlock == UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| unicodeBlock == UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
|| unicodeBlock == UnicodeBlock.GENERAL_PUNCTUATION
|| unicodeBlock == UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
//全角数字字符和日韩字符
|| unicodeBlock == UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
//韩文字符集
|| unicodeBlock == UnicodeBlock.HANGUL_SYLLABLES
|| unicodeBlock == UnicodeBlock.HANGUL_JAMO
|| unicodeBlock == UnicodeBlock.HANGUL_COMPATIBILITY_JAMO
//日文字符集
|| unicodeBlock == UnicodeBlock.HIRAGANA //平假名
|| unicodeBlock == UnicodeBlock.KATAKANA //片假名
|| unicodeBlock == UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS);
}
/**
* Check given code string is valid of given code type
* 检查给定代码字符穿是否符合指定代码类型的算法
*
* @param code will check for code
* 将要检查的代码字符串
* @param codeType Code type
* 代码类型
*
* @return Check result
* 检查结果
*/
public static boolean validateCode(final String code, final CodeType codeType) {
if (StringUtils.isEmpty(code)) {
return Boolean.FALSE;
}
switch (codeType) {
case CHN_ID_Code:
String cardCode = code.toUpperCase();
if (StringUtils.matches(cardCode, RegexGlobals.CHN_ID_Card)) {
int validateCode = CHN_ID_CARD_CODE.indexOf(cardCode.charAt(17));
if (validateCode != -1) {
int sigma = 0;
for (int i = 0; i < 17; i++) {
sigma += (int) (Character.digit(cardCode.charAt(i), 10) * (Math.pow(2, 17 - i) % 11));
}
return validateCode == ((12 - (sigma % 11)) % 11);
}
}
break;
case CHN_Social_Code:
String creditCode = code.toUpperCase();
if (StringUtils.matches(creditCode, RegexGlobals.CHN_Social_Credit)) {
int validateCode = CHN_SOCIAL_CREDIT_CODE.indexOf(creditCode.charAt(17));
if (validateCode != -1) {
int sigma = 0;
for (int i = 0; i < 17; i++) {
sigma += (int) (CHN_SOCIAL_CREDIT_CODE.indexOf(creditCode.charAt(i)) * (Math.pow(3, i) % 31));
}
int authCode = 31 - (sigma % 31);
return (authCode == 31) ? (validateCode == 0) : (authCode == validateCode);
}
}
break;
case Luhn:
if (StringUtils.matches(code, RegexGlobals.LUHN)) {
int result = 0, length = code.length();
for (int i = 0; i < length; i++) {
int currentCode = Character.getNumericValue(code.charAt(length - i - 1));
if (i % 2 == 1) {
currentCode *= 2;
if (currentCode > 9) {
currentCode -= 9;
}
}
result += currentCode;
}
return result % 10 == 0;
}
break;
}
return Boolean.FALSE;
}
/**
* Enumeration of String Type
* 字符串类型的枚举类
*/
public enum StringType {
JSON, YAML, XML, SIMPLE, DEFAULT
}
/**
* Enumeration of Code Type
* 代码类型的枚举类
*/
public enum CodeType {
CHN_Social_Code, CHN_ID_Code, Luhn
}
/**
* Parse string to target JavaBean instance.
* 解析字符串为目标JavaBean实例对象
*
* @param target JavaBean class
* 目标JavaBean类
* @param string The string will parse
* 要解析的字符串
* @param stringType The string type
* 字符串类型
* @param encoding String charset encoding
* 字符串的字符集编码
* @param beanClass target JavaBean class
* 目标JavaBean类
* @param schemaPaths XML schema path(Maybe schema uri or local path)
* XML描述文件路径(可能为描述文件URI或本地文件路径)
*
* @return Converted object instance
* 转换后的实例对象
*/
private static T stringToObject(final String string, final StringType stringType, final String encoding,
final Class beanClass, final String... schemaPaths) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Parse_String_Debug", string, encoding, beanClass.getName());
}
if (StringType.SIMPLE.equals(stringType)) {
try {
return ClassUtils.parseSimpleData(string, beanClass);
} catch (ParseException e) {
LOGGER.error("Parse_Simple_Data_Error");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Stack_Message_Error", e);
}
}
}
String stringEncoding = (encoding == null) ? Globals.DEFAULT_ENCODING : encoding;
try (InputStream inputStream = new ByteArrayInputStream(string.getBytes(stringEncoding))) {
return streamToObject(inputStream, stringType, beanClass, schemaPaths);
} catch (IOException e) {
LOGGER.error("Parse_String_Error");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Stack_Message_Error", e);
}
}
return null;
}
/**
* change the first letter to the given capitalize
* 转换字符串的第一个字符为大/小写
*
* @param str the String to capitalize, maybe null
* 要大写的字符串,可能为 null
* @param capitalize capitalize status
* 大小写状态
*
* @return the capitalized String, or null
if parameter str is null
* 大写字符串,如果参数 str 为 null
,则为 null
*/
private static String changeFirstCharacterCase(final String str, final boolean capitalize) {
if (str == null || str.isEmpty()) {
return str;
}
StringBuilder buf = new StringBuilder(str.length());
if (capitalize) {
buf.append(Character.toUpperCase(str.charAt(0)));
} else {
buf.append(Character.toLowerCase(str.charAt(0)));
}
buf.append(str.substring(1));
return buf.toString();
}
/**
* Register URL instance of schema mapping file
* 从URL实例对象中读取XML约束文档的资源映射文件内容并注册
*
* @param url URL instance
* URL实例对象
*/
private static void REGISTER_SCHEMA(final URL url) {
String basePath = url.getPath();
ConvertUtils.toMap(url, new HashMap<>())
.forEach((key, value) ->
SCHEMA_MAPPING.put(key, StringUtils.replace(basePath, SCHEMA_MAPPING_RESOURCE_PATH, value)));
}
/**
* Private constructor for StringUtils
* 字符串工具集的私有构造方法
*/
private StringUtils() {
}
/**
* Schema resource resolver for support schema mapping
* 支持自定义资源描述文件映射的资源文件解析器
*/
private static final class SchemaResourceResolver implements LSResourceResolver {
/**
* (Non-Javadoc)
* @see LSResourceResolver#resolveResource(String, String, String, String, String)
*/
@Override
public LSInput resolveResource(final String type, final String namespaceURI, final String publicId,
final String systemId, final String baseURI) {
LOGGER.debug("Resolving_Schema_Debug",
type, namespaceURI, publicId, systemId, baseURI);
String schemaLocation = baseURI.substring(0, baseURI.lastIndexOf("/") + 1);
String filePath;
if (SCHEMA_MAPPING.containsKey(namespaceURI)) {
filePath = SCHEMA_MAPPING.get(namespaceURI);
} else {
if (!systemId.contains(Globals.HTTP_PROTOCOL)) {
filePath = schemaLocation + systemId;
} else {
filePath = systemId;
}
}
try {
return new LSInputImpl(publicId, namespaceURI, FileUtils.loadFile(filePath));
} catch (IOException e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Load_Schemas_Error", e);
}
return new LSInputImpl();
}
}
}
/**
* Implement class for LSInput
* LSInput的实现类
*/
private static final class LSInputImpl implements LSInput {
private String publicId;
private String systemId;
private String baseURI;
private InputStream byteStream;
private Reader characterStream;
private String stringData;
private String encoding;
private boolean certifiedText;
/**
* Default constructor for LSInputImpl
* LSInputImpl的私有构造方法
*/
LSInputImpl() {
}
/**
* Default constructor for LSInputImpl
* LSInputImpl的私有构造方法
*
* @param publicId Public ID
* Public ID
* @param systemId Namespace URI
* 命名空间URI
* @param byteStream Input stream of schema file
* 描述文件的输入流
*/
LSInputImpl(final String publicId, final String systemId, final InputStream byteStream) {
this.publicId = publicId;
this.systemId = systemId;
this.byteStream = byteStream;
}
/**
* (Non-Javadoc)
* @see LSInput#getPublicId()
*/
@Override
public String getPublicId() {
return publicId;
}
/**
* (Non-Javadoc)
* @see LSInput#setPublicId(String)
*/
@Override
public void setPublicId(String publicId) {
this.publicId = publicId;
}
/**
* (Non-Javadoc)
* @see LSInput#getSystemId()
*/
@Override
public String getSystemId() {
return systemId;
}
/**
* (Non-Javadoc)
* @see LSInput#setSystemId(String)
*/
@Override
public void setSystemId(String systemId) {
this.systemId = systemId;
}
/**
* (Non-Javadoc)
* @see LSInput#getBaseURI()
*/
@Override
public String getBaseURI() {
return baseURI;
}
/**
* (Non-Javadoc)
* @see LSInput#setBaseURI(String)
*/
@Override
public void setBaseURI(String baseURI) {
this.baseURI = baseURI;
}
/**
* (Non-Javadoc)
* @see LSInput#getByteStream()
*/
@Override
public InputStream getByteStream() {
return byteStream;
}
/**
* (Non-Javadoc)
* @see LSInput#setByteStream(InputStream)
*/
@Override
public void setByteStream(InputStream byteStream) {
this.byteStream = byteStream;
}
/**
* (Non-Javadoc)
* @see LSInput#getCharacterStream()
*/
@Override
public Reader getCharacterStream() {
return characterStream;
}
/**
* (Non-Javadoc)
* @see LSInput#setCharacterStream(Reader)
*/
@Override
public void setCharacterStream(Reader characterStream) {
this.characterStream = characterStream;
}
/**
* (Non-Javadoc)
* @see LSInput#getStringData()
*/
@Override
public String getStringData() {
return stringData;
}
/**
* (Non-Javadoc)
* @see LSInput#setStringData(String)
*/
@Override
public void setStringData(String stringData) {
this.stringData = stringData;
}
/**
* (Non-Javadoc)
* @see LSInput#getEncoding()
*/
@Override
public String getEncoding() {
return encoding;
}
/**
* (Non-Javadoc)
* @see LSInput#setEncoding(String)
*/
@Override
public void setEncoding(String encoding) {
this.encoding = encoding;
}
/**
* (Non-Javadoc)
* @see LSInput#getCertifiedText()
*/
@Override
public boolean getCertifiedText() {
return certifiedText;
}
/**
* (Non-Javadoc)
* @see LSInput#setCertifiedText(boolean)
*/
@Override
public void setCertifiedText(boolean certifiedText) {
this.certifiedText = certifiedText;
}
}
}