共聚类

This commit is contained in:
jiang 2024-08-23 15:29:06 +08:00
parent 30a0e861a3
commit 742abda568
13 changed files with 1020 additions and 40 deletions

View File

@ -1,12 +1,19 @@
package com.bonus.common.core.utils;
import org.apache.commons.lang3.ObjectUtils;
import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.WeekFields;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
/**
@ -54,6 +61,33 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
}
/**
* 获取当前年份
*
* @return 当前年份的字符串
*/
public static String getCurrentYear() {
return String.valueOf(LocalDate.now().getYear());
}
/**
* 获取当前月份
*
* @return 当前月份的字符串
*/
public static String getCurrentMonth() {
return String.format("%02d", LocalDate.now().getMonthValue());
}
/**
* 获取当前日期中的日
*
* @return 当前日的字符串
*/
public static String getCurrentDay() {
return String.format("%02d", LocalDate.now().getDayOfMonth());
}
/**
* 获取当前日期时间格式为 yyyyMMddHHmmss
*
@ -105,14 +139,18 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
*
* @param endDate 结束日期
* @param startDate 开始日期
* @param separator 自定义拼接符
* @return 时间差字符串
*/
public static String timeDistance(Date endDate, Date startDate) {
public static String timeDistance(Date endDate, Date startDate, String separator) {
long duration = endDate.getTime() - startDate.getTime();
long days = TimeUnit.MILLISECONDS.toDays(duration);
long hours = TimeUnit.MILLISECONDS.toHours(duration) % 24;
long minutes = TimeUnit.MILLISECONDS.toMinutes(duration) % 60;
return days + "" + hours + "小时" + minutes + "分钟";
if (ObjectUtils.isEmpty(separator)) {
return days + "" + hours + "小时" + minutes + "分钟";
}
return days + separator + hours + separator + minutes;
}
/**
@ -428,4 +466,200 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
return toDate(localDateTime);
}
/**
* 根据输入的日 返回月/
*
* @param day
* @param separator 分隔符
* @return /
*/
public static String getMonthOrDay(int day, String separator) {
LocalDate today = LocalDate.now();
if (day < 1 || day > today.lengthOfMonth()) {
return null;
} else {
if (ObjectUtils.isEmpty(separator)) {
return String.format("%02d", LocalDate.now().getMonthValue()) + "" + day;
} else {
return String.format("%02d", LocalDate.now().getMonthValue()) + separator + day;
}
}
}
/**
* 将日期字符串转换为 ISO 8601 格式
*
* @param dateStr 输入的日期字符串
* @param format 输入日期的格式
* @return ISO 8601 格式的日期字符串
*/
public static String convertToISO8601(String dateStr, String format) {
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(format);
DateTimeFormatter isoFormatter = DateTimeFormatter.ISO_DATE_TIME;
LocalDateTime dateTime = LocalDateTime.parse(dateStr, inputFormatter);
return dateTime.format(isoFormatter);
}
/**
* 获取两个时间之间的相差秒数
*
* @param startTimeStr 开始时间的字符串
* @param endTimeStr 结束时间的字符串
* @param format 时间格式
* @return 相差的秒数
*/
public static long getSecondsBetween(String startTimeStr, String endTimeStr, String format) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
LocalDateTime startTime = LocalDateTime.parse(startTimeStr, formatter);
LocalDateTime endTime = LocalDateTime.parse(endTimeStr, formatter);
Duration duration = Duration.between(startTime, endTime);
return duration.getSeconds();
}
/**
* 根据输入日期字符串返回本周的周一和周日的日期
*
* @param dateStr 日期字符串
* @param format 日期格式
* @return 包含本周一和周日日期的数组
*/
public static String[] getWeekStartAndEndDate(String dateStr, String format) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
LocalDate date = LocalDate.parse(dateStr, formatter);
// 获取本周一
LocalDate monday = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
// 获取本周日
LocalDate sunday = date.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
return new String[] {
monday.format(formatter),
sunday.format(formatter)
};
}
/**
* 根据输入日期字符串返回本周的开始时间和结束时间
*
* @param dateStr 日期字符串
* @param format 日期格式
* @return 包含本周开始时间和结束时间的数组
*/
public static String[] getWeekStartAndEndDateTime(String dateStr, String format) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
LocalDate date = LocalDate.parse(dateStr, formatter);
// 获取本周一的开始时间
LocalDateTime startOfWeek = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY))
.atStartOfDay();
// 获取本周日的结束时间
LocalDateTime endOfWeek = date.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY))
.atTime(23, 59, 59);
return new String[] {
startOfWeek.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
endOfWeek.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
};
}
/**
* 根据输入日期字符串返回该日期属于本月的第几周
*
* @param dateStr 日期字符串
* @param format 日期格式
* @return 该日期属于本月的第几周
*/
public static int getWeekOfMonth(String dateStr, String format) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
LocalDate date = LocalDate.parse(dateStr, formatter);
// 获取周字段周一为一周的开始
WeekFields weekFields = WeekFields.of(Locale.getDefault());
return date.get(weekFields.weekOfMonth());
}
/**
* 获取从当前日期往前推 n 天的所有日期并以字符串形式返回
*
* @param n 天数
* @param format 日期格式
* @return 从当前日期往前推 n 天的所有日期的字符串列表
*/
public static List<String> getDatesBefore(int n, String format) {
List<String> dates = new ArrayList<>();
LocalDate today = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
for (int i = 0; i < n; i++) {
LocalDate date = today.minusDays(i);
dates.add(date.format(formatter));
}
return dates;
}
/**
* 获取从当前日期往后推 n 天的所有日期并以字符串形式返回
*
* @param n 天数
* @param format 日期格式
* @return 从当前日期往后推 n 天的所有日期的字符串列表
*/
public static List<String> getDatesAfter(int n, String format) {
List<String> dates = new ArrayList<>();
LocalDate today = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
for (int i = 0; i < n; i++) {
LocalDate date = today.plusDays(i);
dates.add(date.format(formatter));
}
return dates;
}
/**
* 根据输入日期字符串获取从指定日期往后推 n 天的所有日期并以字符串形式返回
*
* @param startDateStr 起始日期字符串
* @param n 天数
* @param format 输入日期的格式
* @return 从指定日期往后推 n 天的所有日期的字符串列表
*/
public static List<String> getDatesAfter(String startDateStr, int n, String format) {
List<String> dates = new ArrayList<>();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
LocalDate startDate = LocalDate.parse(startDateStr, formatter);
for (int i = 0; i < n; i++) {
LocalDate date = startDate.plusDays(i);
dates.add(date.format(formatter));
}
return dates;
}
/**
* 根据输入日期字符串获取从指定日期往前推 n 天的所有日期并以字符串形式返回
*
* @param startDateStr 起始日期字符串
* @param n 天数
* @param format 日期格式
* @return 从指定日期往前推 n 天的所有日期的字符串列表
*/
public static List<String> getDatesBefore(String startDateStr, int n, String format) {
List<String> dates = new ArrayList<>();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
LocalDate startDate = LocalDate.parse(startDateStr, formatter);
for (int i = 0; i < n; i++) {
LocalDate date = startDate.minusDays(i);
dates.add(date.format(formatter));
}
return dates;
}
}

