常用工具类总结
HTTP Client工具类
public class HttpClientUtil {
static String ALGORITHM = "SunX509";
protected final static Logger ERROR_LOGGER = LoggerFactory
.getLogger(LogbackConfig.GATEWAY_ERROR);
private static final int READ_TIMEOUT = 20000;
private static final int CONNECT_TIMEOUT = 10000;
private static final Map<String, CloseableHttpClient> HTTP_CLIENT_CACHE = new ConcurrentHashMap<>();
public static final Map<String, Function<String, HttpRequestBase>> HTTP_REQUEST_CREATOR = new HashMap<>();
static {
HTTP_REQUEST_CREATOR.put(HttpPost.METHOD_NAME, HttpPost::new);
HTTP_REQUEST_CREATOR.put(HttpGet.METHOD_NAME, HttpGet::new);
HTTP_REQUEST_CREATOR.put(HttpPut.METHOD_NAME, HttpPut::new);
HTTP_REQUEST_CREATOR.put(HttpPatch.METHOD_NAME, HttpPatch::new);
}
protected static void execute(CloseableHttpClient httpClient, String url, String httpMethod,
Map<String, String> headers, Map<String, String> params,
String body, String requestCharset, String responseCharset,
int readTimeout, int connectTimeout) {
HttpRequestBase httpRequestBase = createHttpMethod(httpMethod, url, readTimeout,
connectTimeout);
constructParams(httpRequestBase, headers, params, body, requestCharset, MediaType.APPLICATION_JSON_VALUE);
try (CloseableHttpResponse httpResponse = httpClient.execute(httpRequestBase)) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(httpResponse.getEntity().getContent(), responseCharset))) {
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
System.out.println("Response Body: " + stringBuilder.toString());
} catch (IOException e) {
System.err.println("Error reading response body: " + e.getMessage());
}
} catch (IOException e) {
System.err.println("Request failed: " + e.getMessage());
}
}
public static CloseableHttpClient getHttpClient(GwDomainConfig domainConfig, GwCertConfig gwCertConfig) {
return HTTP_CLIENT_CACHE.computeIfAbsent(domainConfig.getDomain(), key -> {
try {
int readTimeout = Optional.ofNullable(domainConfig.getReadTimeOut()).map(Integer::parseInt).orElse(READ_TIMEOUT);
int connectTimeout = Optional.ofNullable(domainConfig.getConnectTimeOut()).map(Integer::parseInt).orElse(CONNECT_TIMEOUT);
SSLContext sslContext = HttpClientUtil.createSSLContext(domainConfig.getSslProtocol(), gwCertConfig);
HttpClientConnectionManager connectionManager = HttpClientUtil.createHttpClientConnectionManager(sslContext,
domainConfig.getSinglePoolLimit(), readTimeout);
return HttpClientUtil.createHttpClient(connectionManager, domainConfig.getSinglePoolLimit(), readTimeout, connectTimeout);
} catch (Exception e) {
ERROR_LOGGER.error(MessageFormat.format("create http client for domain [{0}]", domainConfig.getDomain()), e);
return null;
}
});
}
public static CloseableHttpClient createHttpClient(HttpClientConnectionManager manager,
int maxTotal, int readTimeout,
int connectTimeout) {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setConnectionManager(manager);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(connectTimeout).setConnectTimeout(readTimeout)
.setSocketTimeout(readTimeout).build();
httpClientBuilder.setDefaultRequestConfig(requestConfig);
HttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(0, false);
httpClientBuilder.setRetryHandler(retryHandler);
httpClientBuilder.setMaxConnTotal(maxTotal);
return httpClientBuilder.build();
}
public static SSLContext createSSLContext(String protocol, String fileName) throws Exception {
X509TrustManager customTrustManager = (X509TrustManager) createCustomTrustManager(fileName);
X509TrustManager defaultTrustManagerInner = (X509TrustManager) createDefaultTrustManagerInner();
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return ArrayUtils.addAll(customTrustManager.getAcceptedIssuers(),
defaultTrustManagerInner.getAcceptedIssuers());
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs,
String authType) throws CertificateException {
if (customTrustManager != null) {
try {
customTrustManager.checkServerTrusted(certs, authType);
} catch (CertificateException e) {
if (defaultTrustManagerInner != null) {
defaultTrustManagerInner.checkServerTrusted(certs, authType);
}
}
} else if (defaultTrustManagerInner != null) {
defaultTrustManagerInner.checkServerTrusted(certs, authType);
}
}
} };
SSLContext sslContext = SSLContext.getInstance(protocol);
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
return sslContext;
}
public static SSLContext createSSLContext(String protocol,
GwCertConfig gwCertConfig) throws Exception {
X509TrustManager customTrustManager = (X509TrustManager) createCustomTrustManagerByCertConfig(
gwCertConfig);
X509TrustManager defaultManager = (X509TrustManager) createDefaultTrustManagerInner();
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return ArrayUtils.addAll(
customTrustManager != null ? customTrustManager.getAcceptedIssuers()
: new X509Certificate[0],
defaultManager != null ? defaultManager.getAcceptedIssuers()
: new X509Certificate[0]);
}
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
if (customTrustManager != null) {
try {
customTrustManager.checkServerTrusted(chain, authType);
} catch (CertificateException e) {
if (defaultManager != null) {
defaultManager.checkServerTrusted(chain, authType);
} else {
throw e;
}
}
} else if (defaultManager != null) {
defaultManager.checkServerTrusted(chain, authType);
}
}
} };
SSLContext sslContext = SSLContext.getInstance(protocol);
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
return sslContext;
}
private static TrustManager createCustomTrustManagerByCertConfig(GwCertConfig gwCertConfig) {
if (gwCertConfig == null || gwCertConfig.getCertStoreValue() == null) {
return null;
}
switch (gwCertConfig.getCertStoreType()) {
case DATABASE:
return createCustomTrustManagerByDBCert(gwCertConfig.getCertStoreValue(),
gwCertConfig.getCertAlias());
case GCP_KMS:
return createCustomTrustManagerByGCPSecret(gwCertConfig);
default:
return null;
}
}
private static TrustManager createCustomTrustManagerByGCPSecret(GwCertConfig gwCertConfig) {
return null;
}
private static TrustManager createCustomTrustManagerByDBCert(String certContent,
String certAlias) {
try {
byte[] certBytes = certContent.getBytes(StandardCharsets.UTF_8);
Certificate certificate = CertificateFactory.getInstance("X.509")
.generateCertificate(new ByteArrayInputStream(certBytes));
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry(certAlias, certificate);
TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(ALGORITHM);
trustFactory.init(keyStore);
return trustFactory.getTrustManagers()[0];
} catch (Exception e) {
ERROR_LOGGER.error("createCustomTrustManagerByDBCert error, certAlias:{}", certAlias, e);
return null;
}
}
public static HttpClientConnectionManager createHttpClientConnectionManager(SSLContext sslContext,
int maxTotal,
int readTimeout) {
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
sslContext, new DefaultHostnameVerifier());
RegistryBuilder<ConnectionSocketFactory> registryBuilder = createRegistryBuilderBySSLConnectionSocketFactory(
sslConnectionSocketFactory);
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
registryBuilder.build());
connectionManager.setMaxTotal(maxTotal);
connectionManager.setDefaultMaxPerRoute(maxTotal);
SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(readTimeout).build();
connectionManager.setDefaultSocketConfig(socketConfig);
return connectionManager;
}
public static HttpRequestBase createHttpMethod(String httpReqType, String requestUrl,
int readTimeout, int connectTimeout) {
Function<String, HttpRequestBase> requestBaseFunction = HTTP_REQUEST_CREATOR
.get(StringUtils.upperCase(httpReqType));
HttpRequestBase httpRequestBase = requestBaseFunction.apply(requestUrl);
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom()
.setCookieSpec(CookieSpecs.IGNORE_COOKIES).setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectTimeout).setSocketTimeout(readTimeout);
httpRequestBase.setConfig(requestConfigBuilder.build());
return httpRequestBase;
}
public static void constructParams(HttpRequestBase httpMethod, Map<String, String> headers,
Map<String, String> params, String content,
String requestCharset, String contentType) {
addRequestHeader(headers, httpMethod);
addParameter(httpMethod, params, requestCharset);
if (httpMethod instanceof HttpEntityEnclosingRequestBase) {
addContent(content, (HttpEntityEnclosingRequestBase) httpMethod, requestCharset, contentType);
}
}
public static void addParameter(HttpRequestBase method, Map<String, String> params,
String requestCharset) {
if (CollectionUtils.isEmpty(params)) {
return;
}
List<NameValuePair> valuePairs = new ArrayList<>(params.size());
for (Map.Entry<String, String> entry : params.entrySet()) {
NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(),
String.valueOf(entry.getValue()));
valuePairs.add(nameValuePair);
}
HttpEntity formEntity;
try {
formEntity = new NoUrlEncodedFormEntity(valuePairs, Charset.forName(requestCharset));
AtomicBoolean hasQuery = new AtomicBoolean(
StringUtils.isNotEmpty(method.getURI().getQuery()));
StringBuilder fullUrlBuilder = new StringBuilder(method.getURI().toString());
String param = EntityUtils.toString(formEntity, Charset.forName("UTF-8"));
fullUrlBuilder.append(hasQuery.get() ? "&" : "?").append(param);
hasQuery.set(true);
method.setURI(new URI(fullUrlBuilder.toString()));
} catch (Exception e) {
}
}
public static void addRequestHeader(Map<String, String> headers, HttpRequestBase method) {
if (CollectionUtils.isEmpty(headers)) {
return;
}
Set<Map.Entry<String, String>> entries = headers.entrySet();
for (Map.Entry<String, String> entry : entries) {
method.addHeader(entry.getKey(), entry.getValue());
}
}
public static void addContent(String content, HttpEntityEnclosingRequestBase method,
String requestCharset, String contentType) {
if (StringUtils.isBlank(content)) {
return;
}
try {
switch (contentType) {
case MediaType.APPLICATION_JSON_VALUE:
StringEntity jsonEntity = new StringEntity(content, Charset.forName(requestCharset));
jsonEntity.setContentType(MediaType.APPLICATION_JSON_VALUE);
method.setEntity(jsonEntity);
break;
case MediaType.APPLICATION_FORM_URLENCODED_VALUE:
Map<String, Object> paramMap = JSON.parseObject(content,
new TypeReference<Map<String, Object>>(){});
List<NameValuePair> formParams = new ArrayList<>();
for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
if (entry.getValue() != null) {
formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
}
HttpEntity formEntity = new org.apache.http.client.entity.UrlEncodedFormEntity(
formParams, Charset.forName(requestCharset));
method.setEntity(formEntity);
break;
default:
StringEntity defaultEntity = new StringEntity(content, Charset.forName(requestCharset));
method.setEntity(defaultEntity);
break;
}
} catch (Exception e) {
ERROR_LOGGER.error("Error adding content to request body, contentType: {}", contentType, e);
throw new IorpCommonException(IorpCommonResultCodeEnum.UNKNOWN_EXCEPTION, "Error adding content to request body");
}
}
private static RegistryBuilder<ConnectionSocketFactory> createRegistryBuilderBySSLConnectionSocketFactory(SSLConnectionSocketFactory socketFactory) {
RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder
.<ConnectionSocketFactory> create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", socketFactory);
return registryBuilder;
}
private static TrustManager createDefaultTrustManagerInner() {
TrustManagerFactory defaultTrustFactory = null;
try {
defaultTrustFactory = TrustManagerFactory.getInstance(ALGORITHM);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
try {
defaultTrustFactory.init((KeyStore) null);
} catch (KeyStoreException e) {
throw new RuntimeException(e);
}
return defaultTrustFactory.getTrustManagers()[0];
}
private static TrustManager createCustomTrustManager(String fileName) {
if (StringUtils.isBlank(fileName))
return null;
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
FileInputStream fis = new FileInputStream(fileName);
X509Certificate cert = (X509Certificate) cf.generateCertificate(fis);
fis.close();
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("mycert", cert);
TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(ALGORITHM);
trustFactory.init(keyStore);
return trustFactory.getTrustManagers()[0];
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
JSON 工具类
public class JSONUtil extends JSON {
private static final String NEST_JSON_SPLIT = ">";
private static final String ARRAY_MARK = "[]";
private static final String EMPTY_STRING = "";
private static final SerializeFilter[] emptyObjectAndBigDecimalAndNoneStringValueFilters;
private static final SerializeFilter[] emptyObjectAndNoneStringValueFilters;
private static final SerializeFilter noneObjectFilters;
private static final SerializeFilter bigDecimalToDoubleFilters;
private static final SerializeFilter nonStringValueToStringFilters;
private static final SerializeFilter emptyStringFilters;
private static final SerializeFilter[] emptyStringSerializeFilters;
private static final String FASTJSON_AUTOTYPE_ALIPAY_WHITELIST = "com.alipay.";
private static final String FASTJSON_AUTOTYPE_IPAY_WHITELIST = "com.ipay.";
public static final Pattern PATTER_BRACKETS_CONTAIN_DOT = Pattern
.compile("^.*((\\[)+.*(\\.)+.*(\\])+)+.*$");
public static final Pattern START_WITH_NUMBER = Pattern
.compile("^[0-9]+.*$");
protected final static Logger ERROR_LOGGER = LoggerFactory
.getLogger(LogbackConfig.GATEWAY_ERROR);
static {
JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.DisableCircularReferenceDetect.getMask();
JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.MapSortField.getMask();
ParserConfig.getGlobalInstance().addAccept(FASTJSON_AUTOTYPE_ALIPAY_WHITELIST);
ParserConfig.getGlobalInstance().addAccept(FASTJSON_AUTOTYPE_IPAY_WHITELIST);
noneObjectFilters = (PropertyFilter) (object, name,
value) -> null != value
&& (!(value instanceof JSONArray)
|| !((JSONArray) value).isEmpty())
&& (!(value instanceof JSONObject)
|| !((JSONObject) value).isEmpty());
bigDecimalToDoubleFilters = (ValueFilter) (object, name, value) -> {
if ((value instanceof BigDecimal)) {
return ((BigDecimal) value).doubleValue();
}
return value;
};
nonStringValueToStringFilters = (ValueFilter) (object, name, value) -> {
if ((null != value) && (value instanceof Number || value instanceof Boolean)) {
return value.toString();
}
return value;
};
emptyStringFilters = (ValueFilter) (object, name, value) -> {
if (null != value && value instanceof String) {
if (StringUtils.isNotBlank((String) value)) {
return value.toString();
} else if (StringUtils.isEmpty((String) value) && object instanceof JSONObject) {
((JSONObject) object).remove(name);
JSONObject jsonObject = (JSONObject) JSON.parse("{\"-self-closing\":\"true\"}");
((JSONObject) object).put(name, jsonObject);
return jsonObject;
}
}
return value;
};
emptyObjectAndBigDecimalAndNoneStringValueFilters = new SerializeFilter[3];
emptyObjectAndBigDecimalAndNoneStringValueFilters[0] = noneObjectFilters;
emptyObjectAndBigDecimalAndNoneStringValueFilters[1] = bigDecimalToDoubleFilters;
emptyObjectAndBigDecimalAndNoneStringValueFilters[2] = nonStringValueToStringFilters;
emptyStringSerializeFilters = new SerializeFilter[1];
emptyStringSerializeFilters[0] = emptyStringFilters;
emptyObjectAndNoneStringValueFilters = new SerializeFilter[1];
emptyObjectAndNoneStringValueFilters[0] = nonStringValueToStringFilters;
}
public static void init() {
}
public static Object getValueByPath(Object rootObject, String path) {
try {
List<String> split = Splitter.on(NEST_JSON_SPLIT).trimResults().omitEmptyStrings()
.splitToList(path.replaceAll("\\.", NEST_JSON_SPLIT));
Object eval = null;
int lastIndex = split.size() - 1;
for (int i = 0; i < split.size(); i++) {
String s = split.get(i);
eval = JSONPath.eval(rootObject, s);
if (eval == null) {
return null;
}
if (i < lastIndex) {
if (eval instanceof String) {
rootObject = JSONUtil.parseJSONObjectWithExceptionNull((String) eval);
if (null == rootObject) {
return null;
}
} else {
rootObject = JSON.toJSON(eval);
}
} else if (i == lastIndex && path.endsWith(NEST_JSON_SPLIT)
&& eval instanceof String) {
eval = JSON.parse((String) eval);
}
}
return eval;
} catch (Exception e) {
return null;
}
}
public static Object deepCloneGetValueByPath(Object rootObject, String path) {
return getValueByPath(rootObject, path);
}
public static JSONObject parseObjectOrder(String text) {
return JSON.parseObject(text, Feature.OrderedField);
}
public static Object deepCloneObject(Object object) {
if (null == object) {
return null;
}
return JSON.parse(JSON.toJSONString(object, SerializerFeature.WriteClassName),
Feature.OrderedField);
}
public static void setValueByPath(Object rootObject, String path, Object value) {
if (rootObject == null || StringUtils.isBlank(path)) {
return;
}
if (!StringUtils.contains(path, NEST_JSON_SPLIT)) {
try {
setValue(rootObject, path, value);
} catch (Exception e) {
ERROR_LOGGER.warn("rootObject={},path={},value={}", rootObject, path, value, e);
}
return;
}
String[] paths = path.split(NEST_JSON_SPLIT, 2);
String firstPath = paths[0];
Object eval = JSONPath.eval(rootObject, firstPath);
if (eval == null) {
eval = new JSONObject();
} else {
eval = JSON.parse(eval.toString());
}
String subPath = paths[1];
if (StringUtils.isBlank(subPath)) {
setValue(rootObject, firstPath, JSON.toJSONString(value));
} else {
setValueByPath(eval, subPath, value);
setValue(rootObject, firstPath, JSON.toJSONString(eval));
}
}
public static void setValue(Object rootObject, String path, Object value) {
if (value != null) {
JSONPath.set(rootObject, path, value);
}
}
public static void map(Object source, Object dest, String sourcePath, String destPath) {
map(source, dest, sourcePath, destPath, a -> a);
}
public static void map(Object source, Object dest, String sourcePath, String destPath,
Function<Object, Object> function) {
map(source, dest, sourcePath, null, destPath, function, false);
}
public static void map(Object source, Object dest, String sourcePath,
Map<String, String> sourcePathMap, String destPath,
Function<Object, Object> function) {
map(source, dest, sourcePath, sourcePathMap, destPath, function, true);
}
public static void map(Object source, Object dest, String sourcePath,
Map<String, String> sourcePathMap, String destPath,
Function<Object, Object> function, boolean multiInputMapping) {
try {
if (source == null || dest == null
|| (CollectionUtils.isEmpty(sourcePathMap) && multiInputMapping)
|| StringUtils.isBlank(destPath)
|| (StringUtils.isBlank(sourcePath) && !multiInputMapping)) {
return;
}
if (!sourcePath.contains(ARRAY_MARK)) {
Object sourceParameter = getMappingFunctionInputParameter(source, sourcePath,
sourcePathMap, multiInputMapping);
JSONUtil.setValueByPath(dest, destPath, function.apply(sourceParameter));
return;
}
String sourcePath1 = StringUtils.substringBefore(sourcePath, "[]");
String sourcePath2 = StringUtils.substringAfter(sourcePath, "[]");
String destPath1 = StringUtils.substringBefore(destPath, "[]");
String destPath2 = StringUtils.substringAfter(destPath, "[]");
JSONArray sourceArray = (JSONArray) JSONUtil.deepCloneGetValueByPath(source,
sourcePath1);
if (sourceArray == null) {
return;
}
JSONArray destArray = new JSONArray();
for (int i = 0; i < sourceArray.size(); i++) {
Object dest1 = JSONUtil.getValueByPath(dest, destPath1 + "[" + i + "]");
if (dest1 == null) {
dest1 = new JSONObject();
}
destArray.add(i, dest1);
map(sourceArray.get(i), dest1, sourcePath2, sourcePathMap, destPath2, function,
multiInputMapping);
}
JSONUtil.setValueByPath(dest, destPath1, destArray);
} catch (Exception e) {
throw e;
}
}
private static Object getMappingFunctionInputParameter(Object source, String sourcePath,
Map<String, String> sourcePathMap,
boolean multiInputMapping) {
Object sourceParameter;
if (multiInputMapping) {
sourceParameter = buildSourceValueMap(source, sourcePathMap);
} else {
sourceParameter = JSONUtil.deepCloneGetValueByPath(source, sourcePath);
}
return sourceParameter;
}
private static Map<String, Object> buildSourceValueMap(Object source,
Map<String, String> sourcePathMap) {
Map<String, Object> resultMap = new HashMap<>();
sourcePathMap.forEach(
(key, value) -> resultMap.put(key, JSONUtil.deepCloneGetValueByPath(source, value)));
return resultMap;
}
public static Object defaultIfNotJson(String jsonStr) {
try {
return JSON.parseObject(jsonStr);
} catch (Exception e) {
return jsonStr;
}
}
public static String defaultIfToJSONStringFail(Object obj) {
try {
return JSON.toJSONString(obj);
} catch (Throwable e) {
return EMPTY_STRING;
}
}
public static boolean isEquals(JSONObject json1, JSONObject json2) {
if (json1 == null || json2 == null) {
return ObjectUtil.equals(json1, json2);
} else if (json1.size() != json2.size()) {
return false;
}
boolean result = true;
for (String key : json1.keySet()) {
if (isJson(json1.getString(key))) {
result = isEquals(json1.getJSONObject(key), json2.getJSONObject(key));
} else {
result = StringUtils.equals(json1.getString(key), json2.getString(key));
}
if (!result) {
return false;
}
}
return result;
}
public static boolean isJson(String jsonStr) {
try {
if (StringUtils.isBlank(jsonStr)) {
return false;
}
JSON.parseObject(jsonStr);
return true;
} catch (Exception e) {
return false;
}
}
public static JSONObject parseJSONObjectWithExceptionNull(String jsonStr) {
try {
if (StringUtils.isBlank(jsonStr)) {
return null;
} else {
return JSON.parseObject(jsonStr);
}
} catch (Exception e) {
return null;
}
}
public static String getJsonPath(String key) {
if (StringUtils.contains(key, "-")) {
return "['" + key + "']";
}
return key;
}
private static boolean containJsonPathSpecialChar(String str) {
return (START_WITH_NUMBER.matcher(str).matches()
|| (StringUtils.contains(str, "-") && !StringUtils.contains(str, "\\-")))
&& !StringUtils.contains(str, "[");
}
public static String getFullJsonPath(String key) {
String result = Arrays.stream(StringUtils.split(key, ".")).map(str -> {
if (containJsonPathSpecialChar(str)) {
return "['" + str + "']";
} else {
return "." + str;
}
}).collect(Collectors.joining());
if (result.startsWith(".")) {
result = result.replaceFirst("\\.", "");
}
return result;
}
public static JSONObject filterEmptyJsonAndBigDecimalAndToStringValueField(JSONObject jsonObject,
SerializerFeature... features) {
return JSON.parseObject(JSON.toJSONString(jsonObject,
emptyObjectAndBigDecimalAndNoneStringValueFilters, features));
}
public static JSONObject filterEmptyJsonAndToStringValueField(JSONObject jsonObject,
SerializerFeature... features) {
return JSON.parseObject(
JSON.toJSONString(jsonObject, emptyObjectAndNoneStringValueFilters, features),
Feature.OrderedField);
}
public static JSONObject filterEmptyStringValueField(JSONObject jsonObject,
SerializerFeature... features) {
return JSON.parseObject(
JSON.toJSONString(jsonObject, emptyStringSerializeFilters, features),
Feature.OrderedField);
}
public static String objToJsonString(Object object) {
if (null == object || object instanceof String) {
return (String) object;
} else {
return JSON.toJSONString(object);
}
}
public static <T> T parseObject(String text, Class<T> clazz) {
return JSON.parseObject(text, clazz);
}
public static void parseJson2keySet(Set<String> allFullFields, String json, String parentKey) {
JsonElement jsonElement = new JsonParser().parse(json);
if (jsonElement.isJsonObject()) {
JsonObject jsonObject = jsonElement.getAsJsonObject();
parseJson2keySet(allFullFields, jsonObject, parentKey);
} else if (jsonElement.isJsonArray()) {
JsonArray jsonArray = jsonElement.getAsJsonArray();
for (JsonElement element : jsonArray) {
parseJson2keySet(allFullFields, element.getAsJsonObject(), parentKey);
}
}
}
public static void parseJson2keySet(Set<String> allFullFields, JsonObject jsonObject,
String parentKey) {
for (Map.Entry<String, JsonElement> object : jsonObject.entrySet()) {
String key = object.getKey();
JsonElement value = object.getValue();
String fullKey = (null == parentKey || parentKey.trim().equals("")) ? key
: parentKey.trim() + "." + key;
if (value.isJsonNull() || value.isJsonPrimitive()) {
allFullFields.add(fullKey);
} else if (value.isJsonObject()) {
parseJson2keySet(allFullFields, value.getAsJsonObject(), fullKey);
} else if (value.isJsonArray()) {
JsonArray jsonArray = value.getAsJsonArray();
for (JsonElement jsonElement1 : jsonArray) {
parseJson2keySet(allFullFields, jsonElement1.getAsJsonObject(), fullKey);
}
}
}
}
public static String getLastPathKey(String fullPath) {
String lastPath = fullPath;
if (StringUtils.isNotBlank(fullPath)) {
if (fullPath.endsWith("]")) {
String lastParam = StringUtils.substringAfterLast(fullPath, "['");
lastPath = StringUtils.substringBeforeLast(lastParam, "']");
} else if (fullPath.contains(".")) {
lastPath = StringUtils.substringAfterLast(fullPath, ".");
}
}
return lastPath;
}
public static String objToStringWithMapNullValue(JSONObject jsonObject) {
if (null == jsonObject) {
return null;
} else {
return JSON.toJSONString(jsonObject, SerializerFeature.WriteMapNullValue);
}
}
public static JSONObject merge(JSONObject jsonObject, JSONObject mergeJsonObject) {
try {
jsonObject.putAll(mergeJsonObject);
return jsonObject;
} catch (Exception e) {
return null;
}
}
public static String getStringBySimplePath(JSONObject jsonObject, String path) {
Object value;
try {
value = JSONPath.eval(jsonObject, "$." + path);
return value != null ? value.toString() : EMPTY_STRING;
} catch (Exception e) {
return EMPTY_STRING;
}
}
public static Map<String, Object> convertToMap(JSONObject jsonObject) {
Map<String, Object> map = new HashMap<>();
for (String key : jsonObject.keySet()) {
Object value = jsonObject.get(key);
if (value instanceof JSONObject) {
map.put(key, convertToMap((JSONObject) value));
} else {
map.put(key, value);
}
}
return map;
}
}
日期工具
@Slf4j
public class DateUtils {
public final static String shortFormat = "yyyyMMdd";
public final static String shortFormat2 = "yyMMdd";
public final static String longFormat = "yyyyMMddHHmmss";
public final static String webFormat = "yyyy-MM-dd";
public final static String webFormat2 = "yyyy/MM/dd";
public final static String webFormat3 = "yyyy/M/d";
public final static String webFormat4 = "yy/MM/dd";
public final static String timeFormat = "HHmmss";
public final static String monthFormat = "yyyyMM";
public final static String monthFormat2 = "M月";
public final static String chineseDtFormat = "yyyy年MM月dd日";
public final static String chineseDtFormat2 = "yyyy年M月d日";
public final static String chineseDtFormat3 = "M月d日";
public final static String newFormat = "yyyy-MM-dd HH:mm:ss";
public final static String noSecondFormat = "yyyy-MM-dd HH:mm";
public static final String DATE_FORMAT_MMDD = "MMdd";
public final static String TZ_UTC = "UTC";
public final static String TZ_GMT8 = "GMT+08:00";
public final static String TZ_UTC9 = "UTC+9";
public final static String TZ_GMT9 = "GMT+09:00";
public final static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
public final static long ONE_DAY_SECONDS = 86400;
public final static long ONE_DAY_MILL_SECONDS = 86400000;
private final static String TIMEZONE_INTERVAL = "|";
private final static int ISO_DATE_LENGTH = 25;
private final static int UTC_0_ISO_DATE_LENGTH = 20;
private final static String UTC_0_TIMEZONE = "Z";
public static String getUtcISODateTimeStr(Date date) {
return getISODateTimeStr(date, TimeZone.getTimeZone(TZ_UTC));
}
public static String getGMT8ISODateTimeStr(Date date) {
return getISODateTimeStr(date, TimeZone.getTimeZone(TZ_GMT8));
}
public static String getISODateTimeStrWithTZ(Date date, String tz) {
return getISODateTimeStr(date, TimeZone.getTimeZone(tz));
}
public static String getISODateTimeStr(Date date, String timeZone) {
return getISODateTimeStr(date, TimeZone.getTimeZone(timeZone));
}
public static String getISODateTimeStr(Date date, TimeZone timeZone) {
if (date == null) {
return null;
}
date.setTime(date.getTime() / 1000L * 1000L);
Calendar cal = new GregorianCalendar();
if (timeZone != null) {
cal.setTimeZone(timeZone);
}
cal.setTime(date);
return DatatypeConverter.printDateTime(cal);
}
public static Date parseISODateTimeStr(String isoDateStr) {
if (StringUtils.isBlank(isoDateStr)) {
return null;
}
int minDateStrLength;
if (isoDateStr.endsWith(UTC_0_TIMEZONE)) {
minDateStrLength = UTC_0_ISO_DATE_LENGTH;
} else {
minDateStrLength = ISO_DATE_LENGTH;
}
if (isoDateStr.length() < minDateStrLength) {
return null;
}
try {
Calendar cal = DatatypeConverter.parseDate(isoDateStr);
return cal.getTime();
} catch (IllegalArgumentException e) {
log.error("DateUtils.parseXSDate exception,isoDatetime:{0} {}", isoDateStr, e);
return null;
}
}
public static String dateFormat(Date date, String format) {
return org.apache.commons.lang3.time.DateFormatUtils.format(date, format);
}
public static Date parseDate(String dateStr, String format) {
try {
return org.apache.commons.lang3.time.DateUtils.parseDate(dateStr, format);
} catch (ParseException e) {
throw new IorpCommonException(IorpCommonResultCodeEnum.UNKNOWN_EXCEPTION,
"parse date error:" + e.getMessage());
}
}
public static String calculateNextDay(String currentDay) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(webFormat);
LocalDate date = LocalDate.parse(currentDay, formatter);
LocalDate newDate = date.plusDays(1);
return newDate.format(formatter);
}
public static Date parseDate(String day, int hour, int minute) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(webFormat);
LocalDate date = LocalDate.parse(day, formatter);
LocalDateTime localDateTime = date.atTime(hour, minute);
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
}
Money 工具类
public class MoneyUtil {
public static Money convertToMoney(String amount, String currency) {
CurrencyUnit currencyUnit = Monetary.getCurrency(currency);
return Money.of(new BigDecimal(amount), currencyUnit);
}
public static Money convertToMoney(BigDecimal amount, String currency) {
if(currency == null){
return null;
}
if (amount == null) {
return Money.of(new BigDecimal(0), currency );
}
CurrencyUnit currencyUnit = Monetary.getCurrency(currency);
return Money.of(amount, currencyUnit);
}
public static BigDecimal convertToAmount(Money money) {
if(money == null){
return null;
}
return money.getNumberStripped();
}
public static String convertToCurrency(Money money) {
if(money == null){
return null;
}
CurrencyUnit currency = money.getCurrency();
if (currency == null) {
return null;
}
return currency.getCurrencyCode();
}
public static Money convertToMoney(Long amount, String currency) {
CurrencyUnit currencyUnit = Monetary.getCurrency(currency);
return Money.of(amount, currencyUnit);
}
public static String getMoneyAmount(Money money) {
if (Objects.isNull(money)) {
return null;
}
return Optional.of(money.getNumber()).map(String::valueOf).orElse(null);
}
public static Long getMoneyLongAmount(Money money) {
if (Objects.isNull(money)) {
return null;
}
return money.getNumber().longValue();
}
public static String getMoneyCurrencyCode(Money money) {
if (Objects.isNull(money)) {
return null;
}
return Optional.ofNullable(money.getCurrency()).map(CurrencyUnit::getCurrencyCode)
.orElse(null);
}
public static boolean isGreaterThanZero(Money money) {
return money.getNumberStripped().compareTo(BigDecimal.ZERO) > 0;
}
public static Money buildZero(String currency) {
return convertToMoney("0", currency);
}
public static Long toMinorUnit(Money money) {
if(money == null){
return null;
}
CurrencyUnit currency = money.getCurrency();
int fractionDigits = currency.getDefaultFractionDigits();
if (fractionDigits < 0) {
fractionDigits = 0;
}
BigDecimal majorAmount = money.getNumberStripped();
BigDecimal minorAmount = majorAmount.movePointRight(fractionDigits);
minorAmount = minorAmount.setScale(0, RoundingMode.HALF_UP);
return minorAmount.longValueExact();
}
public static Money fromMinorUnit(Long minorUnit, String currency) {
if(currency == null){
return null;
}
if(minorUnit == null){
minorUnit = 0L;
}
CurrencyUnit currencyUnit = Monetary.getCurrency(currency);
int fractionDigits = currencyUnit.getDefaultFractionDigits();
if (fractionDigits < 0) {
fractionDigits = 0;
}
BigDecimal amount = BigDecimal.valueOf(minorUnit, fractionDigits);
return convertToMoney(amount, currency);
}
}
断言工具类
public class AssertUtil {
public static void isTrue(final boolean expValue, final CommonResultCodeEnum resultCode,
final Object... objs) {
if (!expValue) {
String logString = getLogString(objs);
String resultMsg = StringUtils.isBlank(logString) ? resultCode.getMessage() : logString;
throw new CommonException(resultCode, resultMsg);
}
}
public static void isTrue(final boolean expValue, final IorpCommonResultCodeEnum resultCode) {
if (!expValue) {
throw new CommonException(resultCode, resultCode.getMessage());
}
}
public static void isFalse(final boolean expValue, final CommonResultCodeEnum resultCode,
final Object... objs) {
isTrue(!expValue, resultCode, objs);
}
public static void isFalse(final boolean expValue, final CommonResultCodeEnum resultCode) {
isTrue(!expValue, resultCode);
}
public static void equals(final Object obj1, final Object obj2,
final CommonResultCodeEnum resultCode, final Object... objs) {
isTrue(obj1 == null ? obj2 == null : obj1.equals(obj2), resultCode, objs);
}
public static void notEquals(final Object obj1, final Object obj2,
final CommonResultCodeEnum resultCode, final Object... objs) {
isTrue(obj1 == null ? obj2 != null : !obj1.equals(obj2), resultCode, objs);
}
public static void is(final Object base, final Object target,
final CommonResultCodeEnum resultCode, final Object... objs) {
isTrue(base == target, resultCode, objs);
}
public static void isNot(final Object base, final Object target,
final CommonResultCodeEnum resultCode, final Object... objs) {
isTrue(base != target, resultCode, objs);
}
public static void contains(final Object base, final Collection<?> collection,
final CommonResultCodeEnum resultCode, final Object... objs) {
notEmpty(collection, resultCode, objs);
isTrue(collection.contains(base), resultCode, objs);
}
public static void notIn(final Object base, final Object[] collection,
final CommonResultCodeEnum resultCode, final Object... objs) {
if (null == collection) {
return;
}
for (Object obj2 : collection) {
isTrue(base != obj2, resultCode, objs);
}
}
public static void blank(final String str, final CommonResultCodeEnum resultCode,
final Object... objs) {
isTrue(StringUtils.isBlank(str), resultCode, objs);
}
public static void blank(final String str, final CommonResultCodeEnum resultCode) {
isTrue(StringUtils.isBlank(str), resultCode);
}
public static void notBlank(final String str, final IorpCommonResultCodeEnum resultCode,
final Object... objs) {
isTrue(StringUtils.isNotBlank(str), resultCode, objs);
}
public static void notBlank(final String str, final IorpCommonResultCodeEnum resultCode) {
isTrue(StringUtils.isNotBlank(str), resultCode);
}
public static void isNull(final Object object, final CommonResultCodeEnum resultCode,
final Object... objs) {
isTrue(object == null, resultCode, objs);
}
public static void notNull(final Object object, final CommonResultCodeEnum resultCode,
final Object... objs) {
isTrue(object != null, resultCode, objs);
}
public static void notEmpty(final Collection collection,
final CommonResultCodeEnum resultCode, final Object... objs) {
isTrue(!CollectionUtils.isEmpty(collection), resultCode, objs);
}
public static void notEmpty(final Collection collection,
final CommonResultCodeEnum resultCode) {
isTrue(!CollectionUtils.isEmpty(collection), resultCode);
}
public static void empty(final Collection collection, final CommonResultCodeEnum resultCode,
final Object... objs) {
isTrue(CollectionUtils.isEmpty(collection), resultCode, objs);
}
public static void empty(final Collection collection,
final CommonResultCodeEnum resultCode) {
isTrue(CollectionUtils.isEmpty(collection), resultCode);
}
public static void notEmpty(final Map map, final CommonResultCodeEnum resultCode,
final Object... objs) {
isTrue(!CollectionUtils.isEmpty(map), resultCode, objs);
}
public static void empty(final Map map, final CommonResultCodeEnum resultCode,
final Object... objs) {
isTrue(CollectionUtils.isEmpty(map), resultCode, objs);
}
public static void deductNotBlank(final boolean condition, final String str,
final CommonResultCodeEnum resultCode,
final Object... objs) {
if (!condition) {
return;
}
notBlank(str, resultCode, objs);
}
public static void deductTrue(final boolean condition, final boolean expValue,
final CommonResultCodeEnum resultCode, final Object... objs) {
if (!condition) {
return;
}
isTrue(expValue, resultCode, objs);
}
private static String getLogString(Object... objs) {
StringBuilder log = new StringBuilder();
for (Object o : objs) {
log.append(o);
}
return log.toString();
}
}