Skip to content

Commit 639829a

Browse files
mashhursmergify[bot]
authored andcommitted
DeadLetterQueueUtils#extractSegmentId improvement: replace split with index of and substring methods. (#18874)
* DeadLetterQueueUtils: avoid using heavy split operation, replace it with simple index of and substring methods. * Handle exception case if file name doesn't end with .log. Add unit test cases. (cherry picked from commit 8d7a5a3)
1 parent 817ee46 commit 639829a

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

logstash-core/src/main/java/org/logstash/common/io/DeadLetterQueueUtils.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,13 @@ class DeadLetterQueueUtils {
3737

3838
private static final Logger logger = LogManager.getLogger(DeadLetterQueueUtils.class);
3939

40-
static int extractSegmentId(Path p) {
41-
return Integer.parseInt(p.getFileName().toString().split("\\.log")[0]);
40+
static int extractSegmentId(final Path p) {
41+
final String fileName = p.getFileName().toString();
42+
final int dotIndex = fileName.indexOf(".log");
43+
if (dotIndex <= 0) {
44+
throw new IllegalArgumentException("Invalid segment file name: " + fileName);
45+
}
46+
return Integer.parseInt(fileName.substring(0, dotIndex));
4247
}
4348

4449
static Stream<Path> listFiles(Path path, String suffix) throws IOException {

logstash-core/src/test/java/org/logstash/common/io/DeadLetterQueueReaderTest.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1124,4 +1124,26 @@ public void testReaderLockProhibitMultipleInstances() throws IOException {
11241124
}
11251125
}
11261126
}
1127+
1128+
@Test
1129+
public void testExtractSegmentIdWithValidFileName() {
1130+
Path validPath = Paths.get("123.log");
1131+
assertEquals(123, DeadLetterQueueUtils.extractSegmentId(validPath));
1132+
1133+
Path singleDigitPath = Paths.get("1.log");
1134+
assertEquals(1, DeadLetterQueueUtils.extractSegmentId(singleDigitPath));
1135+
1136+
Path largeNumberPath = Paths.get("999999.log");
1137+
assertEquals(999999, DeadLetterQueueUtils.extractSegmentId(largeNumberPath));
1138+
}
1139+
1140+
@Test
1141+
public void testExtractSegmentIdWithNoLogExtensionThrowsException() {
1142+
Path noExtensionPath = Paths.get("123.txt");
1143+
IllegalArgumentException exception = Assert.assertThrows(
1144+
IllegalArgumentException.class,
1145+
() -> DeadLetterQueueUtils.extractSegmentId(noExtensionPath)
1146+
);
1147+
assertThat(exception.getMessage(), containsString("Invalid segment file name"));
1148+
}
11271149
}

0 commit comments

Comments
 (0)