CountSegment implements Segment { @Override public String createToken(final String prefix, final Timestamp timestamp) { int separator = Math.max(prefix.lastIndexOf(File.separatorChar), prefix.lastIndexOf('/')); File directory; String filePrefix; if (separator == -1) { directory = new File("").getAbsoluteFile(); filePrefix = prefix; } else { directory = new File(prefix.substring(0, separator)); filePrefix = separator == prefix.length() - 1 ? "" : prefix.substring(separator + 1); } if (directory.isDirectory()) { String[] entries = directory.list(); if (entries != null) { for (String entry : entries) { if (entry.startsWith(filePrefix)) { Long foundCount = parseDigits(entry, filePrefix.length()); if (foundCount != null && foundCount + 1 > count) { count = foundCount + 1; } } } } } return Long.toString(count++); } CountSegment(); @Override String getStaticText(); @Override String createToken(final String prefix, final Timestamp timestamp); @Override boolean validateToken(final String token);  }
@Test public void createTokenForNonExistentFolder() { CountSegment segment = new CountSegment(); String prefix = folder.getRoot() + File.separator + "test" + File.separator; assertThat(segment.createToken(prefix, null)).isEqualTo("0"); }
@Test public void createTokenForEmptyFolder() throws IOException { CountSegment segment = new CountSegment(); String prefix = folder.newFolder().getAbsolutePath() + File.separator; assertThat(segment.createToken(prefix, null)).isEqualTo("0"); }
@Test public void createTokenForExistentFiles() throws IOException { folder.newFile("10"); folder.newFile("11"); folder.newFile("9"); CountSegment segment = new CountSegment(); String prefix = folder.getRoot().getAbsolutePath() + File.separator; assertThat(segment.createToken(prefix, null)).isEqualTo("12"); }
@Test public void createTokenForRealFiles() throws IOException { folder.newFile("test10.log"); folder.newFile("test11.log"); folder.newFile("test9.log"); folder.newFile("testA.log"); folder.newFile("other42.log"); CountSegment segment = new CountSegment(); String prefix = folder.getRoot().getAbsolutePath() + File.separator + "test"; assertThat(segment.createToken(prefix, null)).isEqualTo("12"); }
@Test public void createTokenForInvalidFiles() throws IOException { folder.newFile("abc"); folder.newFile("test"); CountSegment segment = new CountSegment(); String prefix = folder.getRoot().getAbsolutePath() + File.separator; assertThat(segment.createToken(prefix, null)).isEqualTo("0"); }
@Test public void createTokenInCurrentPath() throws IOException { File file = new File("41.tmp"); try { file.createNewFile(); CountSegment segment = new CountSegment(); assertThat(segment.createToken("", null)).isEqualTo("42"); } finally { file.delete(); } }