Skip to content

Commit 950f477

Browse files
committed
fix:codeql scan Security issue
1 parent 23f513f commit 950f477

1 file changed

Lines changed: 92 additions & 56 deletions

File tree

‎app/src/main/java/com/tinyengine/it/task/DatabaseCleanupService.java‎

Lines changed: 92 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -69,10 +69,6 @@ public class DatabaseCleanupService {
6969
"t_page_history",
7070
"t_page_template");
7171

72-
public DatabaseCleanupService() {
73-
// Required for Spring field injection.
74-
}
75-
7672
/** 每天24:00自动执行清空操作 */
7773
@Scheduled(cron = "${cleanup.cron-expression:0 0 0 * * ?}")
7874
public void autoCleanupAtMidnight() {
@@ -81,8 +77,8 @@ public void autoCleanupAtMidnight() {
8177
return;
8278
}
8379

84-
final String executionId = UUID.randomUUID().toString().substring(0, EXEC_ID_LENGTH);
85-
final String startTime = LocalDateTime.now(ZoneId.systemDefault()).format(FORMATTER);
80+
final String executionId = createExecutionId();
81+
final String startTime = currentTime();
8682

8783
logInfo("======= Start executing the database clearing task [{}] =======", executionId);
8884
logInfo("⏰ Time: {}", startTime);
@@ -92,55 +88,20 @@ public void autoCleanupAtMidnight() {
9288
executionStats.put(executionId, stats);
9389
totalExecutions.incrementAndGet();
9490

95-
int successCount = 0;
96-
int failedCount = 0;
97-
long totalRowsCleaned = 0L;
98-
99-
for (String tableName : getWhitelistTables()) {
100-
try {
101-
validateTableName(tableName);
102-
103-
if (!tableExists(tableName)) {
104-
logWarn("⚠️ Table {} does not exist, skip", tableName);
105-
stats.recordSkipped(tableName, "Table does not exist");
106-
continue;
107-
}
108-
109-
final long beforeCount = getTableRecordCount(tableName);
110-
long rowsCleaned;
111-
112-
if (cleanupProperties.isUseTruncate()) {
113-
truncateTable(tableName);
114-
rowsCleaned = beforeCount;
115-
} else {
116-
rowsCleaned = clearTableData(tableName);
117-
}
118-
119-
totalRowsCleaned += rowsCleaned;
120-
successCount++;
121-
122-
logInfo("✅ Table {} cleared: {} records deleted", tableName, rowsCleaned);
123-
stats.recordSuccess(tableName, rowsCleaned);
124-
125-
} catch (DataAccessException | IllegalArgumentException exception) {
126-
failedCount++;
127-
logError(
128-
"❌ Failed to clear table {}: {}",
129-
tableName,
130-
exception.getMessage(),
131-
exception);
132-
stats.recordFailure(tableName, exception.getMessage());
133-
}
91+
final CleanupSummary cleanupSummary = new CleanupSummary();
92+
93+
for (final String tableName : getWhitelistTables()) {
94+
cleanTable(tableName, stats, cleanupSummary);
13495
}
13596

136-
final String endTime = LocalDateTime.now(ZoneId.systemDefault()).format(FORMATTER);
97+
final String endTime = currentTime();
13798
stats.setEndTime(endTime);
138-
stats.setTotalRowsCleaned(totalRowsCleaned);
99+
stats.setTotalRowsCleaned(cleanupSummary.getTotalRowsCleaned());
139100

140101
logInfo("📊 ======= Task Completion Statistics [{}] =======", executionId);
141-
logInfo("✅ Successful table count: {}", successCount);
142-
logInfo("❌ Failure count: {}", failedCount);
143-
logInfo("📈 Total deleted records: {}", totalRowsCleaned);
102+
logInfo("✅ Successful table count: {}", cleanupSummary.getSuccessCount());
103+
logInfo("❌ Failure count: {}", cleanupSummary.getFailedCount());
104+
logInfo("📈 Total deleted records: {}", cleanupSummary.getTotalRowsCleaned());
144105
logInfo("⏰ Time-consuming: {} second", stats.getDurationSeconds());
145106
logInfo("🕐 Start: {}, End: {}", startTime, endTime);
146107
logInfo("🎉 ======= Task execution completed =======\n");
@@ -179,11 +140,61 @@ public void init() {
179140
*
180141
* @return whitelist table names
181142
*/
143+
@SuppressWarnings("PMD.LawOfDemeter")
182144
public List<String> getWhitelistTables() {
183145
final List<String> tables = cleanupProperties.getWhitelistTables();
184146
return tables != null && !tables.isEmpty() ? tables : DEFAULT_TABLES;
185147
}
186148

149+
private static String createExecutionId() {
150+
final UUID executionUuid = UUID.randomUUID();
151+
final String uuidValue = executionUuid.toString();
152+
return uuidValue.substring(0, EXEC_ID_LENGTH);
153+
}
154+
155+
private static String currentTime() {
156+
final ZoneId systemZone = ZoneId.systemDefault();
157+
final LocalDateTime currentDateTime = LocalDateTime.now(systemZone);
158+
return currentDateTime.format(FORMATTER);
159+
}
160+
161+
private void cleanTable(
162+
final String tableName,
163+
final ExecutionStats stats,
164+
final CleanupSummary cleanupSummary) {
165+
try {
166+
validateTableName(tableName);
167+
if (!tableExists(tableName)) {
168+
logWarn("⚠️ Table {} does not exist, skip", tableName);
169+
stats.recordSkipped(tableName, "Table does not exist");
170+
return;
171+
}
172+
173+
final long rowsCleaned = clearTable(tableName);
174+
cleanupSummary.recordSuccess(rowsCleaned);
175+
logInfo("✅ Table {} cleared: {} records deleted", tableName, rowsCleaned);
176+
stats.recordSuccess(tableName, rowsCleaned);
177+
} catch (DataAccessException | IllegalArgumentException exception) {
178+
cleanupSummary.recordFailure();
179+
logError(
180+
"❌ Failed to clear table {}: {}",
181+
tableName,
182+
exception.getMessage(),
183+
exception);
184+
stats.recordFailure(tableName, exception.getMessage());
185+
}
186+
}
187+
188+
private long clearTable(final String tableName) {
189+
if (!cleanupProperties.isUseTruncate()) {
190+
return clearTableData(tableName);
191+
}
192+
193+
final long recordCount = getTableRecordCount(tableName);
194+
truncateTable(tableName);
195+
return recordCount;
196+
}
197+
187198
/**
188199
* 清空表数据(DELETE方式).
189200
*
@@ -208,18 +219,17 @@ private void truncateTable(final String tableName) {
208219
* @return whether the table exists
209220
*/
210221
public boolean tableExists(final String tableName) {
211-
boolean tableExists = false;
212222
try {
213223
final String sql =
214224
"SELECT COUNT(*) FROM information_schema.tables "
215225
+ "WHERE table_schema = DATABASE() AND table_name = ?";
216226
final Integer count =
217227
jdbcTemplate.queryForObject(sql, Integer.class, tableName.toUpperCase(Locale.ROOT));
218-
tableExists = count != null && count > 0;
228+
return count != null && count > 0;
219229
} catch (DataAccessException | IllegalArgumentException exception) {
220230
logWarn("The checklist has failed: {}", exception.getMessage());
231+
return false;
221232
}
222-
return tableExists;
223233
}
224234

225235
/**
@@ -228,16 +238,15 @@ public boolean tableExists(final String tableName) {
228238
* @return record count in the table
229239
*/
230240
public long getTableRecordCount(final String tableName) {
231-
long recordCount = -1;
232241
try {
233242
validateTableName(tableName);
234243
final String sql = "SELECT COUNT(*) FROM " + tableName;
235244
final Long count = jdbcTemplate.queryForObject(sql, Long.class);
236-
recordCount = count != null ? count : 0;
245+
return count != null ? count : 0;
237246
} catch (DataAccessException | IllegalArgumentException exception) {
238247
logError("获取表记录数失败: {}", exception.getMessage());
248+
return -1;
239249
}
240-
return recordCount;
241250
}
242251

243252
/** 验证表名安全性 */
@@ -281,6 +290,33 @@ private static void logError(final String message, final Object... arguments) {
281290
}
282291
}
283292

293+
private static final class CleanupSummary {
294+
private int successCount;
295+
private int failedCount;
296+
private long totalRowsCleaned;
297+
298+
private void recordSuccess(final long rowsCleaned) {
299+
successCount++;
300+
totalRowsCleaned += rowsCleaned;
301+
}
302+
303+
private void recordFailure() {
304+
failedCount++;
305+
}
306+
307+
private int getSuccessCount() {
308+
return successCount;
309+
}
310+
311+
private int getFailedCount() {
312+
return failedCount;
313+
}
314+
315+
private long getTotalRowsCleaned() {
316+
return totalRowsCleaned;
317+
}
318+
}
319+
284320
/** 执行统计内部类 */
285321
public static class ExecutionStats {
286322
private final String executionId;

0 commit comments

Comments
 (0)