Optimize utils

This commit is contained in:
hongqiaowei
2021-09-29 14:13:46 +08:00
parent f5e44e6cf9
commit e5302112dd
40 changed files with 418 additions and 307 deletions

View File

@@ -18,6 +18,7 @@
package we.config;
import we.util.Constants;
import we.util.Consts;
import we.util.Utils;
/**
@@ -71,11 +72,11 @@ public abstract class RedisReactiveProperties {
}
public void appendTo(StringBuilder b) {
b.append(Constants.Symbol.LEFT_BRACE);
Utils.addTo(b, "host", Constants.Symbol.EQUAL, host, Constants.Symbol.SPACE_STR);
Utils.addTo(b, "port", Constants.Symbol.EQUAL, port, Constants.Symbol.SPACE_STR);
Utils.addTo(b, "password", Constants.Symbol.EQUAL, password, Constants.Symbol.SPACE_STR);
Utils.addTo(b, "database", Constants.Symbol.EQUAL, database, Constants.Symbol.EMPTY);
b.append(Constants.Symbol.RIGHT_BRACE);
b.append(Consts.S.LEFT_BRACE);
Utils.addTo(b, "host", Consts.S.EQUAL, host, Consts.S.SPACE_STR);
Utils.addTo(b, "port", Consts.S.EQUAL, port, Consts.S.SPACE_STR);
Utils.addTo(b, "password", Consts.S.EQUAL, password, Consts.S.SPACE_STR);
Utils.addTo(b, "database", Consts.S.EQUAL, database, Consts.S.EMPTY);
b.append(Consts.S.RIGHT_BRACE);
}
}

View File

@@ -28,7 +28,7 @@ import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.ServerWebExchangeDecorator;
import reactor.core.publisher.Mono;
import we.spring.http.server.reactive.ext.FizzServerHttpRequestDecorator;
import we.util.Constants;
import we.util.Consts;
import we.util.NettyDataBufferUtils;
import we.util.ThreadContext;
@@ -126,13 +126,13 @@ public class FizzServerWebExchangeDecorator extends ServerWebExchangeDecorator {
String field = fieldValuesEntry.getKey();
List<String> values = fieldValuesEntry.getValue();
if (CollectionUtils.isEmpty(values)) {
b.append(URLEncoder.encode(field, Constants.Charset.UTF8));
b.append(URLEncoder.encode(field, Consts.C.UTF8));
} else {
int vs = values.size();
for (int i = 0; i < vs; ) {
b.append(URLEncoder.encode(field, Constants.Charset.UTF8))
b.append(URLEncoder.encode(field, Consts.C.UTF8))
.append('=')
.append(URLEncoder.encode(values.get(i), Constants.Charset.UTF8));
.append(URLEncoder.encode(values.get(i), Consts.C.UTF8));
if ((++i) != vs) {
b.append('&');
}

View File

@@ -21,8 +21,10 @@ import org.apache.commons.lang3.SystemUtils;
/**
* @author hongqiaowei
* @deprecated and use {@link we.util.Consts} instead
*/
@Deprecated
public final class Constants {
public static final class Symbol {

View File

@@ -0,0 +1,108 @@
/*
* Copyright (C) 2020 the original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package we.util;
/**
* @author hongqiaowei
*/
public final class Consts {
private Consts() {
}
public static final class S {
public static final String EMPTY = "";
public static final String SPACE_STR = " ";
public static final char SPACE = ' ';
public static final String TWO_SPACE_STR = " ";
public static final char COMMA = ',';
public static final char COLON = ':';
public static final char FORWARD_SLASH = '/';
public static final String FORWARD_SLASH_STR = "/";
public static final char BACK_SLASH = '\\';
public static final char DOT = '.';
public static final char SEMICOLON = ';';
public static final char QUESTION = '?';
public static final char DOUBLE_QUOTE = '"';
public static final char SINGLE_QUOTE = '\'';
public static final char ASTERISK = '*';
public static final char DASH = '-';
public static final char UNDERLINE = '_';
public static final char EQUAL = '=';
public static final char AT = '@';
public static final char LEFT_SQUARE_BRACKET = '[';
public static final char RIGHT_SQUARE_BRACKET = ']';
public static final char LEFT_BRACE = '{';
public static final char RIGHT_BRACE = '}';
public static final char SQUARE = '^';
public static final char HASH = '#';
public static final char LF = '\n';
public static final char TAB = '\t';
public static final char NUL = '\u0000';
/*
private static final char c0 = SystemUtils.IS_OS_WINDOWS ? S.BACK_SLASH : S.FORWARD_SLASH;
public static final char PATH_SEPARATOR = c0;
*/
public static final String LINE_SEPARATOR = System.lineSeparator();
public static final String COMMA_SPACE = ", ";
public static final String HTTP_PROTOCOL_PREFIX = "http://";
}
public static final class C {
public static final String UTF8 = "UTF-8";
public static final String GBK = "GBK";
public static final String ISO88591 = "ISO8859-1";
}
public static final class DP {
public static final String DP10 = "yyyy-MM-dd";
public static final String DP14 = "yyyyMMddHHmmss";
public static final String DP19 = "yyyy-MM-dd HH:mm:ss";
public static final String DP23 = "yyyy-MM-dd HH:mm:ss.SSS";
public static final byte MILLS_LEN = 13;
}
public static final class P {
public static final String LOCAL = "local";
public static final String DEV = "dev";
public static final String TEST = "test";
public static final String FAT = "fat";
public static final String PREPROD = "preprod";
public static final String UAT = "uat";
public static final String PRO = "pro";
public static final String PROD = "prod";
}
public static final String HTTP_SERVER = "http_server";
public static final String HTTP_CLIENT = "http_client";
public static final String MYSQL = "mysql";
public static final String REDIS = "redis";
public static final String CODIS = "codis";
public static final String MONGO = "mongo";
public static final String KAFKA = "kafka";
public static final String ELASTICSEARCH = "elasticsearch";
public static final String SCHED = "sched";
public static final String R2DBC = "r2dbc";
public static final String TRACE_ID = "id^";
}

View File

@@ -19,12 +19,14 @@ package we.util;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import we.util.Constants.DatetimePattern;
import we.util.Consts.DP;
/**
* @author hongqiaowei
@@ -35,8 +37,11 @@ public abstract class DateTimeUtils {
private static Map<String, DateTimeFormatter> dateTimeFormatters = new HashMap<>();
private static ZoneId defaultZone = ZoneId.systemDefault();
private static final String zeroTimeSuffix = " 00:00:00";
private static final String zeroTimeSuffix = " 00:00:00.000";
private DateTimeUtils() {
}
public static DateTimeFormatter getDateTimeFormatter(String pattern) {
DateTimeFormatter f = dateTimeFormatters.get(pattern);
@@ -47,22 +52,6 @@ public abstract class DateTimeUtils {
return f;
}
public static Date from(Instant i) {
return new Date(i.toEpochMilli());
}
public static Date from(LocalDateTime ldt) {
return from(ldt.atZone(defaultZone).toInstant());
}
public static LocalDateTime from(Date d) {
return LocalDateTime.ofInstant(d.toInstant(), defaultZone);
}
public static LocalDateTime from(long l) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(l), defaultZone);
}
public static long toMillis(LocalDateTime ldt) {
return ldt.atZone(defaultZone).toInstant().toEpochMilli();
}
@@ -71,17 +60,41 @@ public abstract class DateTimeUtils {
if (dateTime.length() == 10) {
dateTime += zeroTimeSuffix;
}
String p = DatetimePattern.DP19;
String p = DP.DP23;
if (pattern.length != 0) {
p = pattern[0];
}
DateTimeFormatter f = getDateTimeFormatter(p);
LocalDateTime ldt = LocalDateTime.parse(dateTime, f);
return ldt.atZone(defaultZone).toInstant().toEpochMilli();
return toMillis(ldt);
}
public static String toDate(long mills, String... pattern) {
String p = DatetimePattern.DP10;
public static LocalDate transform(Date date) {
return date.toInstant().atZone(defaultZone).toLocalDate();
}
public static LocalDateTime transform(long l) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(l), defaultZone);
}
public static LocalDateTime localDateTimeFrom(Date date) {
return date.toInstant().atZone(defaultZone).toLocalDateTime();
}
public static Date from(Instant i) {
return new Date(i.toEpochMilli());
}
public static Date from(LocalDate localDate) {
return Date.from(localDate.atStartOfDay().atZone(defaultZone).toInstant());
}
public static Date from(LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(defaultZone).toInstant());
}
public static String convert(long mills, String... pattern) {
String p = DP.DP10;
if (pattern.length != 0) {
p = pattern[0];
}
@@ -89,30 +102,9 @@ public abstract class DateTimeUtils {
DateTimeFormatter f = getDateTimeFormatter(p);
return ldt.format(f);
}
public static long until(LocalDate thatDate) {
return LocalDate.now().until(thatDate, ChronoUnit.DAYS);
}
public static long from(LocalDate thatDate) {
return thatDate.until(LocalDate.now(), ChronoUnit.DAYS);
}
public static long until(LocalDate startDate, LocalDate endDate) {
return startDate.until(endDate, ChronoUnit.DAYS);
}
public static LocalDate date2localDate(Date date) {
return date.toInstant().atZone(defaultZone).toLocalDate();
}
public static Date localDate2date(LocalDate localDate) {
ZonedDateTime zonedDateTime = localDate.atStartOfDay(defaultZone);
return Date.from(zonedDateTime.toInstant());
}
public static String localDate2str(LocalDate date, String... pattern) {
String p = DatetimePattern.DP10;
public static String convert(LocalDate date, String... pattern) {
String p = DP.DP10;
if (pattern.length != 0) {
p = pattern[0];
}
@@ -120,25 +112,25 @@ public abstract class DateTimeUtils {
return date.format(f);
}
public static String localDateTime2str(LocalDateTime localDateTime, String... pattern) {
String p = DatetimePattern.DP23;
public static String convert(LocalDateTime localDateTime, String... pattern) {
String p = DP.DP23;
if (pattern.length != 0) {
p = pattern[0];
}
DateTimeFormatter f = getDateTimeFormatter(p);
return localDateTime.format(f);
}
public static List<String> datesBetween(String start, String end) {
LocalDate sd = LocalDate.parse(start);
LocalDate ed = LocalDate.parse(end);
long dist = ChronoUnit.DAYS.between(sd, ed);
if (dist == 0) {
return Collections.EMPTY_LIST;
return Collections.emptyList();
} else if (dist < 0) {
LocalDate x = ed;
LocalDate d = ed;
ed = sd;
sd = x;
sd = d;
dist = Math.abs(dist);
}
long max = dist + 1;
@@ -146,35 +138,13 @@ public abstract class DateTimeUtils {
return d.plusDays(1);
}).limit(max).map(LocalDate::toString).collect(Collectors.toList());
}
public static class LocalDateAndStr {
public LocalDate d;
public String s;
public LocalDateAndStr(LocalDate d, String s) {
this.d = d;
this.s = s;
}
}
public static List<LocalDateAndStr> datesBetween0(String start, String end) {
LocalDate sd = LocalDate.parse(start);
LocalDate ed = LocalDate.parse(end);
long dist = ChronoUnit.DAYS.between(sd, ed);
if (dist == 0) {
return Collections.EMPTY_LIST;
} else if (dist < 0) {
LocalDate x = ed;
ed = sd;
sd = x;
dist = Math.abs(dist);
}
long max = dist + 1;
return Stream.iterate(sd, d -> {
return d.plusDays(1);
}).limit(max).map((LocalDate e) -> {
return new LocalDateAndStr(e, e.toString());
}).collect(Collectors.toList());
public static List<LocalDate> datesBetween(LocalDate sd, LocalDate ed) {
long numOfDaysBetween = ChronoUnit.DAYS.between(sd, ed);
return IntStream.iterate(0, i -> i + 1)
.limit(numOfDaysBetween)
.mapToObj(i -> sd.plusDays(i))
.collect(Collectors.toList());
}
public static LocalDate beforeNow(long offsetDays) {
@@ -184,4 +154,22 @@ public abstract class DateTimeUtils {
public static LocalDateTime beforeNowNoTime(long offsetDays) {
return LocalDate.now().minusDays(offsetDays).atTime(0, 0, 0, 0);
}
public static LocalDateTime time2zero(LocalDateTime ldt) {
return ldt.withHour(0).withMinute(0).withSecond(0).with(ChronoField.MILLI_OF_SECOND, 0);
}
public static boolean isSameDay(Date date1, Date date2) {
LocalDate localDate1 = date1.toInstant().atZone(defaultZone).toLocalDate();
LocalDate localDate2 = date2.toInstant().atZone(defaultZone).toLocalDate();
return localDate1.isEqual(localDate2);
}
/*
void iterateBetweenDatesJava8(LocalDate start, LocalDate end) {
for (LocalDate date = start; date.isBefore(end); date = date.plusDays(1)) {
processDate(date);
}
}
*/
}

View File

@@ -27,7 +27,7 @@ import java.security.MessageDigest;
public abstract class DigestUtils extends org.apache.commons.codec.digest.DigestUtils {
static final String md5digest = "$md5digest";
static final String md5digest = "$m5dgt";
private DigestUtils() {
}

View File

@@ -25,7 +25,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import we.util.Constants.DatetimePattern;
import we.util.Consts.DP;
import java.io.IOException;
import java.time.LocalDate;
@@ -74,6 +74,9 @@ public abstract class JacksonUtils {
m.registerModule(m3);
}
private JacksonUtils() {
}
public static ObjectMapper getObjectMapper() {
return m;
}
@@ -101,18 +104,18 @@ class DateDeseralizer extends JsonDeserializer<Date> {
String s = jp.getText();
int sl = s.length();
if (sl == DatetimePattern.MILLS_LEN) {
if (sl == DP.MILLS_LEN) {
return new Date(Long.parseLong(s));
} else {
String dtp = DatetimePattern.DP10;
String dtp = DP.DP10;
DateTimeFormatter dtf = null;
if (sl == DatetimePattern.DP10.length()) {
} else if (sl == DatetimePattern.DP14.length()) {
dtp = DatetimePattern.DP14;
} else if (sl == DatetimePattern.DP19.length()) {
dtp = DatetimePattern.DP19;
} else if (sl == DatetimePattern.DP23.length()) {
dtp = DatetimePattern.DP23;
if (sl == DP.DP10.length()) {
} else if (sl == DP.DP14.length()) {
dtp = DP.DP14;
} else if (sl == DP.DP19.length()) {
dtp = DP.DP19;
} else if (sl == DP.DP23.length()) {
dtp = DP.DP23;
} else {
throw new IOException("invalid datetime pattern: " + s);
}
@@ -128,8 +131,8 @@ class LocalDateDeseralizer extends JsonDeserializer<LocalDate> {
public LocalDate deserialize(JsonParser jp, DeserializationContext ctx) throws IOException {
String s = jp.getText();
if (s.length() == DatetimePattern.DP10.length()) {
DateTimeFormatter dtf = DateTimeUtils.getDateTimeFormatter(DatetimePattern.DP10);
if (s.length() == DP.DP10.length()) {
DateTimeFormatter dtf = DateTimeUtils.getDateTimeFormatter(DP.DP10);
return LocalDate.parse(s, dtf);
} else {
throw new IOException("invalid datetime pattern: " + s);
@@ -143,18 +146,18 @@ class LocalDateTimeDeseralizer extends JsonDeserializer<LocalDateTime> {
String s = jp.getText();
int sl = s.length();
if (sl == DatetimePattern.MILLS_LEN) {
return DateTimeUtils.from(Long.parseLong(s));
if (sl == DP.MILLS_LEN) {
return DateTimeUtils.transform(Long.parseLong(s));
} else {
String dtp = DatetimePattern.DP10;
String dtp = DP.DP10;
DateTimeFormatter dtf = null;
if (sl == DatetimePattern.DP10.length()) {
} else if (sl == DatetimePattern.DP14.length()) {
dtp = DatetimePattern.DP14;
} else if (sl == DatetimePattern.DP19.length()) {
dtp = DatetimePattern.DP19;
} else if (sl == DatetimePattern.DP23.length()) {
dtp = DatetimePattern.DP23;
if (sl == DP.DP10.length()) {
} else if (sl == DP.DP14.length()) {
dtp = DP.DP14;
} else if (sl == DP.DP19.length()) {
dtp = DP.DP19;
} else if (sl == DP.DP23.length()) {
dtp = DP.DP23;
} else {
throw new IOException("invalid datetime pattern: " + s);
}

View File

@@ -43,6 +43,9 @@ public abstract class NettyDataBufferUtils extends org.springframework.core.io.b
public static final DataBuffer EMPTY_DATA_BUFFER = from(new byte[0]);
private NettyDataBufferUtils() {
}
public static NettyDataBuffer from(String s) {
return from(s.getBytes(StandardCharsets.UTF_8));
}

View File

@@ -49,6 +49,9 @@ public class NetworkUtils {
private static final String SERVER_IP = "SERVER_IP";
private NetworkUtils() {
}
/**
* @return user settings, or the first one in ip address list.
*/
@@ -115,7 +118,7 @@ public class NetworkUtils {
log.error(null, e);
}
serverId = serverId & maxServerId;
log.info("server id is " + serverId);
log.info("server id: {}", serverId);
}
return serverId;
}

View File

@@ -35,6 +35,9 @@ import we.config.RedisReactiveConfig;
public abstract class ReactiveRedisHelper {
private ReactiveRedisHelper() {
}
public static ReactiveRedisConnectionFactory getConnectionFactory(String host, int port, String password, int database) {
RedisStandaloneConfiguration rcs = new RedisStandaloneConfiguration(host, port);
if (password != null) {

View File

@@ -24,19 +24,22 @@ import reactor.core.publisher.Mono;
* @author hongqiaowei
*/
public interface ReactorUtils {
public abstract class ReactorUtils {
static final Object OBJ = new Object();
public static final Object OBJ = new Object();
static final Object NULL = OBJ;
public static final Object NULL = OBJ;
static final Throwable EMPTY_THROWABLE = Utils.throwableWithoutStack(null); // XXX
public static final Throwable EMPTY_THROWABLE = Utils.throwableWithoutStack(null);
static Mono getInitiateMono() {
private ReactorUtils() {
}
public static Mono getInitiateMono() {
return Mono.just(OBJ);
}
static Flux getInitiateFlux() {
public static Flux getInitiateFlux() {
return Flux.just(OBJ);
}
}

View File

@@ -25,6 +25,9 @@ import java.lang.reflect.Field;
public abstract class ReflectionUtils extends org.springframework.util.ReflectionUtils {
private ReflectionUtils() {
}
public static void set(Object target, String field, Object value) {
Field f = findField(target.getClass(), field);
makeAccessible(f);

View File

@@ -57,6 +57,9 @@ public abstract class ScriptUtils {
engineManger = new ScriptEngineManager();
}
private ScriptUtils() {
}
private static ScriptEngine createJavascriptEngine() throws ScriptException {
ScriptEngine eng = engineManger.getEngineByName(JAVA_SCRIPT);
try {
@@ -70,10 +73,8 @@ public abstract class ScriptUtils {
ClassPathResource res = new ClassPathResource(COMMON_JS_PATH);
eng.eval(new InputStreamReader(res.getInputStream()));
return eng;
} catch (FileNotFoundException e) {
throw new ScriptException(e);
} catch (IOException e) {
throw new ScriptException(e);
throw new ScriptException(e);
}
}

View File

@@ -28,11 +28,16 @@ import java.util.Map;
public abstract class ThreadContext {
private static ThreadLocal<Map<String, Object>> tl = new ThreadLocal<>();
private static final int mapCap = 32;
private static ThreadLocal<Map<String, Object>> tl = new ThreadLocal<>();
private static final String sb = "$sb";
private static final int sbCap = 256;
private static final int mapCap = 32;
private static final String sb = "$sb";
private static final int sbCap = 256;
private ThreadContext() {
}
/** use me carefully! */
public static StringBuilder getStringBuilder() {

View File

@@ -29,45 +29,48 @@ import java.time.LocalTime;
public abstract class Utils {
public static void addTo(StringBuilder b, String k, char c, boolean v, String separator) {
private Utils() {
}
public static void addTo(StringBuilder b, String k, char c, boolean v, String separator) {
b.append(k).append(c).append(v).append(separator);
}
public static void addTo(StringBuilder b, String k, char c, char v, String separator) {
public static void addTo(StringBuilder b, String k, char c, char v, String separator) {
b.append(k).append(c).append(v).append(separator);
}
public static void addTo(StringBuilder b, String k, char c, int v, String separator) {
public static void addTo(StringBuilder b, String k, char c, int v, String separator) {
b.append(k).append(c).append(v).append(separator);
}
public static void addTo(StringBuilder b, String k, char c, long v, String separator) {
public static void addTo(StringBuilder b, String k, char c, long v, String separator) {
b.append(k).append(c).append(v).append(separator);
}
public static void addTo(StringBuilder b, String k, char c, float v, String separator) {
public static void addTo(StringBuilder b, String k, char c, float v, String separator) {
b.append(k).append(c).append(v).append(separator);
}
public static void addTo(StringBuilder b, String k, char c, double v, String separator) {
public static void addTo(StringBuilder b, String k, char c, double v, String separator) {
b.append(k).append(c).append(v).append(separator);
}
public static void addTo(StringBuilder b, String k, char c, String v, String separator) {
public static void addTo(StringBuilder b, String k, char c, String v, String separator) {
b.append(k).append(c).append(v).append(separator);
}
public static void addTo(StringBuilder b, String k, char c, LocalTime v, String separator) {
public static void addTo(StringBuilder b, String k, char c, LocalTime v, String separator) {
b.append(k).append(c).append(v).append(separator);
}
public static void addTo(StringBuilder b, String k, char c, LocalDate v, String separator) {
public static void addTo(StringBuilder b, String k, char c, LocalDate v, String separator) {
b.append(k).append(c).append(v).append(separator);
}
public static void addTo(StringBuilder b, String k, char c, LocalDateTime v, String separator) { b.append(k).append(c).append(v).append(separator); }
public static void addTo(StringBuilder b, String k, char c, Object v, String separator) {
public static void addTo(StringBuilder b, String k, char c, Object v, String separator) {
b.append(k).append(c).append(v).append(separator);
}
@@ -86,7 +89,7 @@ public abstract class Utils {
}
}
if (begin == 0) {
return Constants.Symbol.EMPTY;
return Consts.S.EMPTY;
} else if (end == 0) {
end = l;
}
@@ -110,7 +113,7 @@ public abstract class Utils {
StackTraceElement[] stackTraces = Thread.currentThread().getStackTrace();
if (stackTraces != null) {
for (int i = 0; i < stackTraces.length; i++) {
b.append(stackTraces[i]).append(Constants.Symbol.LF);
b.append(stackTraces[i]).append(Consts.S.LF);
}
}
}