From e88b1dd794356373f02864599fde6b914f22144c Mon Sep 17 00:00:00 2001 From: jmal Date: Sat, 7 Dec 2024 18:49:22 +0800 Subject: [PATCH 1/5] refactor: Optimize code --- .../jmal/clouddisk/webdav/BasicAuthenticator.java | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/jmal/clouddisk/webdav/BasicAuthenticator.java b/src/main/java/com/jmal/clouddisk/webdav/BasicAuthenticator.java index 49839b2b..3b3e1c38 100644 --- a/src/main/java/com/jmal/clouddisk/webdav/BasicAuthenticator.java +++ b/src/main/java/com/jmal/clouddisk/webdav/BasicAuthenticator.java @@ -1,5 +1,6 @@ package com.jmal.clouddisk.webdav; +import cn.hutool.core.codec.Base64Decoder; import cn.hutool.core.util.StrUtil; import com.jmal.clouddisk.config.FileProperties; import jakarta.servlet.http.HttpServletRequest; @@ -11,13 +12,13 @@ import org.apache.catalina.connector.Request; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.MessageBytes; -import org.apache.tomcat.util.codec.binary.Base64; import org.springframework.stereotype.Component; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.Principal; +import java.util.Base64; @Component @Slf4j @@ -190,7 +191,7 @@ public static class BasicCredentials { public BasicCredentials(ByteChunk input, Charset charset, boolean trimCredentials) throws IllegalArgumentException { authorization = input; - initialOffset = input.getOffset(); + initialOffset = input.getStart(); this.charset = charset; this.trimCredentials = trimCredentials; @@ -219,9 +220,14 @@ private void parseMethod() throws IllegalArgumentException { * surrounding white space. */ private byte[] parseBase64() throws IllegalArgumentException { - byte[] decoded = Base64.decodeBase64(authorization.getBuffer(), base64blobOffset, base64blobLength); + // 提取需要解码的子数组 + byte[] subArray = new byte[base64blobLength]; + System.arraycopy(authorization.getBuffer(), base64blobOffset, subArray, 0, base64blobLength); + + // 使用Java内置的Base64解码器 + byte[] decoded = Base64.getDecoder().decode(subArray); // restore original offset - authorization.setOffset(initialOffset); + authorization.setStart(initialOffset); if (decoded == null) { throw new IllegalArgumentException(sm.getString("basicAuthenticator.notBase64")); } From 7edae12eb2dca51d16a5d588a37857920c2e6eac Mon Sep 17 00:00:00 2001 From: jmal Date: Sat, 7 Dec 2024 18:49:28 +0800 Subject: [PATCH 2/5] =?UTF-8?q?perf=EF=BC=9A=E4=BC=98=E5=8C=96=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E5=8E=86=E5=8F=B2=E7=89=88=E6=9C=AC=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../jmal/clouddisk/lucene/LuceneService.java | 4 +- .../service/impl/CommonFileService.java | 13 ++++-- .../service/impl/FileServiceImpl.java | 2 +- .../service/impl/FileVersionServiceImpl.java | 4 +- .../service/impl/MarkdownServiceImpl.java | 2 - .../com/jmal/clouddisk/util/MyFileUtils.java | 45 ++++++++++++++++++- .../com/jmal/clouddisk/util/TimeUntils.java | 6 +++ 7 files changed, 66 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/jmal/clouddisk/lucene/LuceneService.java b/src/main/java/com/jmal/clouddisk/lucene/LuceneService.java index 9e4d15de..1c2e12c5 100644 --- a/src/main/java/com/jmal/clouddisk/lucene/LuceneService.java +++ b/src/main/java/com/jmal/clouddisk/lucene/LuceneService.java @@ -44,6 +44,8 @@ import java.util.concurrent.*; import java.util.concurrent.locks.ReentrantLock; +import static com.jmal.clouddisk.service.Constants.UPDATE_DATE; + /** * @author jmal *

@@ -536,7 +538,7 @@ private static Sort getSort(SearchDTO searchDTO) { } // 创建排序规则 SortField sortField; - if ("updateDate".equals(searchDTO.getSortProp())) { + if (UPDATE_DATE.equals(searchDTO.getSortProp())) { sortField = new SortField("modified", SortField.Type.LONG, "descending".equalsIgnoreCase(searchDTO.getSortOrder())); } else if ("size".equals(searchDTO.getSortProp())) { sortField = new SortField("size", SortField.Type.LONG, "descending".equalsIgnoreCase(searchDTO.getSortOrder())); diff --git a/src/main/java/com/jmal/clouddisk/service/impl/CommonFileService.java b/src/main/java/com/jmal/clouddisk/service/impl/CommonFileService.java index 72459df1..22797d39 100644 --- a/src/main/java/com/jmal/clouddisk/service/impl/CommonFileService.java +++ b/src/main/java/com/jmal/clouddisk/service/impl/CommonFileService.java @@ -447,7 +447,7 @@ private void updateVideoInfo(File file, FileDocument fileExists, String contentT } } - private static void setDateTime(File file, Update update) { + public static LocalDateTime setDateTime(File file, Update update) { LocalDateTime updateDateTime; LocalDateTime uploadDateTime; try { @@ -462,6 +462,7 @@ private static void setDateTime(File file, Update update) { } update.set(UPLOAD_DATE, uploadDateTime); update.set(UPDATE_DATE, updateDateTime); + return updateDateTime; } public FileDocument getFileDocument(String userId, String fileName, String relativePath, Query query) { @@ -987,11 +988,14 @@ public void modifyFile(String username, File file) { update.set(Constants.SUFFIX, suffix); String fileContentType = getContentType(file, contentType); update.set(Constants.CONTENT_TYPE, fileContentType); - LocalDateTime updateDate = LocalDateTime.now(TimeUntils.ZONE_ID); - update.set("updateDate", updateDate); + LocalDateTime updateTime = setDateTime(file, update); + // 如果size相同,不更新,且更新时间在1秒内,则不更新 + if (fileDocument.getSize() == file.length() && TimeUntils.isWithinOneSecond(fileDocument.getUpdateDate(), updateTime)) { + return; + } UpdateResult updateResult = mongoTemplate.upsert(query, update, COLLECTION_NAME); fileDocument.setSize(file.length()); - fileDocument.setUpdateDate(updateDate); + fileDocument.setUpdateDate(updateTime); if (contentType.contains(Constants.CONTENT_TYPE_MARK_DOWN) || "md".equals(suffix)) { // 写入markdown内容 String markDownContent = FileUtil.readString(file, MyFileUtils.getFileCharset(file)); @@ -1006,6 +1010,7 @@ public void modifyFile(String username, File file) { // 修改文件之后保存历史版本 fileVersionService.saveFileVersion(username, Paths.get(relativePath, file.getName()).toString(), userId); } + log.info("修改文件完成: {}", file.getAbsolutePath()); } } diff --git a/src/main/java/com/jmal/clouddisk/service/impl/FileServiceImpl.java b/src/main/java/com/jmal/clouddisk/service/impl/FileServiceImpl.java index 71e6009e..1f69c256 100644 --- a/src/main/java/com/jmal/clouddisk/service/impl/FileServiceImpl.java +++ b/src/main/java/com/jmal/clouddisk/service/impl/FileServiceImpl.java @@ -1735,7 +1735,7 @@ private boolean renameFileError(String newFileName, String fileId, String filePa Update update = new Update(); update.set("name", newFileName); update.set(Constants.SUFFIX, MyFileUtils.extName(newFileName)); - update.set("updateDate", LocalDateTime.now(TimeUntils.ZONE_ID)); + setDateTime(file, update); mongoTemplate.upsert(query, update, COLLECTION_NAME); } else { return true; diff --git a/src/main/java/com/jmal/clouddisk/service/impl/FileVersionServiceImpl.java b/src/main/java/com/jmal/clouddisk/service/impl/FileVersionServiceImpl.java index 4ae3ffa3..30622f50 100644 --- a/src/main/java/com/jmal/clouddisk/service/impl/FileVersionServiceImpl.java +++ b/src/main/java/com/jmal/clouddisk/service/impl/FileVersionServiceImpl.java @@ -58,6 +58,8 @@ import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; +import static com.jmal.clouddisk.service.Constants.UPDATE_DATE; + /** * @author jmal * @Description 文件版本管理 @@ -352,7 +354,7 @@ public Long recovery(String gridFSId) { FileUtil.writeFromStream(inputStream, file); Query query = new Query().addCriteria(Criteria.where("_id").is(fileId)); Update update = new Update(); - update.set("updateDate", time); + update.set(UPDATE_DATE, time); mongoTemplate.updateFirst(query, update, FileDocument.class); luceneService.pushCreateIndexQueue(fileId); } catch (IOException e) { diff --git a/src/main/java/com/jmal/clouddisk/service/impl/MarkdownServiceImpl.java b/src/main/java/com/jmal/clouddisk/service/impl/MarkdownServiceImpl.java index ae1dd602..b247c9d5 100644 --- a/src/main/java/com/jmal/clouddisk/service/impl/MarkdownServiceImpl.java +++ b/src/main/java/com/jmal/clouddisk/service/impl/MarkdownServiceImpl.java @@ -603,7 +603,6 @@ public ResponseResult deleteDraft(String fileId, String username) { File file = Paths.get(fileProperties.getRootDir(), username, fileDocument.getPath(), fileDocument.getName()).toFile(); FileUtil.writeString(fileDocument.getContentText(), file, StandardCharsets.UTF_8); - Update update = new Update(); update.unset(Constants.DRAFT); mongoTemplate.upsert(query, update, CommonFileService.COLLECTION_NAME); @@ -639,7 +638,6 @@ public ResponseResult editTextByPath(UploadApiParamDTO upload) { String userId = upload.getUserId(); commonFileService.checkPermissionUserId(userId, upload.getOperationPermissionList(), OperationPermission.PUT); FileUtil.writeString(upload.getContentText(), file, StandardCharsets.UTF_8); - commonFileService.modifyFile(upload.getUsername(), file); return ResultUtil.success(); } diff --git a/src/main/java/com/jmal/clouddisk/util/MyFileUtils.java b/src/main/java/com/jmal/clouddisk/util/MyFileUtils.java index 0f4d790f..c87c2994 100644 --- a/src/main/java/com/jmal/clouddisk/util/MyFileUtils.java +++ b/src/main/java/com/jmal/clouddisk/util/MyFileUtils.java @@ -1,16 +1,22 @@ package com.jmal.clouddisk.util; +import cn.hutool.core.date.TimeInterval; import cn.hutool.core.io.CharsetDetector; import cn.hutool.core.io.FileTypeUtil; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.StrUtil; +import cn.hutool.crypto.digest.DigestAlgorithm; import com.jmal.clouddisk.service.Constants; import lombok.extern.slf4j.Slf4j; import org.mozilla.universalchardet.UniversalDetector; import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.List; @@ -28,8 +34,13 @@ private MyFileUtils() { } - public static void main(String[] args) { + public static void main(String[] args) throws IOException, NoSuchAlgorithmException { System.out.println(extName("file")); + File file1 = new File("/Users/jmal/Downloads/归档.zip"); + File file2 = new File("/Users/jmal/Downloads/归档.zip"); + TimeInterval timer = new TimeInterval(); + System.out.println(hashEquals(file1.getAbsolutePath(), file2.getAbsolutePath())); + System.out.println(timer.interval()); } public static String extName(File file) { @@ -126,6 +137,38 @@ public static boolean checkNoCacheFile(File file) { public static boolean hasContentFile(String type) { return hasContentTypes.contains(type); } + + public static MessageDigest digest; + + static { + try { + digest = MessageDigest.getInstance(DigestAlgorithm.MD5.getValue()); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + } + + public static String calculateHash(String filePath) throws IOException { + try (FileInputStream fis = new FileInputStream(filePath)) { + byte[] buffer = new byte[1024]; + int bytesRead; + while ((bytesRead = fis.read(buffer)) != -1) { + digest.update(buffer, 0, bytesRead); + } + } + byte[] hashBytes = digest.digest(); + StringBuilder sb = new StringBuilder(); + for (byte b : hashBytes) { + sb.append(String.format("%02x", b)); + } + return sb.toString(); + } + + public static boolean hashEquals(String filePath1, String filePath2) throws IOException { + String hash1 = calculateHash(filePath1); + String hash2 = calculateHash(filePath2); + return hash1.equals(hash2); + } } diff --git a/src/main/java/com/jmal/clouddisk/util/TimeUntils.java b/src/main/java/com/jmal/clouddisk/util/TimeUntils.java index df0f3831..94059413 100644 --- a/src/main/java/com/jmal/clouddisk/util/TimeUntils.java +++ b/src/main/java/com/jmal/clouddisk/util/TimeUntils.java @@ -10,6 +10,7 @@ import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; +import java.time.temporal.ChronoUnit; import cn.hutool.core.text.CharSequenceUtil; import com.jmal.clouddisk.exception.ExceptionType; @@ -641,4 +642,9 @@ public static String lastYearOnTime(String time) throws CommonException { public static String getLocalDateTime(LocalDateTime date) { return date.format(FORMAT_TIME); } + + public static boolean isWithinOneSecond(LocalDateTime time1, LocalDateTime time2) { + long secondsDifference = Math.abs(time1.until(time2, ChronoUnit.SECONDS)); + return secondsDifference < 1; + } } From d229a8f563f78613a14fe219451d1a635d979e6d Mon Sep 17 00:00:00 2001 From: jmal Date: Sat, 7 Dec 2024 18:54:24 +0800 Subject: [PATCH 3/5] refactor: Optimize code --- .../service/impl/FileVersionServiceImpl.java | 2 +- .../com/jmal/clouddisk/util/TimeUntils.java | 585 ------------------ .../clouddisk/webdav/BasicAuthenticator.java | 11 +- 3 files changed, 2 insertions(+), 596 deletions(-) diff --git a/src/main/java/com/jmal/clouddisk/service/impl/FileVersionServiceImpl.java b/src/main/java/com/jmal/clouddisk/service/impl/FileVersionServiceImpl.java index 30622f50..372f49d6 100644 --- a/src/main/java/com/jmal/clouddisk/service/impl/FileVersionServiceImpl.java +++ b/src/main/java/com/jmal/clouddisk/service/impl/FileVersionServiceImpl.java @@ -170,7 +170,7 @@ private InputStream getInputStream(GridFSFile gridFSFile) throws IOException { return gzipDecompress(gridFsResource.getInputStream(), gridFSFile.getMetadata()); } - @Nullable + @NotNull private GridFSFile getGridFSFile(String gridFSId) { Query query = getQueryOfId(gridFSId); return gridFsTemplate.findOne(query); diff --git a/src/main/java/com/jmal/clouddisk/util/TimeUntils.java b/src/main/java/com/jmal/clouddisk/util/TimeUntils.java index 94059413..7d075f41 100644 --- a/src/main/java/com/jmal/clouddisk/util/TimeUntils.java +++ b/src/main/java/com/jmal/clouddisk/util/TimeUntils.java @@ -1,22 +1,11 @@ package com.jmal.clouddisk.util; -import java.time.DayOfWeek; import java.time.Instant; -import java.time.LocalDate; import java.time.LocalDateTime; -import java.time.LocalTime; -import java.time.Year; -import java.time.YearMonth; import java.time.ZoneId; import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; import java.time.temporal.ChronoUnit; -import cn.hutool.core.text.CharSequenceUtil; -import com.jmal.clouddisk.exception.ExceptionType; - -import com.jmal.clouddisk.exception.CommonException; - /** * @Description 时间工具类 * @Author jmal @@ -25,13 +14,6 @@ */ public class TimeUntils { - public final static String TIME_TYPE_MINUTE = "minute"; - public final static String TIME_TYPE_HOUR = "hour"; - public final static String TIME_TYPE_DAY = "day"; - public final static String TIME_TYPE_WEEK = "week"; - public final static String TIME_TYPE_MONTH = "month"; - public final static String TIME_TYPE_YEAR = "year"; - public static final DateTimeFormatter UPDATE_FORMAT_TIME = DateTimeFormatter.ofPattern("yyyy 年 MM 月 dd 日 HH:mm:ss"); public static final DateTimeFormatter UPLOAD_FORMAT_TIME = DateTimeFormatter.ofPattern("yyyy 年 MM 月 dd 日"); @@ -40,129 +22,11 @@ public class TimeUntils { private static final DateTimeFormatter FORMAT_FILE_DAY = DateTimeFormatter.ofPattern("yyyyMMdd"); private static final DateTimeFormatter FORMAT_FILE_MONTH = DateTimeFormatter.ofPattern("yyyy-MM"); - private static final DateTimeFormatter FORMAT_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - private static final DateTimeFormatter FORMAT_DAY = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - private static final DateTimeFormatter FORMAT_MONTH = DateTimeFormatter.ofPattern("yyyy-MM"); - private static final DateTimeFormatter FORMAT_YEAR = DateTimeFormatter.ofPattern("yyyy"); public static final ZoneId ZONE_ID = ZoneId.systemDefault(); - public static LocalDateTime getLocalDateTime(String time) throws CommonException { - int timelength = time.length(); - LocalDateTime date; - try { - switch (timelength) { - case 10: - date = LocalDate.parse(time, FORMAT_DAY).atStartOfDay(); - break; - case 7: - date = YearMonth.parse(time, FORMAT_MONTH).atDay(1).atStartOfDay(); - break; - case 4: - Year year = Year.parse(time, FORMAT_YEAR); - date = LocalDateTime.of(year.getValue(), 1, 1, 0, 0); - break; - default: - date = LocalDateTime.parse(time, FORMAT_TIME); - break; - } - } catch (DateTimeParseException e) { - throw new CommonException(ExceptionType.INCORRECT_DATE.getCode(), "时间格式不正确,应为%s或者%s或者%s或者%s".formatted("yyyy", "yyyy-MM", "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss")); - } - return date; - } - - /*** - * 获取该时间类型有多少个时间段 - * 例如:timeType = day,则有24个时间段 - * timeType = month,则有12个时间段 - * @param time - * @param timeType - */ - public static int getTrendCount(String time, String timeType) throws CommonException { - int trendsCount; - switch (timeType) { - case TIME_TYPE_MINUTE: - case TIME_TYPE_HOUR: - // 时 - // 分 - trendsCount = 60; - break; - case TIME_TYPE_DAY: - // 日 - trendsCount = 24; - break; - case TIME_TYPE_WEEK: - // 周 - trendsCount = 7; - break; - case TIME_TYPE_MONTH: - // 月 - trendsCount = getMaxDayOfMonth(time); - break; - case TIME_TYPE_YEAR: - // 年 - trendsCount = 12; - break; - default: - return throwTimeTypeException(); - } - return trendsCount; - } - - private static int throwTimeTypeException() throws CommonException { - throw new CommonException(ExceptionType.INCORRECT_DATE.getCode(), "时间类型格式不正确,应为:minute/hour/day/week/month/year"); - } - - /** - * 获取某月有多少天 - * - * @param time - * @return - */ - private static int getMaxDayOfMonth(String time) throws CommonException { - if (CharSequenceUtil.isBlank(time)) { - return 30; - } - LocalDateTime date = getLocalDateTime(time); - return date.getMonth().length(isLeap(date.getYear())); - } - - private static final long SECOND_UNIT = 1000; - private static final long MINUTE_UNIT = SECOND_UNIT * 60; - private static final long HOUR_UNIT = MINUTE_UNIT * 60; - - public static String getAgoTime(long now , LocalDateTime updateDate){ - - int diffNumber = 0; - String timeType = " second"; - - long update = TimeUntils.getMilli(updateDate); - long diff = now - update; - if(diff > SECOND_UNIT && diff < MINUTE_UNIT){ - diffNumber = (int) (diff / SECOND_UNIT); - timeType = " 秒钟"; - }else if(diff >= MINUTE_UNIT && diff < HOUR_UNIT){ - diffNumber = (int) (diff / MINUTE_UNIT); - timeType = " 分钟"; - }else{ - return "刚刚"; - } - return diffNumber + timeType + " 前"; - } - - /*** - * 时间戳转时间格式(yyyy-MM-dd HH:mm:ss)字符串 - * @return - */ - public static String getStringTime(long timestamp) { - LocalDateTime date = getLocalDateTime(timestamp); - return date.format(FORMAT_TIME); - } - /*** * yyyyMMdd - * @return */ public static String getFileTimeStrOfDay() { return LocalDateTime.now(TimeUntils.ZONE_ID).format(FORMAT_FILE_DAY); @@ -170,7 +34,6 @@ public static String getFileTimeStrOfDay() { /*** * yyyy-MM - * @return */ public static String getFileTimeStrOfMonth() { return LocalDateTime.now(TimeUntils.ZONE_ID).format(FORMAT_FILE_MONTH); @@ -178,8 +41,6 @@ public static String getFileTimeStrOfMonth() { /*** * yyyy-MM - * @param dateTime - * @return */ public static String getFileTimeStrOfMonth(LocalDateTime dateTime) { return dateTime.format(FORMAT_FILE_MONTH); @@ -187,462 +48,16 @@ public static String getFileTimeStrOfMonth(LocalDateTime dateTime) { /*** * 时间戳转LocalDateTime - * @return */ public static LocalDateTime getLocalDateTime(long timestamp) { Instant instant = Instant.ofEpochMilli(timestamp); return LocalDateTime.ofInstant(instant, ZONE_ID); } - public static String getStringTime(String dateType, long thisTime) { - String time = getStringTime(thisTime); - switch (dateType) { - case TIME_TYPE_DAY: - // 日 - return time; - case TIME_TYPE_MONTH: - // 月 - return time.substring(0, 10); - case TIME_TYPE_YEAR: - // 年 - return time.substring(0, 7); - default: - return time; - } - } - - /*** - * 时间戳转时间格式(yyyy-MM-dd HH:mm:ss)字符串 - * @param time - * @return - */ - public static long getTimestamp(String time) throws CommonException { - LocalDateTime localDateTime = getLocalDateTime(time); - return localDateTime.atZone(ZONE_ID).toInstant().toEpochMilli(); - } - public static long getMilli(LocalDateTime localDateTime){ return localDateTime.atZone(ZONE_ID).toInstant().toEpochMilli(); } - /*** - * 获取当前时间 minute/hour/day/week/month/year MIN - * @param time - * @param timeType - * @return long - * @throws CommonException - */ - public static long toTypeThisTimeInMillis(String time, String timeType) throws CommonException { - LocalDateTime firstDate = toTypeThisTimeLocalDateTime(time,timeType); - return firstDate.atZone(ZONE_ID).toInstant().toEpochMilli(); - } - - /*** - * 获取当前时间 minute/hour/day/week/month/year MIN - * @param time - * @param timeType - * @return LocalDateTime - * @throws CommonException - */ - public static LocalDateTime toTypeThisTimeLocalDateTime(String time, String timeType) throws CommonException { - LocalDateTime firstDate = null; - LocalDateTime date = getLocalDateTime(time); - switch (timeType) { - case TIME_TYPE_MINUTE: - // 分 - firstDate = date.minusSeconds(date.getSecond()).minusNanos(date.getNano()); - break; - case TIME_TYPE_HOUR: - // 时 - firstDate = date.minusMinutes(date.getMinute()).minusSeconds(date.getSecond()).minusNanos(date.getNano()); - break; - case TIME_TYPE_DAY: - // 日 - firstDate = LocalDateTime.of(date.toLocalDate(), LocalTime.MIN); - break; - case TIME_TYPE_WEEK: - // 周 - firstDate = date.with(DayOfWeek.MONDAY); - firstDate = LocalDateTime.of(firstDate.toLocalDate(), LocalTime.MIN); - break; - case TIME_TYPE_MONTH: - // 月 - firstDate = date.withDayOfMonth(1); - firstDate = LocalDateTime.of(firstDate.toLocalDate(), LocalTime.MIN); - break; - case TIME_TYPE_YEAR: - // 年 - firstDate = date.withDayOfYear(1); - firstDate = LocalDateTime.of(firstDate.toLocalDate(), LocalTime.MIN); - break; - default: - throwTimeTypeException(); - } - return firstDate; - } - - /*** - * 获取下一时间 - * @param time 2020-02-03 12:23:12 - * @param timeType minute/hour/day/week/month/year - * @return - * @throws CommonException - */ - public static LocalDateTime toTypeNextLocalDateTime(String time, String timeType) throws CommonException { - LocalDateTime date = getLocalDateTime(time); - return toTypeNextLocalDateTime(date,timeType); - } - - /*** - * 获取下一时间 - * @param date - * @param timeType - * @return - * @throws CommonException - */ - public static LocalDateTime toTypeNextLocalDateTime(LocalDateTime date, String timeType) throws CommonException { - LocalDateTime lastDate = null; - switch (timeType) { - case TIME_TYPE_MINUTE: - // 分 - lastDate = date.minusSeconds(date.getSecond()).minusNanos(date.getNano()).plusMinutes(1); - break; - case TIME_TYPE_HOUR: - // 时 - lastDate = date.minusMinutes(date.getMinute()).minusSeconds(date.getSecond()).minusNanos(date.getNano()).plusHours(1); - break; - case TIME_TYPE_DAY: - // 日 - lastDate = LocalDateTime.of(date.toLocalDate(), LocalTime.MAX); - break; - case TIME_TYPE_WEEK: - // 周 - lastDate = date.with(DayOfWeek.SUNDAY); - lastDate = LocalDateTime.of(lastDate.toLocalDate(), LocalTime.MAX); - break; - case TIME_TYPE_MONTH: - // 月 - lastDate = date.withDayOfMonth(date.getMonth().length(isLeap(date.getYear()))); - lastDate = LocalDateTime.of(lastDate.toLocalDate(), LocalTime.MAX); - break; - case TIME_TYPE_YEAR: - // 年 - lastDate = date.withDayOfYear(getMaxDayOfYear(date.getYear())); - lastDate = LocalDateTime.of(lastDate.toLocalDate(), LocalTime.MAX); - break; - default: - throwTimeTypeException(); - } - return lastDate; - } - - /*** - * 获取下一时间 - * @param timeType minute/hour/day/week/month/year - * @return - * @throws CommonException - */ - public static LocalDateTime toNextLocalDateTime(LocalDateTime date, String timeType) throws CommonException { - LocalDateTime lastDate = null; - switch (timeType) { - case TIME_TYPE_MINUTE: - // 分 - lastDate = date.plusMinutes(1); - break; - case TIME_TYPE_HOUR: - // 时 - lastDate = date.plusHours(1); - break; - case TIME_TYPE_DAY: - // 日 - lastDate = date.plusDays(1); - break; - case TIME_TYPE_WEEK: - // 周 - lastDate = date.plusWeeks(1); - break; - case TIME_TYPE_MONTH: - // 月 - lastDate = date.plusMonths(1); - break; - case TIME_TYPE_YEAR: - // 年 - lastDate = date.plusYears(1); - break; - default: - throwTimeTypeException(); - } - return lastDate; - } - - /*** - * 获取下一时间 - * @param time 2020-02-03 12:23:12 - * @param timeType minute/hour/day/week/month/year - * @return - * @throws CommonException - */ - public static long toTypeNextTimeInMillis(String time, String timeType) throws CommonException { - LocalDateTime lastDate = toTypeNextLocalDateTime(time,timeType); - return lastDate.atZone(ZONE_ID).toInstant().toEpochMilli(); - } - - /*** - * 判断是否为闰年 - * @param year - * @return - */ - private static boolean isLeap(long year) { - return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0); - } - - /*** - * 判断当年有多少天 - * @param year - * @return - */ - private static int getMaxDayOfYear(int year) { - return isLeap(year) ? 366 : 365; - } - - /** - * 获取某个分/小时/天/月的时间戳 - * - * @param createTime 2020-02-03 12:23:12 - * @param timeType minute/hour/day/week/month/year - * @param index - * @return - * @throws CommonException - */ - public static LocalDateTime toTypeTimeOfLocalDateTime(String createTime, String timeType, int index) throws CommonException { - LocalDateTime date = null; - switch (timeType) { - case TIME_TYPE_MINUTE: - // 分 - date = tpTypeTimeOfMinute(createTime, index); - break; - case TIME_TYPE_HOUR: - // 时 - date = tpTypeTimeOfHour(createTime, index); - break; - case TIME_TYPE_DAY: - // 日 - date = tpTypeTimeOfDay(createTime, index); - break; - case TIME_TYPE_WEEK: - // 周 - date = tpTypeTimeOfWeek(createTime, index); - break; - case TIME_TYPE_MONTH: - // 月 - date = tpTypeTimeOfMonth(createTime, index); - break; - case TIME_TYPE_YEAR: - // 年 - date = tpTypeTimeOfYear(createTime, index); - break; - default: - throwTimeTypeException(); - } - return date; - } - - /*** - * 获取某个分/小时/天/月的时间戳 - * @param time - * @param timeType - * @param index - * @return - * @throws CommonException - */ - public static long toTypeTimeOfMilli(String time, String timeType, int index) throws CommonException { - return toTypeTimeOfLocalDateTime(time,timeType,index).atZone(ZONE_ID).toInstant().toEpochMilli(); - } - - /** - * 获取某个分/小时/天/月的时间 下一个时刻的时间 - * @param timeType minute/hour/day/week/month/year - * @return - * @throws CommonException - */ - public static LocalDateTime toTypeTimeOfNextDate(LocalDateTime date, String timeType) throws CommonException { - return toTypeTimeOfNextDate(date,timeType,1); - } - - /** - * 获取某个分/小时/天/月的时间 下一个时刻的时间 - * - * @param timeType minute/hour/day/week/month/year - * @return - */ - public static LocalDateTime toTypeTimeOfNextDate(LocalDateTime date, String timeType,int amount) throws CommonException { - switch (timeType) { - case TIME_TYPE_MINUTE: - // 分 - date = date.plusSeconds(amount); - break; - case TIME_TYPE_HOUR: - // 时 - date = date.plusMinutes(amount); - break; - case TIME_TYPE_DAY: - // 日 - date = date.plusHours(amount); - break; - case TIME_TYPE_WEEK: - // 周 - date = date.plusDays(amount); - break; - case TIME_TYPE_MONTH: - // 月 - date = date.plusDays(amount); - break; - case TIME_TYPE_YEAR: - // 年 - date = date.plusMonths(amount); - break; - default: - throwTimeTypeException(); - } - return date; - } - - /** - * 获取某个分/小时/天/月的时间 - * - * @param timeType minute/hour/day/week/month/year - * @param index - * @return - */ - public static LocalDateTime toTypeTimeOfDate(String time, String timeType, int index) throws CommonException { - return toTypeTimeOfLocalDateTime(time,timeType,index); - } - - private static LocalDateTime tpTypeTimeOfYear(String time, int month) throws CommonException { - LocalDateTime date = toTypeThisTimeLocalDateTime(time,TIME_TYPE_YEAR); - return date.plusMonths(month); - } - - private static LocalDateTime tpTypeTimeOfMonth(String time, int day) throws CommonException { - LocalDateTime date = toTypeThisTimeLocalDateTime(time, TIME_TYPE_MONTH); - return date.plusDays(day); - } - - private static LocalDateTime tpTypeTimeOfWeek(String time, int day) throws CommonException { - LocalDateTime date = toTypeThisTimeLocalDateTime(time, TIME_TYPE_WEEK); - return date.plusDays(day); - } - - private static LocalDateTime tpTypeTimeOfDay(String time, int hour) throws CommonException { - LocalDateTime date = toTypeThisTimeLocalDateTime(time, TIME_TYPE_DAY); - return date.plusHours(hour); - } - - private static LocalDateTime tpTypeTimeOfHour(String time, int minute) throws CommonException { - LocalDateTime date = toTypeThisTimeLocalDateTime(time, TIME_TYPE_HOUR); - return date.plusMinutes(minute); - } - - private static LocalDateTime tpTypeTimeOfMinute(String time, int second) throws CommonException { - LocalDateTime date = toTypeThisTimeLocalDateTime(time, TIME_TYPE_MINUTE); - return date.plusSeconds(second); - } - - /*** - * 获取上一时间 - * @param timeType minute/hour/day/week/month/year - * @return LocalDateTime - * @throws CommonException - */ - private static LocalDateTime toLastLocalDateTime(LocalDateTime date, String timeType) throws CommonException { - LocalDateTime lastDate = null; - switch (timeType) { - case TIME_TYPE_MINUTE: - // 分 - lastDate = date.minusSeconds(1); - break; - case TIME_TYPE_HOUR: - // 时 - lastDate = date.minusMinutes(1); - break; - case TIME_TYPE_DAY: - // 日 - lastDate = date.minusHours(1); - break; - case TIME_TYPE_WEEK: - // 周 - lastDate = date.minusDays(1); - break; - case TIME_TYPE_MONTH: - // 月 - lastDate = date.minusDays(1); - break; - case TIME_TYPE_YEAR: - // 年 - lastDate = date.minusMonths(1); - break; - default: - throwTimeTypeException(); - } - return lastDate; - } - -// public static void main(String[] args){ -// try { -// TimeUntils.getStringTime(1580885481000L); -// long stime = System.currentTimeMillis(); -// -// String time = "2020-01-08 14:12:45"; -// String timeType = "minute"; -// -// LocalDateTime sstime = toTypeThisTimeLocalDateTime(time,timeType); -// Object strDate = toNextLocalDateTime(sstime,timeType); -// -// System.out.println("耗时:"+(System.currentTimeMillis() - stime)); -// -// System.out.println(strDate); -// } catch (CommonException e) { -// System.err.println(e.getMsg()); -// } -// } - - /*** - * 获取上一时间 - * @param time - * @param timeType minute/hour/day/week/month/year - * @return - * @throws CommonException - */ - public static String lastTime(String time, String timeType) throws CommonException { - return toLastLocalDateTime(getLocalDateTime(time),timeType).format(FORMAT_TIME); - } - - public static long toLastTimeByType(long thisTime, String timeType) throws CommonException { - LocalDateTime date = getLocalDateTime(thisTime); - return toLastLocalDateTime(date,timeType).atZone(ZONE_ID).toInstant().toEpochMilli(); - } - - /*** - * 去年的该时间段 同比 - * @param time - * @return - * @throws CommonException - */ - public static String lastYearOnTime(String time) throws CommonException { - try { - LocalDateTime date = toLastLocalDateTime(getLocalDateTime(time),TIME_TYPE_YEAR); - date = date.minusYears(1); - return date.format(FORMAT_TIME); - } catch (Exception e) { - throwTimeTypeException(); - } - return "1997"; - } - - public static String getLocalDateTime(LocalDateTime date) { - return date.format(FORMAT_TIME); - } - public static boolean isWithinOneSecond(LocalDateTime time1, LocalDateTime time2) { long secondsDifference = Math.abs(time1.until(time2, ChronoUnit.SECONDS)); return secondsDifference < 1; diff --git a/src/main/java/com/jmal/clouddisk/webdav/BasicAuthenticator.java b/src/main/java/com/jmal/clouddisk/webdav/BasicAuthenticator.java index 3b3e1c38..f5846488 100644 --- a/src/main/java/com/jmal/clouddisk/webdav/BasicAuthenticator.java +++ b/src/main/java/com/jmal/clouddisk/webdav/BasicAuthenticator.java @@ -1,6 +1,5 @@ package com.jmal.clouddisk.webdav; -import cn.hutool.core.codec.Base64Decoder; import cn.hutool.core.util.StrUtil; import com.jmal.clouddisk.config.FileProperties; import jakarta.servlet.http.HttpServletRequest; @@ -55,11 +54,6 @@ public boolean getTrimCredentials() { } - public void setTrimCredentials(boolean trimCredentials) { - this.trimCredentials = trimCredentials; - } - - @Override protected boolean doAuthenticate(Request request, HttpServletResponse response) throws IOException { @@ -73,7 +67,7 @@ protected boolean doAuthenticate(Request request, HttpServletResponse response) if (authorization != null) { authorization.toBytes(); ByteChunk authorizationBC = authorization.getByteChunk(); - BasicCredentials credentials = null; + BasicCredentials credentials; try { credentials = new BasicCredentials(authorizationBC, charset, getTrimCredentials()); String username = credentials.getUsername(); @@ -164,7 +158,6 @@ public static class BasicCredentials { * -- GETTER -- * Trivial accessor. * - * @return the decoded username token as a String, which is never be null, but can be empty. */ @Getter private String username = null; @@ -172,8 +165,6 @@ public static class BasicCredentials { * -- GETTER -- * Trivial accessor. * - * @return the decoded password token as a String, or null if no password was found in the - * credentials. */ @Getter private String password = null; From 2dadfaffa0ef3a6c6a66cf819e39e4d33f3dd284 Mon Sep 17 00:00:00 2001 From: jmal Date: Sat, 7 Dec 2024 18:55:20 +0800 Subject: [PATCH 4/5] refactor: Optimize code --- .../service/impl/FileVersionServiceImpl.java | 15 ++++----------- .../jmal/clouddisk/webdav/BasicAuthenticator.java | 2 +- 2 files changed, 5 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/jmal/clouddisk/service/impl/FileVersionServiceImpl.java b/src/main/java/com/jmal/clouddisk/service/impl/FileVersionServiceImpl.java index 372f49d6..0174b146 100644 --- a/src/main/java/com/jmal/clouddisk/service/impl/FileVersionServiceImpl.java +++ b/src/main/java/com/jmal/clouddisk/service/impl/FileVersionServiceImpl.java @@ -28,7 +28,6 @@ import org.apache.commons.io.IOUtils; import org.bson.Document; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import org.mozilla.universalchardet.UniversalDetector; import org.springframework.core.io.InputStreamResource; import org.springframework.data.domain.Sort; @@ -159,10 +158,7 @@ private static Metadata setMetadata(long size, String filepath, String filename, */ public InputStream readFileVersion(String gridFSId) throws IOException { GridFSFile gridFSFile = getGridFSFile(gridFSId); - if (gridFSFile != null) { - return getInputStream(gridFSFile); - } - return null; + return getInputStream(gridFSFile); } private InputStream getInputStream(GridFSFile gridFSFile) throws IOException { @@ -229,7 +225,7 @@ public ResponseResult> listFileVersionByPath(String path, Integer @Override public FileDocument getFileById(String gridFSId) { GridFSFile gridFSFile = getGridFSFile(gridFSId); - if (gridFSFile == null || gridFSFile.getMetadata() == null) { + if (gridFSFile.getMetadata() == null) { return null; } String fileId = gridFSFile.getFilename(); @@ -263,9 +259,6 @@ private Charset getCharset(GridFSFile gridFSFile) { public StreamingResponseBody getStreamFileById(String gridFSId) { return outputStream -> { GridFSFile gridFSFile = getGridFSFile(gridFSId); - if (gridFSFile == null) { - return; - } Charset charset = getCharset(gridFSFile); try (InputStream inputStream = getInputStream(gridFSFile); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset); @@ -329,7 +322,7 @@ public void rename(String sourceFileId, String destinationFileId) { @Override public Long recovery(String gridFSId) { GridFSFile gridFSFile = getGridFSFile(gridFSId); - if (gridFSFile == null || gridFSFile.getMetadata() == null) { + if (gridFSFile.getMetadata() == null) { throw new CommonException(ExceptionType.FILE_NOT_FIND); } String fileId = gridFSFile.getFilename(); @@ -366,7 +359,7 @@ public Long recovery(String gridFSId) { @Override public ResponseEntity readHistoryFile(String gridFSId) { GridFSFile gridFSFile = getGridFSFile(gridFSId); - if (gridFSFile == null || gridFSFile.getMetadata() == null) { + if (gridFSFile.getMetadata() == null) { return ResponseEntity.notFound().build(); } try (InputStream inputStream = getInputStream(gridFSFile)) { diff --git a/src/main/java/com/jmal/clouddisk/webdav/BasicAuthenticator.java b/src/main/java/com/jmal/clouddisk/webdav/BasicAuthenticator.java index f5846488..a0a3cdc3 100644 --- a/src/main/java/com/jmal/clouddisk/webdav/BasicAuthenticator.java +++ b/src/main/java/com/jmal/clouddisk/webdav/BasicAuthenticator.java @@ -26,7 +26,6 @@ public class BasicAuthenticator extends AuthenticatorBase { private Charset charset = StandardCharsets.ISO_8859_1; private String charsetString = null; - private boolean trimCredentials = true; private final FileProperties fileProperties; @@ -50,6 +49,7 @@ public void setCharset(String charsetString) { public boolean getTrimCredentials() { + boolean trimCredentials = true; return trimCredentials; } From a53575cd343bf0b5b0c84ed720222ee125b730c7 Mon Sep 17 00:00:00 2001 From: jmal Date: Sat, 7 Dec 2024 18:55:40 +0800 Subject: [PATCH 5/5] refactor: Optimize code --- .../java/com/jmal/clouddisk/webdav/BasicAuthenticator.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/com/jmal/clouddisk/webdav/BasicAuthenticator.java b/src/main/java/com/jmal/clouddisk/webdav/BasicAuthenticator.java index a0a3cdc3..a4b39f58 100644 --- a/src/main/java/com/jmal/clouddisk/webdav/BasicAuthenticator.java +++ b/src/main/java/com/jmal/clouddisk/webdav/BasicAuthenticator.java @@ -49,8 +49,7 @@ public void setCharset(String charsetString) { public boolean getTrimCredentials() { - boolean trimCredentials = true; - return trimCredentials; + return true; }