diff --git a/logstash-core/src/main/java/org/logstash/common/io/DeadLetterQueueUtils.java b/logstash-core/src/main/java/org/logstash/common/io/DeadLetterQueueUtils.java index 31e9d564426..06a6a507462 100644 --- a/logstash-core/src/main/java/org/logstash/common/io/DeadLetterQueueUtils.java +++ b/logstash-core/src/main/java/org/logstash/common/io/DeadLetterQueueUtils.java @@ -37,8 +37,13 @@ class DeadLetterQueueUtils { private static final Logger logger = LogManager.getLogger(DeadLetterQueueUtils.class); - static int extractSegmentId(Path p) { - return Integer.parseInt(p.getFileName().toString().split("\\.log")[0]); + static int extractSegmentId(final Path p) { + final String fileName = p.getFileName().toString(); + final int dotIndex = fileName.indexOf(".log"); + if (dotIndex <= 0) { + throw new IllegalArgumentException("Invalid segment file name: " + fileName); + } + return Integer.parseInt(fileName.substring(0, dotIndex)); } static Stream listFiles(Path path, String suffix) throws IOException { diff --git a/logstash-core/src/test/java/org/logstash/common/io/DeadLetterQueueReaderTest.java b/logstash-core/src/test/java/org/logstash/common/io/DeadLetterQueueReaderTest.java index d6b2365a783..adcad9050b6 100644 --- a/logstash-core/src/test/java/org/logstash/common/io/DeadLetterQueueReaderTest.java +++ b/logstash-core/src/test/java/org/logstash/common/io/DeadLetterQueueReaderTest.java @@ -1124,4 +1124,26 @@ public void testReaderLockProhibitMultipleInstances() throws IOException { } } } + + @Test + public void testExtractSegmentIdWithValidFileName() { + Path validPath = Paths.get("123.log"); + assertEquals(123, DeadLetterQueueUtils.extractSegmentId(validPath)); + + Path singleDigitPath = Paths.get("1.log"); + assertEquals(1, DeadLetterQueueUtils.extractSegmentId(singleDigitPath)); + + Path largeNumberPath = Paths.get("999999.log"); + assertEquals(999999, DeadLetterQueueUtils.extractSegmentId(largeNumberPath)); + } + + @Test + public void testExtractSegmentIdWithNoLogExtensionThrowsException() { + Path noExtensionPath = Paths.get("123.txt"); + IllegalArgumentException exception = Assert.assertThrows( + IllegalArgumentException.class, + () -> DeadLetterQueueUtils.extractSegmentId(noExtensionPath) + ); + assertThat(exception.getMessage(), containsString("Invalid segment file name")); + } }