View File

@ -21,7 +21,7 @@ import java.util.Properties;
* 文件操作工具类提供对常见文件格式的读写操作
* 支持的文件格式包括PropertiesYMLXMLJSONCIMESVG
*/
public class FileUtils1 {
public class FileUtils {
/**
* 读取文件内容为字符串
@ -90,8 +90,8 @@ public class FileUtils1 {
/**
* 将数据写入 `.yml` 文件
*
* @param file 目标 `.yml` 文件
* @param data 要写入的数据作为 `Map<String, Object>` 对象
* @param file 目标 `.yml` 文件
* @param data 要写入的数据作为 `Map<String, Object>` 对象
* @throws IOException 如果写入文件时发生错误
*/
public static void writeYml(File file, Map<String, Object> data) throws IOException {
@ -137,9 +137,9 @@ public class FileUtils1 {
/**
* `.json` 文件中读取 JSON 数据并将其转换为指定的 Java 对象
*
* @param file 需要读取的 `.json` 文件
* @param file 需要读取的 `.json` 文件
* @param valueType 目标 Java 对象的类
* @param <T> 目标 Java 对象的类型
* @param <T> 目标 Java 对象的类型
* @return 读取到的 Java 对象
* @throws IOException 如果读取文件时发生错误
*/
@ -208,4 +208,89 @@ public class FileUtils1 {
public static void writeSvg(File file, String content) throws IOException {
writeStringToFile(file, content);
}
/**
* 读取 `.txt` 文件的内容并将其转换为字符串
*
* @param file 需要读取的 `.txt` 文件
* @return 文件内容的字符串表示
* @throws IOException 如果读取文件时发生错误
*/
public static String readTxt(File file) throws IOException {
return readFileToString(file);
}
/**
* 将字符串内容写入 `.txt` 文件
*
* @param file 目标 `.txt` 文件
* @param content 要写入文件的内容
* @throws IOException 如果写入文件时发生错误
*/
public static void writeTxt(File file, String content) throws IOException {
writeStringToFile(file, content);
}
/**
* `.properties` 文件中根据 key 读取属性值
*
* @param file 需要读取的 `.properties` 文件
* @param key 要获取的属性键
* @return 属性值
* @throws IOException 如果读取文件时发生错误
*/
public static String readPropertyByKey(File file, String key) throws IOException {
Properties properties = readProperties(file);
return properties.getProperty(key);
}
/**
* `.yml` 文件中根据 key 读取属性值
*
* @param file 需要读取的 `.yml` 文件
* @param key 要获取的属性键
* @return 属性值
* @throws IOException 如果读取文件时发生错误
*/
public static Object readYmlByKey(File file, String key) throws IOException {
Map<String, Object> data = readYml(file);
return getValueByKey(data, key);
}
/**
* `.json` 文件中根据 key 读取属性值
*
* @param file 需要读取的 `.json` 文件
* @param key 要获取的属性键
* @return 属性值
* @throws IOException 如果读取文件时发生错误
*/
public static Object readJsonByKey(File file, String key) throws IOException {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> data = mapper.readValue(file, Map.class);
return getValueByKey(data, key);
}
/**
* 从嵌套 Map 中获取指定 key 的值
*
* @param map Map 数据
* @param key 要获取的属性键
* @return 属性值
*/
private static Object getValueByKey(Map<String, Object> map, String key) {
String[] keys = key.split("\\.");
Map<String, Object> currentMap = map;
for (int i = 0; i < keys.length - 1; i++) {
Object value = currentMap.get(keys[i]);
if (value instanceof Map) {
currentMap = (Map<String, Object>) value;
} else {
return null;
}
}
return currentMap.get(keys[keys.length - 1]);
}
}

View File

@ -1,8 +1,7 @@
package com.bonus.common.core.utils;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.UUID;
/**
* 字符串工具类提供常见的字符串处理方法
@ -230,22 +229,6 @@ public class StringHelper {
return str.substring(0, 1).toLowerCase() + str.substring(1);
}
/**
* 检查字符串是否为有效的电子邮件地址
*
* @param email 电子邮件地址
* @return 是否为有效的电子邮件地址
*/
public static boolean isValidEmail(String email) {
if (isEmpty(email)) {
return false;
}
String emailRegex = "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$";
Pattern pattern = Pattern.compile(emailRegex);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
/**
* 将字符串进行 Base64 编码
*
@ -273,21 +256,6 @@ public class StringHelper {
return new String(decodedBytes, StandardCharsets.UTF_8);
}
/**
* 判断字符串是否为合法的 URL
*
* @param url URL 字符串
* @return 是否为合法的 URL
*/
public static boolean isValidURL(String url) {
if (isEmpty(url)) {
return false;
}
String urlRegex = "^(http:\\/\\/www\\.|https:\\/\\/www\\.|http:\\/\\/|https:\\/|www\\.){1}([0-9A-Za-z-\\.@:%_\\+~#=]+)+((\\.[a-zA-Z]{2,6})+)([\\/\\w\\-\\+\\&@#%=~()|]*)?$";
Pattern pattern = Pattern.compile(urlRegex);
Matcher matcher = pattern.matcher(url);
return matcher.matches();
}
/**
* 字符串是否以指定后缀结尾
@ -316,4 +284,47 @@ public class StringHelper {
}
return str.startsWith(prefix);
}
/**
* 移除前缀
*
* @param str 字符串
* @param prefix 前缀
* @return 移除前缀
*/
public static String removePrefix(String str, String prefix) {
return (isBlank(str) || isBlank(prefix) || !str.startsWith(prefix)) ? str : str.substring(prefix.length());
}
/**
* 移除后缀
*
* @param str 字符串
* @param suffix 后缀
* @return 移除后缀
*/
public static String removeSuffix(String str, String suffix) {
return (isBlank(str) || isBlank(suffix) || !str.endsWith(suffix)) ? str : str.substring(0, str.length() - suffix.length());
}
/**
* HTML 转义
*
* @param html html 字符串
* @return 转义字符
*/
public static String escapeHtml(String html) {
return StringUtils.replaceEach(html,
new String[]{"&", "\"", "<", ">", "'"},
new String[]{"&amp;", "&quot;", "&lt;", "&gt;", "&#39;"});
}
/**
* uuid生成
*
* @return uuid
*/
public static String randomUUID() {
return UUID.randomUUID().toString().replace("-", "");
}
}

View File

@ -0,0 +1,306 @@
package com.bonus.common.core.utils;
import org.junit.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoField;
import java.util.Date;
import static org.junit.Assert.*;
public class DateUtilsTest {
@Test
public void testGetNowDate() {
assertNotNull(DateUtils.getNowDate());
}
@Test
public void testGetDate() {
String date = DateUtils.getDate();
assertNotNull(date);
assertEquals(new SimpleDateFormat("yyyy-MM-dd").format(new Date()), date);
}
@Test
public void testGetTime() {
String time = DateUtils.getTime();
assertNotNull(time);
assertEquals(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), time);
}
@Test
public void testParseDate() {
String dateStr = "2024-08-13";
Date date = DateUtils.parseDate(dateStr);
assertNotNull(date);
assertEquals(dateStr, new SimpleDateFormat("yyyy-MM-dd").format(date));
}
@Test
public void testDaysBetween() {
String startDateStr = "2023-12-31";
Date startDate = DateUtils.parseDate(startDateStr);
Date futureDate = DateUtils.addDays(startDate, 60);
long daysBetween = DateUtils.daysBetween(startDate, futureDate);
assertEquals(60, daysBetween);
}
@Test
public void testDaysBetweenCrossYear() throws ParseException {
String startDateStr = "2023-12-31";
String endDateStr = "2024-01-02";
Date startDate = DateUtils.parseDate(startDateStr);
Date endDate = DateUtils.parseDate(endDateStr);
long daysBetween = DateUtils.daysBetween(startDate, endDate);
assertEquals(2, daysBetween);
}
@Test
public void testAddDays() {
Date now = new Date();
Date futureDate = DateUtils.addDays(now, 5);
assertNotNull(futureDate);
Date pastDate = DateUtils.addDays(now, -5);
assertNotNull(pastDate);
}
@Test
public void testAddDaysCrossMonth() throws ParseException {
String dateStr = "2024-02-28";
Date date = DateUtils.parseDate(dateStr);
// 跨月测试增加 1 应该得到 2024-03-01
Date nextDay = DateUtils.addDays(date, 2);
String nextDayStr = new SimpleDateFormat("yyyy-MM-dd").format(nextDay);
assertEquals("2024-03-01", nextDayStr);
}
@Test
public void testIsBefore() {
Date now = new Date();
Date futureDate = DateUtils.addDays(now, 5);
assertTrue(DateUtils.isBefore(now, futureDate));
}
@Test
public void testIsAfter() {
Date now = new Date();
Date pastDate = DateUtils.addDays(now, -5);
assertTrue(DateUtils.isAfter(now, pastDate));
}
@Test
public void testIsEqual() {
Date now = new Date();
Date sameDate = new Date(now.getTime());
assertTrue(DateUtils.isEqual(now, sameDate));
}
@Test
public void testGetUnixTimestamp() {
long timestamp = DateUtils.getUnixTimestamp();
assertTrue(timestamp > 0);
}
@Test
public void testFromUnixTimestamp() {
long timestamp = DateUtils.getUnixTimestamp();
Date date = DateUtils.fromUnixTimestamp(timestamp);
assertNotNull(date);
}
@Test
public void testToUnixTimestamp() {
Date date = new Date();
long timestamp = DateUtils.toUnixTimestamp(date);
assertTrue(timestamp > 0);
}
@Test
public void testGetISO8601Timestamp() {
String iso8601Timestamp = DateUtils.getISO8601Timestamp();
assertNotNull(iso8601Timestamp);
}
@Test
public void testFromISO8601Timestamp() {
String iso8601Timestamp = DateUtils.getISO8601Timestamp();
Date date = DateUtils.fromISO8601Timestamp(iso8601Timestamp);
assertNotNull(date);
}
@Test
public void testGetStartOfWeek() {
Date startOfWeek = DateUtils.getStartOfWeek();
assertNotNull(startOfWeek);
// 检查是否为星期一
LocalDate localDate = LocalDate.now();
LocalDate expectedStart = localDate.with(java.time.DayOfWeek.MONDAY);
assertEquals(DateUtils.toDate(expectedStart), startOfWeek);
}
@Test
public void testGetEndOfWeek() {
Date endOfWeek = DateUtils.getEndOfWeek();
assertNotNull(endOfWeek);
// 检查是否为星期日
LocalDate localDate = LocalDate.now();
LocalDate expectedEnd = localDate.with(java.time.DayOfWeek.SUNDAY);
assertEquals(DateUtils.toDate(expectedEnd.atTime(23, 59, 59)), endOfWeek);
}
@Test
public void testGetWeekOfYear() {
int weekOfYear = DateUtils.getWeekOfYear();
assertEquals(LocalDate.now().get(ChronoField.ALIGNED_WEEK_OF_YEAR), weekOfYear);
}
@Test
public void testGetDateBefore() {
String dateStr = "2024-01-05";
Date date = DateUtils.parseDate(dateStr);
Date dateBefore = DateUtils.getDateBefore(date, 5);
assertNotNull(dateBefore);
}
@Test
public void testGetDateAfter() {
String dateStr = "2024-12-31";
Date date = DateUtils.parseDate(dateStr);
Date dateAfter = DateUtils.getDateAfter(date, 5);
assertNotNull(dateAfter);
}
@Test
public void testGetMonthOrDay() {
String monthOrDay = DateUtils.getMonthOrDay(32, "/");
assertNotNull(monthOrDay);
assertTrue(monthOrDay.matches("\\d{2}/\\d{2}"));
}
@Test
public void testConvertToISO8601() {
String dateStr = "2024-08-32 12:00:00";
String iso8601 = DateUtils.convertToISO8601(dateStr, "yyyy-MM-dd HH:mm:ss");
assertNotNull(iso8601);
assertTrue(iso8601.matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}"));
}
@Test
public void testGetSecondsBetween() {
String startTime = "2024-08-13 12:00:00";
String endTime = "2024-08-13 12:01:00";
long secondsBetween = DateUtils.getSecondsBetween(startTime, endTime, "yyyy-MM-dd HH:mm:ss");
assertEquals(60, secondsBetween);
}
@Test
public void testGetWeekStartAndEndDate() {
String dateStr = "2024-08-13";
String[] weekDates = DateUtils.getWeekStartAndEndDate(dateStr, "yyyy-MM-dd");
assertNotNull(weekDates);
assertEquals(2, weekDates.length);
assertTrue(weekDates[0].matches("\\d{4}-\\d{2}-\\d{2}"));
assertTrue(weekDates[1].matches("\\d{4}-\\d{2}-\\d{2}"));
}
@Test
public void testGetWeekStartAndEndDateTime() {
String dateStr = "2024-08-13";
String[] weekDateTimes = DateUtils.getWeekStartAndEndDateTime(dateStr, "yyyy-MM-dd");
assertNotNull(weekDateTimes);
assertEquals(2, weekDateTimes.length);
assertTrue(weekDateTimes[0].matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}"));
assertTrue(weekDateTimes[1].matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}"));
}
@Test
public void testGetWeekOfMonth() {
String dateStr = "2024-08-13";
int weekOfMonth = DateUtils.getWeekOfMonth(dateStr, "yyyy-MM-dd");
assertTrue(weekOfMonth > 0);
}
@Test
public void testGetCurrentYear() {
String currentYear = DateUtils.getCurrentYear();
assertEquals(String.valueOf(LocalDate.now().getYear()), currentYear);
}
@Test
public void testGetCurrentMonth() {
String currentMonth = DateUtils.getCurrentMonth();
assertEquals(String.format("%02d", LocalDate.now().getMonthValue()), currentMonth);
}
@Test
public void testGetCurrentDay() {
String currentDay = DateUtils.getCurrentDay();
assertEquals(String.format("%02d", LocalDate.now().getDayOfMonth()), currentDay);
}
@Test
public void testDateTimeNow() {
String dateTimeNow = DateUtils.dateTimeNow();
assertNotNull(dateTimeNow);
assertEquals(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()), dateTimeNow);
}
@Test
public void testParseDateToStr() {
Date now = new Date();
String formattedDate = DateUtils.parseDateToStr("yyyy-MM-dd", now);
assertEquals(new SimpleDateFormat("yyyy-MM-dd").format(now), formattedDate);
}
@Test
public void testDateTime() {
String dateString = "2024-08-13";
Date date = DateUtils.dateTime("yyyy-MM-dd", dateString);
assertNotNull(date);
assertEquals(dateString, new SimpleDateFormat("yyyy-MM-dd").format(date));
}
@Test
public void testTimeDistance() {
Date now = new Date();
Date later = DateUtils.addDays(now, 1);
String distance = DateUtils.timeDistance(later, now, null);
assertEquals("1天0小时0分钟", distance);
}
@Test
public void testToDate() {
LocalDateTime now = LocalDateTime.now();
Date date = DateUtils.toDate(now);
assertNotNull(date);
}
@Test
public void testToLocalDateTime() {
Date date = new Date();
LocalDateTime localDateTime = DateUtils.toLocalDateTime(date);
assertNotNull(localDateTime);
}
@Test
public void testGetServerStartDate() {
Date serverStartDate = DateUtils.getServerStartDate();
assertNotNull(serverStartDate);
}
@Test
public void testDatePath() {
String datePath = DateUtils.datePath();
assertNotNull(datePath);
assertEquals(new SimpleDateFormat("yyyy/MM/dd").format(new Date()), datePath);
}
}

View File

@ -0,0 +1,152 @@
package com.bonus.common.core.utils;
import org.junit.Test;
import org.w3c.dom.Document;
import java.io.File;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class FileUtilsTest {
File propertiesFile = new File("src/test/java/com/bonus/common/core/utils/test.properties");
File ymlFile = new File("src/test/java/com/bonus/common/core/utils/test.yml");
File xmlFile = new File("src/test/java/com/bonus/common/core/utils/test.xml");
File jsonFile = new File("src/test/java/com/bonus/common/core/utils/test.json");
File txtFile = new File("src/test/java/com/bonus/common/core/utils/test.txt");
File svgFile = new File("src/test/java/com/bonus/common/core/utils/test.svg");
File cimeFile = new File("src/test/java/com/bonus/common/core/utils/test.cime");
@Test
public void testReadProperties() throws Exception {
Properties properties = FileUtils.readProperties(propertiesFile);
assertEquals("value", properties.getProperty("key"));
assertEquals("anotherValue", properties.getProperty("anotherKey"));
}
@Test
public void testWriteProperties() throws Exception {
Properties properties = new Properties();
properties.setProperty("key", "value");
FileUtils.writeProperties(propertiesFile, properties);
Properties loadedProperties = FileUtils.readProperties(propertiesFile);
assertEquals("value", loadedProperties.getProperty("key"));
}
@Test
public void testReadYml() throws Exception {
Map<String, Object> ymlData = FileUtils.readYml(ymlFile);
assertEquals("value", ymlData.get("key"));
assertEquals("anotherValue", ymlData.get("anotherKey"));
}
@Test
public void testWriteYml() throws Exception {
Map<String, Object> ymlData = Collections.singletonMap("key", "value");
FileUtils.writeYml(ymlFile, ymlData);
Map<String, Object> loadedYmlData = FileUtils.readYml(ymlFile);
assertEquals("value", loadedYmlData.get("key"));
}
@Test
public void testReadXml() throws Exception {
Document document = FileUtils.readXml(xmlFile);
assertNotNull(document.getElementsByTagName("key").item(0));
assertEquals("value", document.getElementsByTagName("key").item(0).getTextContent());
}
@Test
public void testWriteXml() throws Exception {
Document document = FileUtils.readXml(xmlFile);
document.getDocumentElement().setAttribute("newAttribute", "newValue");
FileUtils.writeXml(xmlFile, document);
Document updatedDocument = FileUtils.readXml(xmlFile);
assertEquals("newValue", updatedDocument.getDocumentElement().getAttribute("newAttribute"));
}
@Test
public void testReadJson() throws Exception {
Map<String, Object> jsonData = FileUtils.readJson(jsonFile, Map.class);
assertEquals("value", jsonData.get("key"));
assertEquals("anotherValue", jsonData.get("anotherKey"));
}
@Test
public void testWriteJson() throws Exception {
Map<String, Object> jsonData = Collections.singletonMap("key", "value");
FileUtils.writeJson(jsonFile, jsonData);
Map<String, Object> loadedJsonData = FileUtils.readJson(jsonFile, Map.class);
assertEquals("value", loadedJsonData.get("key"));
}
@Test
public void testReadTxt() throws Exception {
String content = FileUtils.readTxt(txtFile);
assertEquals("This is a test text file.", content);
}
@Test
public void testWriteTxt() throws Exception {
String newContent = "This is updated text content.";
FileUtils.writeTxt(txtFile, newContent);
String updatedContent = FileUtils.readTxt(txtFile);
assertEquals(newContent, updatedContent);
}
@Test
public void testReadSvg() throws Exception {
String content = FileUtils.readSvg(svgFile);
assertEquals("<svg>This is a test SVG file.</svg>", content);
}
@Test
public void testWriteSvg() throws Exception {
String newContent = "<svg>This is updated SVG content.</svg>";
FileUtils.writeSvg(svgFile, newContent);
String updatedContent = FileUtils.readSvg(svgFile);
assertEquals(newContent, updatedContent);
}
@Test
public void testReadCime() throws Exception {
String content = FileUtils.readCime(cimeFile);
assertEquals("This is a test CIME file.", content);
}
@Test
public void testWriteCime() throws Exception {
String newContent = "This is updated CIME content.";
FileUtils.writeCime(cimeFile, newContent);
String updatedContent = FileUtils.readCime(cimeFile);
assertEquals(newContent, updatedContent);
}
@Test
public void testReadPropertyByKey() throws Exception {
String value = FileUtils.readPropertyByKey(propertiesFile, "key");
assertEquals("value", value);
}
@Test
public void testReadYmlByKey() throws Exception {
Object value = FileUtils.readYmlByKey(ymlFile, "key");
assertEquals("value", value);
}
@Test
public void testReadJsonByKey() throws Exception {
Object value = FileUtils.readJsonByKey(jsonFile, "key");
assertEquals("value", value);
}
}

View File

@ -0,0 +1,177 @@
package com.bonus.common.core.utils;
import org.junit.Test;
import static org.junit.Assert.*;
public class StringHelperTest {
@Test
public void testIsEmpty() {
assertTrue(StringHelper.isEmpty(null));
assertTrue(StringHelper.isEmpty(""));
assertFalse(StringHelper.isEmpty("abc"));
}
@Test
public void testIsNotEmpty() {
assertFalse(StringHelper.isNotEmpty(null));
assertFalse(StringHelper.isNotEmpty(""));
assertTrue(StringHelper.isNotEmpty("abc"));
}
@Test
public void testIsBlank() {
assertTrue(StringHelper.isBlank(null));
assertTrue(StringHelper.isBlank(""));
assertTrue(StringHelper.isBlank(" "));
assertFalse(StringHelper.isBlank("abc"));
}
@Test
public void testIsNotBlank() {
assertFalse(StringHelper.isNotBlank(null));
assertFalse(StringHelper.isNotBlank(""));
assertFalse(StringHelper.isNotBlank(" "));
assertTrue(StringHelper.isNotBlank("abc"));
}
@Test
public void testTrim() {
assertNull(StringHelper.trim(null));
assertEquals("abc", StringHelper.trim(" abc "));
}
@Test
public void testToUpperCase() {
assertNull(StringHelper.toUpperCase(null));
assertEquals("ABC", StringHelper.toUpperCase("abc"));
}
@Test
public void testToLowerCase() {
assertNull(StringHelper.toLowerCase(null));
assertEquals("abc", StringHelper.toLowerCase("ABC"));
}
@Test
public void testIsNumeric() {
assertFalse(StringHelper.isNumeric(null));
assertFalse(StringHelper.isNumeric("abc"));
assertTrue(StringHelper.isNumeric("123"));
}
@Test
public void testIsAlphabetic() {
assertFalse(StringHelper.isAlphabetic(null));
assertFalse(StringHelper.isAlphabetic("123"));
assertTrue(StringHelper.isAlphabetic("abc"));
}
@Test
public void testIsAlphanumeric() {
assertFalse(StringHelper.isAlphanumeric(null));
assertFalse(StringHelper.isAlphanumeric("abc!"));
assertTrue(StringHelper.isAlphanumeric("abc123"));
}
@Test
public void testContains() {
assertFalse(StringHelper.contains(null, "abc"));
assertFalse(StringHelper.contains("abc", null));
assertTrue(StringHelper.contains("abc", "a"));
}
@Test
public void testReverse() {
assertNull(StringHelper.reverse(null));
assertEquals("cba", StringHelper.reverse("abc"));
}
@Test
public void testReplace() {
assertNull(StringHelper.replace(null, "a", "b"));
assertEquals("bbc", StringHelper.replace("abc", "a", "b"));
}
@Test
public void testRemoveWhitespace() {
assertNull(StringHelper.removeWhitespace(null));
assertEquals("abc", StringHelper.removeWhitespace(" a b c "));
}
@Test
public void testSplit() {
assertArrayEquals(new String[0], StringHelper.split(null, ","));
assertArrayEquals(new String[]{"a", "b", "c"}, StringHelper.split("a,b,c", ","));
}
@Test
public void testJoin() {
assertNull(StringHelper.join(null, ","));
assertEquals("a,b,c", StringHelper.join(new String[]{"a", "b", "c"}, ","));
}
@Test
public void testCapitalize() {
assertNull(StringHelper.capitalize(null));
assertEquals("Abc", StringHelper.capitalize("abc"));
}
@Test
public void testUncapitalize() {
assertNull(StringHelper.uncapitalize(null));
assertEquals("abc", StringHelper.uncapitalize("Abc"));
}
@Test
public void testEncodeBase64() {
assertNull(StringHelper.encodeBase64(null));
assertEquals("YWJj", StringHelper.encodeBase64("abc"));
}
@Test
public void testDecodeBase64() {
assertNull(StringHelper.decodeBase64(null));
assertEquals("abc", StringHelper.decodeBase64("YWJj"));
}
@Test
public void testEndsWith() {
assertFalse(StringHelper.endsWith(null, "c"));
assertFalse(StringHelper.endsWith("abc", null));
assertTrue(StringHelper.endsWith("abc", "c"));
}
@Test
public void testStartsWith() {
assertFalse(StringHelper.startsWith(null, "a"));
assertFalse(StringHelper.startsWith("abc", null));
assertTrue(StringHelper.startsWith("abc", "a"));
}
@Test
public void testRemovePrefix() {
assertNull(StringHelper.removePrefix(null, "a"));
assertEquals("bc", StringHelper.removePrefix("abc", "a"));
}
@Test
public void testRemoveSuffix() {
assertNull(StringHelper.removeSuffix(null, "c"));
assertEquals("ab", StringHelper.removeSuffix("abc", "c"));
}
@Test
public void testEscapeHtml() {
assertNull(StringHelper.escapeHtml(null));
assertEquals("&lt;div&gt;", StringHelper.escapeHtml("<div>"));
}
@Test
public void testRandomUUID() {
assertNotNull(StringHelper.randomUUID());
assertEquals(32, StringHelper.randomUUID().length());
}
}

View File

@ -0,0 +1 @@
This is updated CIME content.

View File

@ -0,0 +1,4 @@
{
"key": "value",
"anotherKey": "anotherValue"
}

View File

@ -0,0 +1,2 @@
key=value
anotherKey=anotherValue

View File

@ -0,0 +1 @@
<svg>This is updated SVG content.</svg>

After

Width:  |  Height:  |  Size: 39 B

View File

@ -0,0 +1 @@
This is a test text file.

View File

@ -0,0 +1,4 @@
<root>
<key>value</key>
<anotherKey>anotherValue</anotherKey>
</root>

View File

@ -0,0 +1,2 @@
key: value
anotherKey: anotherValue