src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
RemoveSingleImageSetStage implements Function<Multimap<Long, ImageRecord>, Multimap<Long, ImageRecord>> { @Override public Multimap<Long, ImageRecord> apply(Multimap<Long, ImageRecord> toPrune) { DuplicateUtil.removeSingleImageGroups(toPrune); return toPrune; } @Override Multimap<Long, ImageRecord> apply(Multimap<Long, ImageRecord> toPrune); }
@Test public void testRemoveSingleImageGroup() throws Exception { cut.apply(testMap); assertThat(testMap.containsKey(HASH_A), is(false)); } @Test public void testParameterReturned() throws Exception { assertThat(cut.apply(testMap), is(sameInstance(testMap))); }
GroupImagesStage implements Function<Collection<ImageRecord>, Multimap<Long, ImageRecord>> { @Override public Multimap<Long, ImageRecord> apply(Collection<ImageRecord> toGroup) { Multimap<Long, ImageRecord> resultMap = MultimapBuilder.hashKeys().hashSetValues().build(); rs.build(toGroup); Stopwatch sw = Stopwatch.createStarted(); toGroup.forEach(new Consumer<ImageRecord>() { @Override public void accept(ImageRecord t) { resultMap.putAll(t.getpHash(), rs.distanceMatch(t.getpHash(), hammingDistance).values()); } }); LOGGER.info("Built result map with {} pairs in {}, using hamming distance {}", resultMap.size(), sw, hammingDistance); return resultMap; } GroupImagesStage(); GroupImagesStage(int hammingDistance); @Override Multimap<Long, ImageRecord> apply(Collection<ImageRecord> toGroup); int getHammingDistance(); }
@Test public void testNoDuplicatesInGroup() throws Exception { assertThat(cut.apply(images).get(HASH_B), hasSize(1)); } @Test public void testSortedByHash() throws Exception { assertThat(cut.apply(images).get(HASH_A), hasItem(imageA)); } @Test public void testHammingDistance() throws Exception { cut = new GroupImagesStage(1); assertThat(cut.apply(images).get(HASH_B), hasItems(imageA, imageB)); }
HashAttribute { public void writeHash(Path path, long hash) { try { ExtendedAttribute.setExtendedAttribute(path, hashFQN, Long.toHexString(hash)); ExtendedAttribute.setExtendedAttribute(path, timestampFQN, Long.toString(Files.getLastModifiedTime(path).toMillis())); } catch (IOException e) { LOGGER.warn("Failed to write hash to file {} ({})", path, e.toString()); } } HashAttribute(String hashName); boolean areAttributesValid(Path path); long readHash(Path path); void writeHash(Path path, long hash); void markCorrupted(Path path); boolean isCorrupted(Path path); String getHashFQN(); String getTimestampFQN(); String getCorruptNameFQN(); }
@Test public void testWrittenHashValue() throws Exception { cut.writeHash(tempFile, TEST_VALUE); assertThat(Long.parseUnsignedLong(ExtendedAttribute.readExtendedAttributeAsString(tempFile, testHashFullName), HEXADECIMAL_RADIX), is(TEST_VALUE)); } @Test public void testWrittenTimeStamp() throws Exception { cut.writeHash(tempFile, TEST_VALUE); long timestamp = Files.getLastModifiedTime(tempFile).toMillis(); assertThat(Long.parseUnsignedLong(ExtendedAttribute.readExtendedAttributeAsString(tempFile, timestampFullName)), is(allOf(greaterThan(timestamp - TIMESTAMP_TOLERANCE), lessThan(timestamp + TIMESTAMP_TOLERANCE)))); }
DCTKernel extends Kernel { public synchronized double[] transformDCT(double[] matrix) { for (int i = 0; i < matrixArea; i++) { this.matrix[i] = matrix[i]; } execute(range); return Doubles.concat(result); } DCTKernel(); DCTKernel(int matrixSize); void setDevice(Device device); @Override void run(); synchronized double[] transformDCT(double[] matrix); static final int DEFAULT_MATRIX_SIZE; }
@Test public void testTransformDCT() throws Exception { double[] result = cut.transformDCT(Doubles.concat(testMatrix)); assertArrayEquals(EXPECTED, Doubles.concat(result), 0.1); } @Test public void testTransformDCT2() throws Exception { double[] result = cut.transformDCT(Doubles.concat(testMatrix2)); assertArrayEquals(EXPECTED2, Doubles.concat(result), 0.1); }
GroupImagesStage implements Function<Collection<ImageRecord>, Multimap<Long, ImageRecord>> { public int getHammingDistance() { return hammingDistance; } GroupImagesStage(); GroupImagesStage(int hammingDistance); @Override Multimap<Long, ImageRecord> apply(Collection<ImageRecord> toGroup); int getHammingDistance(); }
@Test public void testGetHammingDistance() throws Exception { cut = new GroupImagesStage(DISTANCE); assertThat(cut.getHammingDistance(), is(DISTANCE)); } @Test public void testDefaultDistance() throws Exception { assertThat(cut.getHammingDistance(), is(0)); }
GroupListPopulator implements Runnable { @Override public void run() { this.logger.info("Populating group list with {} groups", groups.groupCount()); groupListModel.clear(); List<ResultGroup> resultGroups = groups.getAllGroups(); Collections.sort(resultGroups, new Comparator<ResultGroup>() { @Override public int compare(ResultGroup o1, ResultGroup o2) { return Long.compare(o1.getHash(), o2.getHash()); } }); for (ResultGroup g : resultGroups) { groupListModel.addElement(g); } this.logger.info("Finished populating group list"); } GroupListPopulator(GroupList groups, DefaultListModel<ResultGroup> groupListModel); @Override void run(); }
@Test public void testElementsAddedInOrder() { glp.run(); List<ResultGroup> testList = Lists.reverse(results); InOrder inOrder = inOrder(dlm); for (ResultGroup rg : testList) { inOrder.verify(dlm).addElement(rg); } } @Test public void testElementsAdded() { glp.run(); for (ResultGroup rg : results) { verify(dlm).addElement(rg); } }
TagFilter { public Multimap<Long, ImageRecord> getFilterMatches(RecordSearch recordSearch, Tag tagToMatch, int hammingDistance) { Multimap<Long, ImageRecord> uniqueGroups = MultimapBuilder.hashKeys().hashSetValues().build(); List<FilterRecord> matchingFilters = Collections.emptyList(); try { matchingFilters = FilterRecord.getTags(filterRepository, tagToMatch); LOGGER.info("Found {} filters for tag {}", matchingFilters.size(), tagToMatch.getTag()); } catch (RepositoryException e) { LOGGER.error("Failed to query hashes for tag {}, reason: {}, cause: {}", tagToMatch.getTag(), e.toString(), e.getCause()); } Multimap<Long, ImageRecord> parallelGroups = Multimaps.synchronizedMultimap(uniqueGroups); matchingFilters.parallelStream().forEach(filter -> { Multimap<Long, ImageRecord> match = recordSearch.distanceMatch(filter.getpHash(), hammingDistance); parallelGroups.putAll(filter.getpHash(), match.values()); }); return uniqueGroups; } TagFilter(FilterRepository filterRepository); Multimap<Long, ImageRecord> getFilterMatches(RecordSearch recordSearch, Tag tagToMatch, int hammingDistance); }
@Test public void testRepositoryException() throws Exception { when(filterRepository.getAll()).thenThrow(new RepositoryException("just testing!")); assertThat(cut.getFilterMatches(recordSearch, TAG_ALL, DISTANCE), is(emptyMultimap)); } @Test public void testMatchingTag() throws Exception { assertThat(cut.getFilterMatches(recordSearch, TAG, DISTANCE).get(1L), hasItem(image1)); } @Test public void testMatchingTagSecondImageNotIncluded() throws Exception { assertThat(cut.getFilterMatches(recordSearch, TAG, DISTANCE).get(1L), not(hasItem(image2))); }
NamedThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { Thread thread = defaultThreadFactory.newThread(r); thread.setName(threadPrefix + " thread " + threadNumber); threadNumber++; return thread; } NamedThreadFactory(String threadPrefix); @Override Thread newThread(Runnable r); }
@Test public void testNewThread() throws Exception { Thread t = ntf.newThread(runnableMock); assertThat(t.getName(), is("test thread 0")); } @Test public void testNewThreadTwo() throws Exception { ntf.newThread(runnableMock); Thread t2 = ntf.newThread(runnableMock); assertThat(t2.getName(), is("test thread 1")); }
ImageFindJobVisitor extends SimpleFileVisitor<Path> { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (isAcceptedFile(file)) { statistics.incrementFoundFiles(); fileCount++; boolean isHandled = false; for (HashHandler handler : handlers) { if (handler.handle(file)) { isHandled = true; break; } } statistics.incrementProcessedFiles(); if (!isHandled) { statistics.incrementFailedFiles(); LOGGER.error("No handler was able to process {}", file); } } return FileVisitResult.CONTINUE; } ImageFindJobVisitor(Filter<Path> fileFilter, Collection<HashHandler> handlers, Statistics statistics); @Override FileVisitResult visitFile(Path file, BasicFileAttributes attrs); @Deprecated int getFileCount(); }
@Test public void testVisitFileOkProcessedFiles() throws Exception { cut.visitFile(path, attrs); assertThat(statistics.getProcessedFiles(), is(1)); } @Test public void testVisitFileOkFailedFiles() throws Exception { cut.visitFile(path, attrs); assertThat(statistics.getFailedFiles(), is(0)); } @Test public void testVisitNotHandled() throws Exception { when(handler.handle(path)).thenReturn(false); cut.visitFile(path, attrs); assertThat(statistics.getFailedFiles(), is(1)); }
ImageFindJobVisitor extends SimpleFileVisitor<Path> { @Deprecated public int getFileCount() { return fileCount; } ImageFindJobVisitor(Filter<Path> fileFilter, Collection<HashHandler> handlers, Statistics statistics); @Override FileVisitResult visitFile(Path file, BasicFileAttributes attrs); @Deprecated int getFileCount(); }
@Test public void testGetFileCount() throws Exception { cut.visitFile(path, attrs); assertThat(cut.getFileCount(), is(1)); }
ImageHashJob implements Runnable { @Override public void run() { try { long hash = processFile(image); if (hashAttribute != null) { hashAttribute.writeHash(image, hash); } } catch (IIOException e) { LOGGER.warn("Failed to process image {} (IIO Error): {}", image, e.toString()); LOGGER.debug(EXCEPTION_STACKTRACE, image, e); statistics.incrementFailedFiles(); } catch (IOException e) { LOGGER.warn("Failed to load file {}: {}", image, e.toString()); statistics.incrementFailedFiles(); } catch (RepositoryException e) { LOGGER.warn("Failed to query repository for {}: {}", image, e.toString()); statistics.incrementFailedFiles(); } catch (ArrayIndexOutOfBoundsException e) { LOGGER.error("Failed to process image {}: {}", image, e.toString()); LOGGER.debug(EXCEPTION_STACKTRACE, image, e); statistics.incrementFailedFiles(); } } ImageHashJob(Path image, ImagePHash hasher, ImageRepository imageRepository, Statistics statistics); final void setHashAttribute(HashAttribute hashAttribute); @Override void run(); }
@Test public void testRunAddFile() throws Exception { imageLoadJob.run(); verify(imageRepository).store(new ImageRecord(testImage.toString(), 0)); } @Test public void testRunIIOException() throws Exception { when(phw.getLongHash(any(InputStream.class))).thenThrow(IIOException.class); imageLoadJob.run(); verify(statistics).incrementFailedFiles(); }
DuplicateUtil { public static Multimap<Long, ImageRecord> groupByHash(Collection<ImageRecord> dbRecords) { Multimap<Long, ImageRecord> groupedByHash = MultimapBuilder.hashKeys().hashSetValues().build(); logger.info("Grouping records by hash..."); for (ImageRecord ir : dbRecords) { groupedByHash.put(ir.getpHash(), ir); } logger.info("{} records, in {} groups", dbRecords.size(), groupedByHash.keySet().size()); return groupedByHash; } static Multimap<Long, ImageRecord> groupByHash(Collection<ImageRecord> dbRecords); static void removeSingleImageGroups(Multimap<Long, ImageRecord> sourceGroups); static void removeDuplicateSets(Multimap<Long, ImageRecord> records); }
@Test public void testGroupByHashNumberOfGroups() throws Exception { Multimap<Long, ImageRecord> group = DuplicateUtil.groupByHash(records); assertThat(group.keySet().size(), is(10)); } @Test public void testGroupByHashSizeOfGroup() throws Exception { Multimap<Long, ImageRecord> group = DuplicateUtil.groupByHash(records); assertThat(group.get(5L).size(), is(3)); } @Test public void testGroupByHashEntryPath() throws Exception { Multimap<Long, ImageRecord> group = DuplicateUtil.groupByHash(records); assertThat(group.get(2L), hasItem(new ImageRecord("foo", 2L))); }
DuplicateUtil { public static void removeDuplicateSets(Multimap<Long, ImageRecord> records) { logger.info("Checking {} groups for duplicates", records.keySet().size()); Stopwatch sw = Stopwatch.createStarted(); Set<Collection<ImageRecord>> uniqueRecords = new HashSet<Collection<ImageRecord>>(records.keySet().size()); Iterator<Collection<ImageRecord>> recordIter = records.asMap().values().iterator(); long removedGroups = 0; while (recordIter.hasNext()) { Collection<ImageRecord> next = recordIter.next(); if (!uniqueRecords.add(next)) { recordIter.remove(); removedGroups++; } } logger.info("Checked groups in {}, removed {} identical groups", sw, removedGroups); } static Multimap<Long, ImageRecord> groupByHash(Collection<ImageRecord> dbRecords); static void removeSingleImageGroups(Multimap<Long, ImageRecord> sourceGroups); static void removeDuplicateSets(Multimap<Long, ImageRecord> records); }
@Test public void testRemoveDuplicateSetsIdenticalSets() throws Exception { Multimap<Long, ImageRecord> map = MultimapBuilder.hashKeys().hashSetValues().build(); map.putAll(1L, records); map.putAll(2L, records); DuplicateUtil.removeDuplicateSets(map); assertThat(map.keySet().size(), is(1)); } @Test public void testRemoveDuplicateSetsNonIdenticalSets() throws Exception { Multimap<Long, ImageRecord> map = MultimapBuilder.hashKeys().hashSetValues().build(); map.putAll(1L, records); map.putAll(2L, records); map.put(2L, new ImageRecord("foo", 1L)); DuplicateUtil.removeDuplicateSets(map); assertThat(map.keySet().size(), is(2)); }
HashAttribute { public boolean areAttributesValid(Path path) { try { return ExtendedAttribute.isExtendedAttributeSet(path, hashFQN) && verifyTimestamp(path); } catch (IOException e) { LOGGER.error("Failed to check hash for {} ({})", path, e.toString()); } return false; } HashAttribute(String hashName); boolean areAttributesValid(Path path); long readHash(Path path); void writeHash(Path path, long hash); void markCorrupted(Path path); boolean isCorrupted(Path path); String getHashFQN(); String getTimestampFQN(); String getCorruptNameFQN(); }
@Test public void testAreAttributesValidNoHashOrTimestamp() throws Exception { assertThat(cut.areAttributesValid(tempFile), is(false)); } @Test public void testAreAttributesValidHashButNoTimestamp() throws Exception { ExtendedAttribute.setExtendedAttribute(tempFile, testHashFullName, Long.toString(TEST_VALUE)); assertThat(cut.areAttributesValid(tempFile), is(false)); } @Test public void testAreAttributesValidHashAndModifiedFile() throws Exception { ExtendedAttribute.setExtendedAttribute(tempFile, testHashFullName, Long.toString(TEST_VALUE)); long timestamp = Files.getLastModifiedTime(tempFile).toMillis(); timestamp += TimeUnit.MILLISECONDS.convert(1, TimeUnit.HOURS); ExtendedAttribute.setExtendedAttribute(tempFile, timestampFullName, Long.toString(timestamp)); assertThat(cut.areAttributesValid(tempFile), is(false)); } @Test public void testAreAttributesValidHashAndTimestampBefore() throws Exception { ExtendedAttribute.setExtendedAttribute(tempFile, testHashFullName, Long.toString(TEST_VALUE)); long timestamp = Files.getLastModifiedTime(tempFile).toMillis(); timestamp -= TimeUnit.MILLISECONDS.convert(1, TimeUnit.HOURS); ExtendedAttribute.setExtendedAttribute(tempFile, timestampFullName, Long.toString(timestamp)); assertThat(cut.areAttributesValid(tempFile), is(false)); } @Test public void testAreAttributesValidHashAndTimestampOK() throws Exception { ExtendedAttribute.setExtendedAttribute(tempFile, testHashFullName, Long.toString(TEST_VALUE)); long timestamp = Files.getLastModifiedTime(tempFile).toMillis(); ExtendedAttribute.setExtendedAttribute(tempFile, timestampFullName, Long.toString(timestamp)); assertThat(cut.areAttributesValid(tempFile), is(true)); }
DuplicateUtil { protected static final BigInteger hashSum(Collection<Long> hashes) { BigInteger hashSum = BigInteger.ZERO; for (Long hash : hashes) { hashSum = hashSum.add(BigInteger.valueOf(hash)); } return hashSum; } static Multimap<Long, ImageRecord> groupByHash(Collection<ImageRecord> dbRecords); static void removeSingleImageGroups(Multimap<Long, ImageRecord> sourceGroups); static void removeDuplicateSets(Multimap<Long, ImageRecord> records); }
@Test public void testHashSumNoHashes() throws Exception { assertThat(DuplicateUtil.hashSum(Collections.emptyList()), is(BigInteger.ZERO)); } @Test public void testHashSum() throws Exception { List<Long> hashes = new LinkedList<Long>(); hashes.add(2L); hashes.add(3L); assertThat(DuplicateUtil.hashSum(hashes), is(new BigInteger("5"))); }
ImageRecordComperator implements Comparator<ImageRecord>, Serializable { @Override public int compare(ImageRecord o1, ImageRecord o2) { long l1 = o1.getpHash(); long l2 = o2.getpHash(); if (l1 < l2) { return -1; } else if (l1 == l2) { return 0; } else { return 1; } } @Override int compare(ImageRecord o1, ImageRecord o2); }
@Test public void testCompareEqual() throws Exception { assertThat(irc.compare(a, new ImageRecord("", 1L)), is(0)); } @Test public void testCompareLess() throws Exception { assertThat(irc.compare(a, b), is(-1)); } @Test public void testCompareLessLargerNumber() throws Exception { assertThat(irc.compare(a, c), is(-1)); } @Test public void testCompareGreater() throws Exception { assertThat(irc.compare(b, a), is(1)); } @Test public void testCompareGreaterLargerNumber() throws Exception { assertThat(irc.compare(c, a), is(1)); } @Test(expected = NullPointerException.class) public void testCompareFirstNull() throws Exception { irc.compare(null, b); } @Test(expected = NullPointerException.class) public void testCompareSecondNull() throws Exception { irc.compare(a, null); } @Test(expected = NullPointerException.class) public void testCompareBothNull() throws Exception { irc.compare(null, null); }
RecordSearch { public Multimap<Long, ImageRecord> distanceMatch(long hash, long hammingDistance) { Multimap<Long, ImageRecord> searchResult = MultimapBuilder.hashKeys().hashSetValues().build(); Set<Long> resultKeys = bkTree.searchWithin(hash, (double) hammingDistance); for (Long key : resultKeys) { searchResult.putAll(key, imagesGroupedByHash.get(key)); } return searchResult; } RecordSearch(); void build(Collection<ImageRecord> dbRecords); List<Long> exactMatch(); Multimap<Long, ImageRecord> distanceMatch(long hash, long hammingDistance); }
@Test public void testDistanceMatchRadius0Size() throws Exception { Multimap<Long, ImageRecord> result = cut.distanceMatch(2L, 0L); assertThat(result.keySet().size(), is(1)); } @Test public void testDistanceMatchRadius0Hash() throws Exception { Multimap<Long, ImageRecord> result = cut.distanceMatch(2L, 0L); assertThat(result.get(2L).size(), is(2)); } @Test public void testDistanceMatchRadius1Size() throws Exception { Multimap<Long, ImageRecord> result = cut.distanceMatch(2L, 1L); assertThat(result.keySet().size(), is(3)); } @Test public void testDistanceMatchRadius1Hash2() throws Exception { Multimap<Long, ImageRecord> result = cut.distanceMatch(2L, 1L); assertThat(result.containsKey(2L), is(true)); } @Test public void testDistanceMatchRadius1Hash3() throws Exception { Multimap<Long, ImageRecord> result = cut.distanceMatch(2L, 1L); assertThat(result.containsKey(3L), is(true)); } @Test public void testDistanceMatchRadius1Hash6() throws Exception { Multimap<Long, ImageRecord> result = cut.distanceMatch(2L, 1L); assertThat(result.containsKey(6L), is(true)); } @Test public void testDistanceMatchRadius2Size() throws Exception { Multimap<Long, ImageRecord> result = cut.distanceMatch(2L, 2L); assertThat(result.keySet().size(), is(4)); } @Test public void testDistanceMatchRadius2Hash1() throws Exception { Multimap<Long, ImageRecord> result = cut.distanceMatch(2L, 2L); assertThat(result.containsKey(1L), is(true)); }
DuplicateOperations { public void moveToDnw(Path path) { logger.info("Method not implemented"); } @Inject DuplicateOperations(FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); DuplicateOperations(FileSystem fileSystem, FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); void moveToDnw(Path path); void deleteAll(Collection<Result> records); void remove(Collection<ImageRecord> records); void deleteFile(Result result); void deleteFile(Path path); void markAll(Collection<Result> records, Tag tag); void markDnwAndDelete(Collection<Result> records); void markAs(Result result, Tag tag); void markAs(Path path, Tag tag); void markAs(ImageRecord image, Tag tag); void markDirectoryAs(Path directory, Tag tag); void markDirectoryAndChildrenAs(Path rootDirectory, Tag tag); List<ImageRecord> findMissingFiles(Path directory); void ignore(Result result); List<Tag> getFilterTags(); }
@Ignore("Not implemented yet") @Test public void testMoveToDnw() throws Exception { List<Path> files = createTempTestFiles(1); Path file = files.get(0); dupOp.moveToDnw(file); assertThat(Files.exists(file), is(true)); verify(imageRepository).remove(new ImageRecord(file.toString(), TEST_HASH)); verify(filterRepository).store(new FilterRecord(anyLong(), TAG_DNW)); }
DuplicateOperations { public void deleteAll(Collection<Result> records) { for (Result result : records) { deleteFile(result); } } @Inject DuplicateOperations(FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); DuplicateOperations(FileSystem fileSystem, FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); void moveToDnw(Path path); void deleteAll(Collection<Result> records); void remove(Collection<ImageRecord> records); void deleteFile(Result result); void deleteFile(Path path); void markAll(Collection<Result> records, Tag tag); void markDnwAndDelete(Collection<Result> records); void markAs(Result result, Tag tag); void markAs(Path path, Tag tag); void markAs(ImageRecord image, Tag tag); void markDirectoryAs(Path directory, Tag tag); void markDirectoryAndChildrenAs(Path rootDirectory, Tag tag); List<ImageRecord> findMissingFiles(Path directory); void ignore(Result result); List<Tag> getFilterTags(); }
@Test public void testDeleteAll() throws Exception { List<Path> files = createTempTestFiles(10); LinkedList<Result> records = new LinkedList<>(); for (Path p : files) { records.add(new Result(resultGroup, new ImageRecord(p.toString(), 0))); } dupOp.deleteAll(records); assertFilesDoNotExist(files); verify(imageRepository, times(10)).remove(any(ImageRecord.class)); }
DuplicateOperations { public void deleteFile(Result result) { deleteFile(fileSystem.getPath(result.getImageRecord().getPath())); result.remove(); } @Inject DuplicateOperations(FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); DuplicateOperations(FileSystem fileSystem, FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); void moveToDnw(Path path); void deleteAll(Collection<Result> records); void remove(Collection<ImageRecord> records); void deleteFile(Result result); void deleteFile(Path path); void markAll(Collection<Result> records, Tag tag); void markDnwAndDelete(Collection<Result> records); void markAs(Result result, Tag tag); void markAs(Path path, Tag tag); void markAs(ImageRecord image, Tag tag); void markDirectoryAs(Path directory, Tag tag); void markDirectoryAndChildrenAs(Path rootDirectory, Tag tag); List<ImageRecord> findMissingFiles(Path directory); void ignore(Result result); List<Tag> getFilterTags(); }
@Test public void testDeleteFile() throws Exception { List<Path> files = createTempTestFiles(1); Path file = files.get(0); assertThat(GUARD_MSG, Files.exists(file), is(true)); dupOp.deleteFile(file); assertThat(Files.exists(file), is(false)); verify(imageRepository).remove(new ImageRecord(file.toString(), 0)); }
DuplicateOperations { public void markDnwAndDelete(Collection<Result> records) { for (Result result : records) { ImageRecord ir = result.getImageRecord(); Path path = fileSystem.getPath(ir.getPath()); try { markAs(ir, TAG_DNW); deleteFile(result); } catch (RepositoryException e) { logger.warn("Failed to add filter entry for {} - {}", path, e.getMessage()); } } } @Inject DuplicateOperations(FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); DuplicateOperations(FileSystem fileSystem, FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); void moveToDnw(Path path); void deleteAll(Collection<Result> records); void remove(Collection<ImageRecord> records); void deleteFile(Result result); void deleteFile(Path path); void markAll(Collection<Result> records, Tag tag); void markDnwAndDelete(Collection<Result> records); void markAs(Result result, Tag tag); void markAs(Path path, Tag tag); void markAs(ImageRecord image, Tag tag); void markDirectoryAs(Path directory, Tag tag); void markDirectoryAndChildrenAs(Path rootDirectory, Tag tag); List<ImageRecord> findMissingFiles(Path directory); void ignore(Result result); List<Tag> getFilterTags(); }
@Test public void testMarkDnwAndDelete() throws Exception { List<Path> files = createTempTestFiles(RECORD_NUMBER); LinkedList<Result> records = new LinkedList<>(); for (Path p : files) { records.add(new Result(resultGroup, new ImageRecord(p.toString(), 0))); } dupOp.markDnwAndDelete(records); assertFilesDoNotExist(files); ArgumentCaptor<FilterRecord> capture = ArgumentCaptor.forClass(FilterRecord.class); verify(filterRepository, times(RECORD_NUMBER)).store(capture.capture()); verify(imageRepository, times(RECORD_NUMBER)).remove(any(ImageRecord.class)); for (FilterRecord record : capture.getAllValues()) { assertThat(record.getTag(), is(TAG_DNW)); } }
DuplicateOperations { public void markAs(Result result, Tag tag) { try { markAs(result.getImageRecord(), tag); } catch (RepositoryException e) { logger.warn(FILTER_ADD_FAILED_MESSAGE, result.getImageRecord().getPath(), e.getMessage()); } } @Inject DuplicateOperations(FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); DuplicateOperations(FileSystem fileSystem, FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); void moveToDnw(Path path); void deleteAll(Collection<Result> records); void remove(Collection<ImageRecord> records); void deleteFile(Result result); void deleteFile(Path path); void markAll(Collection<Result> records, Tag tag); void markDnwAndDelete(Collection<Result> records); void markAs(Result result, Tag tag); void markAs(Path path, Tag tag); void markAs(ImageRecord image, Tag tag); void markDirectoryAs(Path directory, Tag tag); void markDirectoryAndChildrenAs(Path rootDirectory, Tag tag); List<ImageRecord> findMissingFiles(Path directory); void ignore(Result result); List<Tag> getFilterTags(); }
@Test public void testMarkAsNotInDb() throws Exception { List<Path> files = createTempTestFiles(1); Path file = files.get(0); dupOp.markAs(file, TAG_FOO); verify(imageRepository).getByPath(any(Path.class)); verify(filterRepository, never()).store(any(FilterRecord.class)); } @Test public void testMarkAsNoFilterExists() throws Exception { List<Path> files = createTempTestFiles(1); Path file = files.get(0); when(imageRepository.getByPath(file)).thenReturn(new ImageRecord(file.toString(), TEST_HASH)); dupOp.markAs(file, TAG_FOO); verify(filterRepository).store(fooFilter); } @Test public void testMarkAsDBerror() throws Exception { List<Path> files = createTempTestFiles(1); Path file = files.get(0); when(imageRepository.getByPath(file)).thenThrow(new RepositoryException("This is a test")); dupOp.markAs(file, TAG_FOO); verify(filterRepository, never()).store(any(FilterRecord.class)); } @Test public void testMarkAsFilterExists() throws Exception { List<Path> files = createTempTestFiles(1); Path file = files.get(0); when(imageRepository.getByPath(file)).thenReturn(new ImageRecord(file.toString(), 42)); dupOp.markAs(file, TAG_FOO); verify(filterRepository).store(new FilterRecord(42, TAG_FOO)); }
DuplicateOperations { public void markDirectoryAs(Path directory, Tag tag) { if (!isDirectory(directory)) { logger.warn("Directory {} not valid, aborting.", directory); return; } try { int addCount = 0; Iterator<Path> iter = Files.newDirectoryStream(directory).iterator(); while (iter.hasNext()) { Path current = iter.next(); if (Files.isRegularFile(current)) { markAs(current, tag); addCount++; } } logger.info("Added {} images from {} to filter list", addCount, directory); } catch (IOException e) { logger.error("Failed to add images to filter list, {}", e); } } @Inject DuplicateOperations(FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); DuplicateOperations(FileSystem fileSystem, FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); void moveToDnw(Path path); void deleteAll(Collection<Result> records); void remove(Collection<ImageRecord> records); void deleteFile(Result result); void deleteFile(Path path); void markAll(Collection<Result> records, Tag tag); void markDnwAndDelete(Collection<Result> records); void markAs(Result result, Tag tag); void markAs(Path path, Tag tag); void markAs(ImageRecord image, Tag tag); void markDirectoryAs(Path directory, Tag tag); void markDirectoryAndChildrenAs(Path rootDirectory, Tag tag); List<ImageRecord> findMissingFiles(Path directory); void ignore(Result result); List<Tag> getFilterTags(); }
@Test public void testMarkDirectory() throws Exception { createTempTestFiles(3); dupOp.markDirectoryAs(tempDirectory, TAG_FOO); verify(imageRepository, times(3)).getByPath(any(Path.class)); verify(filterRepository, never()).store(any(FilterRecord.class)); } @Test public void testMarkDirectoryNotAdirectory() throws Exception { List<Path> files = createTempTestFiles(3); Path file = files.get(0); dupOp.markDirectoryAs(file, TAG_FOO); verify(imageRepository, never()).getByPath(any(Path.class)); verify(filterRepository, never()).store(any(FilterRecord.class)); } @Test public void testMarkDirectoryDirectoryIsNull() throws Exception { createTempTestFiles(3); dupOp.markDirectoryAs(null, TAG_FOO); verify(imageRepository, never()).getByPath(any(Path.class)); verify(filterRepository, never()).store(any(FilterRecord.class)); } @Test public void testMarkDirectoryDirectoryNonExistantDirectory() throws Exception { createTempTestFiles(3); dupOp.markDirectoryAs(tempDirectory.resolve("foobar"), TAG_FOO); verify(imageRepository, never()).getByPath(any(Path.class)); verify(filterRepository, never()).store(any(FilterRecord.class)); }
DuplicateOperations { public void markAll(Collection<Result> records, Tag tag) { for (Result result : records) { ImageRecord record = result.getImageRecord(); try { markAs(record, tag); logger.info("Adding pHash {} to filter, tag {}, source file {}", record.getpHash(), tag, record.getPath()); } catch (RepositoryException e) { logger.warn("Failed to add tag for {}: {}", record.getPath(), e.toString()); } } } @Inject DuplicateOperations(FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); DuplicateOperations(FileSystem fileSystem, FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); void moveToDnw(Path path); void deleteAll(Collection<Result> records); void remove(Collection<ImageRecord> records); void deleteFile(Result result); void deleteFile(Path path); void markAll(Collection<Result> records, Tag tag); void markDnwAndDelete(Collection<Result> records); void markAs(Result result, Tag tag); void markAs(Path path, Tag tag); void markAs(ImageRecord image, Tag tag); void markDirectoryAs(Path directory, Tag tag); void markDirectoryAndChildrenAs(Path rootDirectory, Tag tag); List<ImageRecord> findMissingFiles(Path directory); void ignore(Result result); List<Tag> getFilterTags(); }
@Test public void testMarkAll() throws Exception { LinkedList<Result> records = new LinkedList<>(); records.add(new Result(resultGroup, new ImageRecord(TAG_FOO.getTag(), 0))); records.add(new Result(resultGroup, new ImageRecord(TAG_BAR.getTag(), 1))); dupOp.markAll(records, TAG_ALL); verify(filterRepository).store(new FilterRecord(0, TAG_ALL)); verify(filterRepository).store(new FilterRecord(1, TAG_ALL)); }
DuplicateOperations { public List<ImageRecord> findMissingFiles(Path directory) { if (!isDirectory(directory)) { logger.error("Directory is null or missing, aborting"); return Collections.emptyList(); } if (!Files.exists(directory)) { logger.warn("Directory {} does not exist.", directory); } List<ImageRecord> records = Collections.emptyList(); try { records = imageRepository.startsWithPath(directory); } catch (RepositoryException e) { logger.error("Failed to get records from database: {}", e.toString()); } LinkedList<ImageRecord> toPrune = new LinkedList<>(); for (ImageRecord ir : records) { Path path = fileSystem.getPath(ir.getPath()); if (!Files.exists(path)) { toPrune.add(ir); } } logger.info("Found {} non-existant records", toPrune.size()); return toPrune; } @Inject DuplicateOperations(FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); DuplicateOperations(FileSystem fileSystem, FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); void moveToDnw(Path path); void deleteAll(Collection<Result> records); void remove(Collection<ImageRecord> records); void deleteFile(Result result); void deleteFile(Path path); void markAll(Collection<Result> records, Tag tag); void markDnwAndDelete(Collection<Result> records); void markAs(Result result, Tag tag); void markAs(Path path, Tag tag); void markAs(ImageRecord image, Tag tag); void markDirectoryAs(Path directory, Tag tag); void markDirectoryAndChildrenAs(Path rootDirectory, Tag tag); List<ImageRecord> findMissingFiles(Path directory); void ignore(Result result); List<Tag> getFilterTags(); }
@Test public void testFindMissingFiles() throws Exception { Path testFile = Files.createTempFile(tempDirectory, "findmissingfilestest", null); ImageRecord missingRecord = new ImageRecord(testFile.getParent().resolve("foo").toString(), 0); when(imageRepository.startsWithPath(tempDirectory)) .thenReturn(Arrays.asList(new ImageRecord(testFile.toString(), 0), missingRecord)); List<ImageRecord> missing = dupOp.findMissingFiles(tempDirectory); assertThat(missing, containsInAnyOrder(missingRecord)); }
DuplicateOperations { public void ignore(Result result) { logger.info("Ignoring {}", result); try { ignoreRepository.store(new IgnoreRecord(result.getImageRecord())); } catch (RepositoryException e) { logger.error("Failed to store ignored image: {}, cause: {}", e.toString(), e.getCause().toString()); } } @Inject DuplicateOperations(FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); DuplicateOperations(FileSystem fileSystem, FilterRepository filterRepository, TagRepository tagRepository, ImageRepository imageRepository, IgnoreRepository ignoreRepository); void moveToDnw(Path path); void deleteAll(Collection<Result> records); void remove(Collection<ImageRecord> records); void deleteFile(Result result); void deleteFile(Path path); void markAll(Collection<Result> records, Tag tag); void markDnwAndDelete(Collection<Result> records); void markAs(Result result, Tag tag); void markAs(Path path, Tag tag); void markAs(ImageRecord image, Tag tag); void markDirectoryAs(Path directory, Tag tag); void markDirectoryAndChildrenAs(Path rootDirectory, Tag tag); List<ImageRecord> findMissingFiles(Path directory); void ignore(Result result); List<Tag> getFilterTags(); }
@Test public void testIgnoreImage() throws Exception { dupOp.ignore(result); verify(ignoreRepository).store(new IgnoreRecord(result.getImageRecord())); }
CompareHammingDistance implements Distance<Long> { protected static int getHammingDistance(long a, long b) { long xor = a ^ b; int distance = Long.bitCount(xor); return distance; } @Override double eval(Long e1, Long e2); }
@Test public void testGetHammingDistance() throws Exception { assertThat(CompareHammingDistance.getHammingDistance(2L, 3L), is(1)); } @Test public void testGetHammingDistance2() throws Exception { assertThat(CompareHammingDistance.getHammingDistance(2L, 4L), is(2)); } @Test public void testGetHammingDistance3() throws Exception { assertThat(CompareHammingDistance.getHammingDistance(3L, 5L), is(2)); }
CompareHammingDistance implements Distance<Long> { @Override public double eval(Long e1, Long e2) { int distance = getHammingDistance(e1, e2); return distance; } @Override double eval(Long e1, Long e2); }
@Test public void testEvalDistanceAxiom1() throws Exception { assertThat(chd.eval(a, c), is(0.0)); assertThat(a, is(c)); } @Test public void testEvalDistanceAxiom2() throws Exception { double ab, ba; ab = chd.eval(a, b); ba = chd.eval(b, a); assertThat(ab, is(ba)); } @Test public void testEvalDistanceAxiom3() throws Exception { double ad, ab, bd; ab = chd.eval(a, b); ad = chd.eval(a, d); bd = chd.eval(b, d); assertThat(ad, is(lessThanOrEqualTo(ab + bd))); }
SimilarImage { protected static boolean isNoWorkersMode(Namespace args) { return args.getBoolean("no_workers"); } static void main(String[] args); void init(boolean noWorkers); }
@Test public void testIsNoWorkersMode() throws Exception { assertThat(SimilarImage.isNoWorkersMode(noWorkersArgs), is(true)); } @Test public void testIsLocalMode() throws Exception { assertThat(SimilarImage.isNoWorkersMode(localModeArgs), is(false)); }
ImageInfo { public Path getPath() { return path; } ImageInfo(Path path, long pHash); Path getPath(); Dimension getDimension(); long getSize(); long getpHash(); double getSizePerPixel(); }
@Test public void testGetPath() throws Exception { assertThat(imageInfo.getPath(), is(testImage)); } @Test public void testGetPathInvalidImage() throws Exception { assertThat(imageInfoInvalid.getPath(), is(invalidImage)); }
ImageInfo { public Dimension getDimension() { return dimension; } ImageInfo(Path path, long pHash); Path getPath(); Dimension getDimension(); long getSize(); long getpHash(); double getSizePerPixel(); }
@Test public void testGetDimension() throws Exception { assertThat(imageInfo.getDimension(), is(new Dimension(40, 40))); } @Test public void testGetDimensionInvalidImage() throws Exception { assertThat(imageInfoInvalid.getDimension(), is(new Dimension(0, 0))); }
ImageInfo { public long getSize() { return size; } ImageInfo(Path path, long pHash); Path getPath(); Dimension getDimension(); long getSize(); long getpHash(); double getSizePerPixel(); }
@Test public void testGetSize() throws Exception { assertThat(imageInfo.getSize(), is(1782L)); } @Test public void testGetSizeInvalidImage() throws Exception { assertThat(imageInfoInvalid.getSize(), is(-1L)); } @Test public void testGetSizeInvalidFile() throws Exception { ImageInfo info = new ImageInfo(Paths.get("foo"), 2); assertThat(info.getSize(), is(-1L)); }
ImageInfo { public long getpHash() { return pHash; } ImageInfo(Path path, long pHash); Path getPath(); Dimension getDimension(); long getSize(); long getpHash(); double getSizePerPixel(); }
@Test public void testGetpHash() throws Exception { assertThat(imageInfo.getpHash(), is(42L)); } @Test public void testGetpHashInvalidImage() throws Exception { assertThat(imageInfoInvalid.getpHash(), is(0L)); } @Test public void testGetpHashInvalidFile() throws Exception { ImageInfo info = new ImageInfo(Paths.get("foo"), 2); assertThat(info.getpHash(), is(2L)); }
HashAttribute { public long readHash(Path path) throws InvalidAttributeValueException, IOException { if (!areAttributesValid(path)) { throw new InvalidAttributeValueException("The required attributes are not set or invalid"); } String encodedHash = ExtendedAttribute.readExtendedAttributeAsString(path, hashFQN); return Long.parseUnsignedLong(encodedHash, HEXADECIMAL_RADIX); } HashAttribute(String hashName); boolean areAttributesValid(Path path); long readHash(Path path); void writeHash(Path path, long hash); void markCorrupted(Path path); boolean isCorrupted(Path path); String getHashFQN(); String getTimestampFQN(); String getCorruptNameFQN(); }
@Test(expected = InvalidAttributeValueException.class) public void testReadHashInvalidFile() throws Exception { cut.readHash(fs.getPath(INVALID_FILE_PATH)); }
ImageInfo { public double getSizePerPixel() { return sizePerPixel; } ImageInfo(Path path, long pHash); Path getPath(); Dimension getDimension(); long getSize(); long getpHash(); double getSizePerPixel(); }
@Test public void testGetSizePerPixel() throws Exception { assertThat(imageInfo.getSizePerPixel(), is(1.11375)); } @Test public void testGetSizePerPixelInvalidImage() throws Exception { assertThat(imageInfoInvalid.getSizePerPixel(), is(0.0)); }
IgnoredImagePresenter { public void setView(IgnoredImageView view) { this.view = view; refreshList(); } IgnoredImagePresenter(IgnoreRepository ignoreRepository); void setView(IgnoredImageView view); DefaultListModel<IgnoreRecord> getModel(); void refreshList(); void removeIgnoredImages(List<IgnoreRecord> toRemove); }
@Test public void testSetView() throws Exception { cut.setView(ignoredImageView); verify(ignoredImageView, timeout(CONCURRENT_TIMEOUT)).pack(); }
IgnoredImagePresenter { public DefaultListModel<IgnoreRecord> getModel() { return model; } IgnoredImagePresenter(IgnoreRepository ignoreRepository); void setView(IgnoredImageView view); DefaultListModel<IgnoreRecord> getModel(); void refreshList(); void removeIgnoredImages(List<IgnoreRecord> toRemove); }
@Test public void testGetModel() throws Exception { assertThat(cut.getModel(), is(not(nullValue()))); }
IgnoredImagePresenter { public void refreshList() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { model.clear(); try { ignoreRepository.getAll().forEach(new Consumer<IgnoreRecord>() { @Override public void accept(IgnoreRecord t) { model.addElement(t); } }); } catch (RepositoryException e) { LOGGER.error("Failed to load ignored image list: {} cause:{}", e.getCause()); } view.pack(); } }); } IgnoredImagePresenter(IgnoreRepository ignoreRepository); void setView(IgnoredImageView view); DefaultListModel<IgnoreRecord> getModel(); void refreshList(); void removeIgnoredImages(List<IgnoreRecord> toRemove); }
@Test public void testRefreshList() throws Exception { cut.setView(ignoredImageView); cut.refreshList(); Awaitility.await().atMost(CONCURRENT_TIMEOUT, TimeUnit.MILLISECONDS).until(() -> cut.getModel().getSize(), is(2)); }
IgnoredImagePresenter { public void removeIgnoredImages(List<IgnoreRecord> toRemove) { LOGGER.info("Removing {} ignored images", toRemove.size()); toRemove.forEach(this::removeIgnoredImage); } IgnoredImagePresenter(IgnoreRepository ignoreRepository); void setView(IgnoredImageView view); DefaultListModel<IgnoreRecord> getModel(); void refreshList(); void removeIgnoredImages(List<IgnoreRecord> toRemove); }
@Test public void testRemoveIgnoredImages() throws Exception { cut.removeIgnoredImages(Arrays.asList(ignoreA)); verify(ignoreRepository).remove(ignoreA); } @Test public void testRemoveIgnoredImagesWithRepositoryError() throws Exception { Mockito.doThrow(new RepositoryException("")).when(ignoreRepository).remove(ignoreA); cut.removeIgnoredImages(Arrays.asList(ignoreA, ignoreB)); verify(ignoreRepository, times(2)).remove(any()); }
ThumbnailCacheLoader extends CacheLoader<Result, BufferedImage> { @Override public BufferedImage load(Result key) throws Exception { BufferedImage bi = ImageUtil.loadImage(Paths.get(key.getImageRecord().getPath())); return Scalr.resize(bi, Method.AUTOMATIC, THUMBNAIL_SIZE); } @Override BufferedImage load(Result key); }
@Test public void testLoadImage() throws Exception { assertThat(cut.load(key), is(notNullValue())); } @Test(expected = NoSuchFileException.class) public void testLoadInvalidPath() throws Exception { assertThat(cut.load(invalidImagePath), is(notNullValue())); }
HashAttribute { public String getHashFQN() { return hashFQN; } HashAttribute(String hashName); boolean areAttributesValid(Path path); long readHash(Path path); void writeHash(Path path, long hash); void markCorrupted(Path path); boolean isCorrupted(Path path); String getHashFQN(); String getTimestampFQN(); String getCorruptNameFQN(); }
@Test public void testGetHashFQN() throws Exception { assertThat(cut.getHashFQN(), is(ExtendedAttribute.createName("hash", TEST_HASH_NAME))); }
ResultPresenter { public Path getImagePath() { return imageInfo.getPath(); } ResultPresenter(Result result, LoadingCache<Result, BufferedImage> thumbnailCache); Path getImagePath(); void displayFullImage(); void setView(ResultView view); }
@Test public void testGetImagePath() throws Exception { assertThat(duplicateEntryController.getImagePath(), is(Paths.get(testImage.toString()))); }
ResultPresenter { public void setView(ResultView view) { this.view = view; loadThumbnail(); addImageInfo(); } ResultPresenter(Result result, LoadingCache<Result, BufferedImage> thumbnailCache); Path getImagePath(); void displayFullImage(); void setView(ResultView view); }
@Test public void testSetView() throws Exception { verify(view).setImage(any(JLabel.class)); verify(view).createLable(eq("Path: " + testImage.toString())); verify(view).createLable(eq("Size: 1 kb")); verify(view).createLable(eq("Dimension: 40x40")); verify(view).createLable(eq("pHash: 42")); verify(view).createLable(eq("Size per Pixel: 1.11375")); }
ResultPresenter { public void displayFullImage() { JLabel largeImage = new JLabel("No Image"); try { BufferedImage bi = ImageUtil.loadImage(getImagePath()); largeImage = imageAsLabel(bi); } catch (Exception e) { LOGGER.warn("Unable to load full image {} - {}", getImagePath(), e.getMessage()); } view.displayFullImage(largeImage, getImagePath()); } ResultPresenter(Result result, LoadingCache<Result, BufferedImage> thumbnailCache); Path getImagePath(); void displayFullImage(); void setView(ResultView view); }
@Test public void testDisplayFullImage() throws Exception { duplicateEntryController.displayFullImage(); verify(view).displayFullImage(any(JLabel.class), eq(testImage)); }
ProgressVisitor extends SimpleFileVisitor<Path> { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (!imageFileFilter.accept(file)) { return FileVisitResult.CONTINUE; } foundFiles.inc(); filesPerSecond.mark(); if (hashAttribute.isCorrupted(file)) { failedFiles.inc(); } else if (hashAttribute.areAttributesValid(file)) { processedFiles.inc(); } return FileVisitResult.CONTINUE; } ProgressVisitor(MetricRegistry metrics, HashAttribute hashAttribute); @Override FileVisitResult visitFile(Path file, BasicFileAttributes attrs); }
@Test public void testProcessedFileFoundCountForNonImage() throws Exception { cut.visitFile(pathNonImage, null); assertThat(foundFiles.getCount(), is(0L)); }
ArgumentPasrser { public void parseArgs(String[] args) throws ArgumentParserException { Namespace parsedArgs = parser.parseArgs(args); if (parsedArgs.get("subcommand") == Subcommand.local) { localCommand(parsedArgs); } if (parsedArgs.get("subcommand") == Subcommand.node) { nodeCommand(parsedArgs); } } ArgumentPasrser(FileVisitor<Path> visitor); void parseArgs(String[] args); }
@Test(expected = ArgumentParserException.class) public void testParseArgsInvalidOption() throws Exception { cut.parseArgs(new String[] { LOCAL_SUBCOMMAND, "--foo" }); } @Test public void testParseArgsUpdateOption() throws Exception { cut.parseArgs(new String[] { LOCAL_SUBCOMMAND, "--update", "foo" }); } @Test public void testParseArgsNodeOption() throws Exception { cut.parseArgs(new String[] { NODE_SUBCOMMAND, "--port", "123" }); }
ProgressCalc { public double totalProgressPercent() { if (foundFiles.getCount() == 0) { return 0; } else { return (PERCENT_100 / foundFiles.getCount()) * (processedFiles.getCount() + failedFiles.getCount()); } } ProgressCalc(MetricRegistry metrics); double totalProgressPercent(); double corruptPercent(); @Override String toString(); static final String METRIC_NAME_FOUND; static final String METRIC_NAME_PROCESSED; static final String METRIC_NAME_FAILED; static final String METRIC_NAME_FILES_PER_SECOND; }
@Test public void testTotalProgressPercent() throws Exception { assertThat(cut.totalProgressPercent(), closeTo(TOTAL_PROGRESS_PERCENT, ALLOWED_COMAPRE_ERROR)); } @Test public void testTotalProgressPercentWithNoFiles() throws Exception { setCounter(ProgressCalc.METRIC_NAME_FOUND, 0); setCounter(ProgressCalc.METRIC_NAME_PROCESSED, 0); assertThat(cut.totalProgressPercent(), is(0.0)); }
HashAttribute { public String getTimestampFQN() { return timestampFQN; } HashAttribute(String hashName); boolean areAttributesValid(Path path); long readHash(Path path); void writeHash(Path path, long hash); void markCorrupted(Path path); boolean isCorrupted(Path path); String getHashFQN(); String getTimestampFQN(); String getCorruptNameFQN(); }
@Test public void testGetTimestampFQN() throws Exception { assertThat(cut.getTimestampFQN(), is(ExtendedAttribute.createName("timestamp", TEST_HASH_NAME))); }
ProgressCalc { public double corruptPercent() { if (foundFiles.getCount() == 0) { return 0; } else { return (PERCENT_100 / foundFiles.getCount()) * failedFiles.getCount(); } } ProgressCalc(MetricRegistry metrics); double totalProgressPercent(); double corruptPercent(); @Override String toString(); static final String METRIC_NAME_FOUND; static final String METRIC_NAME_PROCESSED; static final String METRIC_NAME_FAILED; static final String METRIC_NAME_FILES_PER_SECOND; }
@Test public void testCorruptPercent() throws Exception { assertThat(cut.corruptPercent(), closeTo(CORRUPT_PERCENT, ALLOWED_COMAPRE_ERROR)); } @Test public void testCorruptPercentWithNoFiles() throws Exception { setCounter(ProgressCalc.METRIC_NAME_FOUND, 0); setCounter(ProgressCalc.METRIC_NAME_FAILED, 0); assertThat(cut.corruptPercent(), is(0.0)); }
ProgressCalc { @Override public String toString() { return String.format("Total progress: %.2f%%, corrupt images: %.2f%%, files per second processed: %.2f", totalProgressPercent(), corruptPercent(), filesPerSecond.getMeanRate()); } ProgressCalc(MetricRegistry metrics); double totalProgressPercent(); double corruptPercent(); @Override String toString(); static final String METRIC_NAME_FOUND; static final String METRIC_NAME_PROCESSED; static final String METRIC_NAME_FAILED; static final String METRIC_NAME_FILES_PER_SECOND; }
@Test public void testToString() throws Exception { assertThat(cut.toString(), is("Total progress: 23.81%, corrupt images: 9.52%, files per second processed: 0.00")); }
MessageFactory { public ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid) { ClientMessage message = session.createMessage(true); message.getBodyBuffer().writeLong(uuid.getMostSignificantBits()); message.getBodyBuffer().writeLong(uuid.getLeastSignificantBits()); message.getBodyBuffer().writeBytes(resizedImage); return message; } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }
@Test public void testHashRequestMessageTrackingId() throws Exception { ClientMessage result = cut.hashRequestMessage(IMAGE_DATA, UUID); UUID id = new UUID(result.getBodyBuffer().readLong(), result.getBodyBuffer().readLong()); assertThat(id, is(UUID)); } @Test public void testHashRequestMessageImageData() throws Exception { ClientMessage result = cut.hashRequestMessage(IMAGE_DATA, UUID); result.getBodyBuffer().readLong(); result.getBodyBuffer().readLong(); byte[] data = new byte[IMAGE_DATA.length]; result.getBodyBuffer().readBytes(data); assertArrayEquals(data, IMAGE_DATA); } @Test public void testHashRequestMessageImageSize() throws Exception { ClientMessage result = cut.hashRequestMessage(IMAGE_DATA, UUID); result.getBodyBuffer().readLong(); result.getBodyBuffer().readLong(); byte[] data = new byte[result.getBodySize()]; result.getBodyBuffer().readBytes(data); assertArrayEquals(data, IMAGE_DATA); }
MessageFactory { public ClientMessage resultMessage(long hash, long most, long least) { ClientMessage message = session.createMessage(true); setTaskType(message, TaskType.result); ActiveMQBuffer buffer = message.getBodyBuffer(); buffer.writeLong(most); buffer.writeLong(least); buffer.writeLong(hash); return message; } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }
@Test public void testResultMessageTask() throws Exception { ClientMessage result = cut.resultMessage(HASH, UUID.getMostSignificantBits(), UUID.getLeastSignificantBits()); assertThat(result.getStringProperty(MessageProperty.task.toString()), is(TaskType.result.toString())); } @Test public void testResultMessageUuid() throws Exception { ClientMessage result = cut.resultMessage(HASH, UUID.getMostSignificantBits(), UUID.getLeastSignificantBits()); UUID id = new UUID(result.getBodyBuffer().readLong(), result.getBodyBuffer().readLong()); assertThat(id, is(UUID)); } @Test public void testResultMessageHash() throws Exception { ClientMessage result = cut.resultMessage(HASH, UUID.getMostSignificantBits(), UUID.getLeastSignificantBits()); result.getBodyBuffer().readLong(); result.getBodyBuffer().readLong(); long hash = result.getBodyBuffer().readLong(); assertThat(hash, is(HASH)); }
MessageFactory { public ClientMessage pendingImageQuery() { ClientMessage message = session.createMessage(false); message.putStringProperty(MessageProperty.repository_query.toString(), QueryType.pending.toString()); return message; } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }
@Test public void testPendingImageQuery() throws Exception { ClientMessage result = cut.pendingImageQuery(); assertThat(result.getStringProperty(MessageFactory.MessageProperty.repository_query.toString()), is(MessageFactory.QueryType.pending.toString())); }
HashAttribute { public void markCorrupted(Path path) throws IOException { ExtendedAttribute.setExtendedAttribute(path, corruptNameFQN, ""); } HashAttribute(String hashName); boolean areAttributesValid(Path path); long readHash(Path path); void writeHash(Path path, long hash); void markCorrupted(Path path); boolean isCorrupted(Path path); String getHashFQN(); String getTimestampFQN(); String getCorruptNameFQN(); }
@Test public void testMarkCorrupted() throws Exception { cut.markCorrupted(tempFile); assertThat(ExtendedAttribute.isExtendedAttributeSet(tempFile, cut.getCorruptNameFQN()), is(true)); }
MessageFactory { public ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages) throws IOException { List<String> pendingPaths = new LinkedList<String>(); for (PendingHashImage p : pendingImages) { pendingPaths.add(p.getPath()); } try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos)) { ClientMessage message = session.createMessage(false); oos.writeObject(pendingPaths); message.writeBodyBufferBytes(baos.toByteArray()); return message; } } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }
@Test public void testPendingImageResponse() throws Exception { ClientMessage result = cut.pendingImageResponse(Arrays.asList(new PendingHashImage(PATH, UUID))); assertThat(result.getBodySize(), is(EXPECTED_MESSAGE_SIZE)); }
MessageFactory { public ClientMessage corruptMessage(Path path) { ClientMessage message = session.createMessage(true); message.putStringProperty(MessageProperty.path.toString(), path.toString()); message.putStringProperty(MessageProperty.task.toString(), TaskType.corr.toString()); return message; } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }
@Test public void testCorruptMessagePath() throws Exception { ClientMessage result = cut.corruptMessage(PATH); assertThat(result.getStringProperty(MessageProperty.path.toString()), is(PATH.toString())); } @Test public void testCorruptMessageTask() throws Exception { ClientMessage result = cut.corruptMessage(PATH); assertThat(result.getStringProperty(MessageProperty.task.toString()), is(TaskType.corr.toString())); }
MessageFactory { public ClientMessage eaUpdate(Path path, long hash) { ClientMessage message = session.createMessage(true); setTaskType(message, TaskType.eaupdate); setPath(message, path); message.getBodyBuffer().writeLong(hash); return message; } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }
@Test public void testEaUpdatePath() throws Exception { ClientMessage result = cut.eaUpdate(PATH, HASH); assertThat(result.getStringProperty(MessageProperty.path.toString()), is(PATH.toString())); } @Test public void testEaUpdateHash() throws Exception { ClientMessage result = cut.eaUpdate(PATH, HASH); assertThat(result.getBodyBuffer().readLong(), is(HASH)); } @Test public void testEaUpdateTask() throws Exception { ClientMessage result = cut.eaUpdate(PATH, HASH); assertThat(result.getStringProperty(MessageProperty.task.toString()), is(TaskType.eaupdate.toString())); }
MessageFactory { public ClientMessage resizeRequest(Path path, InputStream is) throws IOException { ClientMessage message = session.createMessage(true); copyInputStreamToMessage(is, message); setTaskType(message, TaskType.hash); setPath(message, path); return message; } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }
@Test public void testResizeRequestPath() throws Exception { ClientMessage result = cut.resizeRequest(PATH, is); assertThat(result.getStringProperty(MessageProperty.path.toString()), is(PATH.toString())); } @Test public void testResizeRequestTask() throws Exception { ClientMessage result = cut.resizeRequest(PATH, is); assertThat(result.getStringProperty(MessageProperty.task.toString()), is(TaskType.hash.toString())); }
MessageFactory { public ClientMessage trackPath(Path path, UUID uuid) { ClientMessage message = session.createMessage(false); setTaskType(message, TaskType.track); setPath(message, path); message.getBodyBuffer().writeLong(uuid.getMostSignificantBits()); message.getBodyBuffer().writeLong(uuid.getLeastSignificantBits()); return message; } MessageFactory(ClientSession session); ClientMessage hashRequestMessage(byte[] resizedImage, UUID uuid); ClientMessage resultMessage(long hash, long most, long least); ClientMessage corruptMessage(Path path); ClientMessage pendingImageQuery(); ClientMessage pendingImageResponse(List<PendingHashImage> pendingImages); ClientMessage trackPath(Path path, UUID uuid); ClientMessage eaUpdate(Path path, long hash); ClientMessage resizeRequest(Path path, InputStream is); }
@Test public void testTrackPathPathProperty() throws Exception { ClientMessage result = cut.trackPath(PATH, UUID); assertThat(result.getStringProperty(MessageProperty.path.toString()), is(PATH.toString())); } @Test public void testTrackPathTaskProperty() throws Exception { ClientMessage result = cut.trackPath(PATH, UUID); assertThat(result.getStringProperty(MessageProperty.task.toString()), is(TaskType.track.toString())); } @Test public void testTrackPathMessageBody() throws Exception { ClientMessage result = cut.trackPath(PATH, UUID); long most = result.getBodyBuffer().readLong(); long least = result.getBodyBuffer().readLong(); assertThat(new UUID(most, least), is(UUID)); }
HashAttribute { public String getCorruptNameFQN() { return corruptNameFQN; } HashAttribute(String hashName); boolean areAttributesValid(Path path); long readHash(Path path); void writeHash(Path path, long hash); void markCorrupted(Path path); boolean isCorrupted(Path path); String getHashFQN(); String getTimestampFQN(); String getCorruptNameFQN(); }
@Test public void testGetCorruptNameFQN() throws Exception { assertThat(cut.getCorruptNameFQN(), is(ExtendedAttribute.createName("corrupt"))); }
QueueToDatabaseTransaction implements CollectedMessageConsumer { @Override public void onDrain(List<ClientMessage> messages) { try { transactionManager.callInTransaction(new Callable<Void>() { @Override public Void call() throws Exception { onCall(messages); return null; } }); } catch (SQLException e) { LOGGER.warn("Failed to store {} messages: {}", messages.size(), e.toString(), e.getCause()); try { session.rollback(); } catch (ActiveMQException mqException) { String message = "Failed to rollback message transaction"; LOGGER.error(message, mqException); throw new RuntimeException(message, mqException); } } } QueueToDatabaseTransaction(ClientSession transactedSession, TransactionManager transactionManager, String eaQueueName, PendingHashImageRepository pendingRepository, ImageRepository imageRepository, MetricRegistry metrics); @Inject QueueToDatabaseTransaction(@Named("transacted") ClientSession transactedSession, TransactionManager transactionManager, PendingHashImageRepository pendingRepository, ImageRepository imageRepository, MetricRegistry metrics); @Override void onDrain(List<ClientMessage> messages); static final String METRIC_NAME_PENDING_MESSAGES_MISSING; static final String METRIC_NAME_PENDING_MESSAGES; static final String METRIC_NAME_PROCESSED_IMAGES; }
@Test public void testOnDrainInTransaction() throws Exception { cut.onDrain(messages); verify(transactionManager).callInTransaction(any()); } @Test public void testMessageRollbackOnDatabaseFailure() throws Exception { when(transactionManager.callInTransaction(any())) .thenThrow(new SQLException(EXCEPTION_MESSAGE)); cut.onDrain(messages); verify(session).rollback(); } @Test(expected = RuntimeException.class) public void testMessageRollbackFailure() throws Exception { when(transactionManager.callInTransaction(any())).thenThrow(new SQLException(EXCEPTION_MESSAGE)); Mockito.doThrow(new ActiveMQException()).when(session).rollback(); cut.onDrain(messages); }
QueueToDatabaseTransaction implements CollectedMessageConsumer { protected void onCall(List<ClientMessage> messages) throws RepositoryException, ActiveMQException { for (ClientMessage message : messages) { processMessage(message); message.acknowledge(); } session.commit(); } QueueToDatabaseTransaction(ClientSession transactedSession, TransactionManager transactionManager, String eaQueueName, PendingHashImageRepository pendingRepository, ImageRepository imageRepository, MetricRegistry metrics); @Inject QueueToDatabaseTransaction(@Named("transacted") ClientSession transactedSession, TransactionManager transactionManager, PendingHashImageRepository pendingRepository, ImageRepository imageRepository, MetricRegistry metrics); @Override void onDrain(List<ClientMessage> messages); static final String METRIC_NAME_PENDING_MESSAGES_MISSING; static final String METRIC_NAME_PENDING_MESSAGES; static final String METRIC_NAME_PROCESSED_IMAGES; }
@Test public void testOnCallMessageAcknowledge() throws Exception { cut.onCall(messages); verify(message, times(TEST_MESSAGE_SIZE)).acknowledge(); } @Test public void testOnCallPendingQuery() throws Exception { cut.onCall(messages); verify(pendingRepository).getByUUID(UUID_MOST, UUID_LEAST); } @Test public void testOnCallPendingMessageMissing() throws Exception { when(pendingRepository.getByUUID(UUID_MOST, UUID_LEAST)).thenReturn(null); cut.onCall(messages); assertThat( metrics.getCounters().get(QueueToDatabaseTransaction.METRIC_NAME_PENDING_MESSAGES_MISSING).getCount(), is((long) TEST_MESSAGE_SIZE)); } @Test public void testOnCallPendingMessagesDecrement() throws Exception { cut.onCall(messages); assertThat(metrics.getCounters().get(QueueToDatabaseTransaction.METRIC_NAME_PENDING_MESSAGES).getCount(), is(-1L)); } @Test public void testOnCallProcessedMessagesIncrement() throws Exception { cut.onCall(messages); assertThat(metrics.getMeters().get(QueueToDatabaseTransaction.METRIC_NAME_PROCESSED_IMAGES).getCount(), is(1L)); } @Test public void testOnCallResultStored() throws Exception { cut.onCall(messages); verify(imageRepository).store(eq(new ImageRecord(PATH, HASH))); } @Test public void testOnCallPendingRemoved() throws Exception { cut.onCall(messages); verify(pendingRepository).remove(new PendingHashImage(PATH, UUID_MOST, UUID_LEAST)); } @Test public void testOnCallEAupdateSent() throws Exception { cut.onCall(messages); verify(producer).send(sendMessage); }
HashAttribute { public boolean isCorrupted(Path path) throws IOException { return ExtendedAttribute.isExtendedAttributeSet(path, corruptNameFQN); } HashAttribute(String hashName); boolean areAttributesValid(Path path); long readHash(Path path); void writeHash(Path path, long hash); void markCorrupted(Path path); boolean isCorrupted(Path path); String getHashFQN(); String getTimestampFQN(); String getCorruptNameFQN(); }
@Test public void testIsCorruptedNotSet() throws Exception { assertThat(cut.isCorrupted(tempFile), is(false)); }
ResizerNode implements MessageHandler, Node { @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(ResizerNode.class.getSimpleName()).append(" {").append(identity.toString()).append("}"); return sb.toString(); } @Inject ResizerNode(ClientSession session, ImageResizer resizer, MetricRegistry metrics); protected ResizerNode(ClientSession session, ImageResizer resizer, String requestAddress, String resultAddress, QueryMessage queryMessage, MetricRegistry metrics); @Override void onMessage(ClientMessage message); @Override void stop(); @Override String toString(); static final String METRIC_NAME_RESIZE_MESSAGES; static final String METRIC_NAME_RESIZE_DURATION; static final String METRIC_NAME_PENDING_CACHE_HIT; static final String METRIC_NAME_PENDING_CACHE_MISS; static final String METRIC_NAME_IMAGE_SIZE; static final String METRIC_NAME_BUFFER_RESIZE; }
@Test public void testValidImageNotCorrupt() throws Exception { producer.send(message); await().atMost(MESSAGE_TIMEOUT).until(hashRequests::size, is(1)); ClientMessage response = hashRequests.get(0); assertThat(response.containsProperty(MessageProperty.task.toString()), is(false)); } @Test public void testValidImageTrackSent() throws Exception { producer.send(message); await().atMost(MESSAGE_TIMEOUT).until(results::size, is(1)); ClientMessage response = results.get(0); assertThat(response.getStringProperty(MessageProperty.task.toString()), is(TaskType.track.toString())); } @Test public void testCorruptImageDataTaskProperty() throws Exception { when(resizer.resize(nullable(BufferedImage.class))).thenThrow(new IIOException("")); producer.send(message); await().atMost(MESSAGE_TIMEOUT).until(eaUpdates::size, is(1)); ClientMessage response = eaUpdates.get(0); assertThat(response.getStringProperty(MessageProperty.task.toString()), is(TaskType.corr.toString())); } @Test public void testCorruptImageDataPathProperty() throws Exception { when(resizer.resize(nullable(BufferedImage.class))).thenThrow(new IIOException("")); producer.send(message); await().atMost(MESSAGE_TIMEOUT).until(eaUpdates::size, is(1)); ClientMessage response = eaUpdates.get(0); assertThat(response.getStringProperty(MessageProperty.path.toString()), is(PATH_NEW)); } @Test public void testGIFerrorUnknownBlock() throws Exception { when(resizer.resize(nullable(BufferedImage.class))).thenThrow(new IOException("Unknown block")); producer.send(message); await().atMost(MESSAGE_TIMEOUT).until(eaUpdates::size, is(1)); ClientMessage response = eaUpdates.get(0); assertThat(response.getStringProperty(MessageProperty.task.toString()), is(TaskType.corr.toString())); } @Test public void testGIFerrorInvalidHeader() throws Exception { when(resizer.resize(nullable(BufferedImage.class))).thenThrow(new IOException("Invalid GIF header")); producer.send(message); await().atMost(MESSAGE_TIMEOUT).until(eaUpdates::size, is(1)); ClientMessage response = eaUpdates.get(0); assertThat(response.getStringProperty(MessageProperty.task.toString()), is(TaskType.corr.toString())); } @Test public void testToStringStart() throws Exception { assertThat(cut.toString(), startsWith("ResizerNode {")); } @Test public void testToStringEnd() throws Exception { assertThat(cut.toString(), endsWith("}")); }
ResizerNode implements MessageHandler, Node { protected void allocateNewBuffer(int messageSize) { messageBuffer = ByteBuffer.allocateDirect(calcNewBufferSize(messageSize)); } @Inject ResizerNode(ClientSession session, ImageResizer resizer, MetricRegistry metrics); protected ResizerNode(ClientSession session, ImageResizer resizer, String requestAddress, String resultAddress, QueryMessage queryMessage, MetricRegistry metrics); @Override void onMessage(ClientMessage message); @Override void stop(); @Override String toString(); static final String METRIC_NAME_RESIZE_MESSAGES; static final String METRIC_NAME_RESIZE_DURATION; static final String METRIC_NAME_PENDING_CACHE_HIT; static final String METRIC_NAME_PENDING_CACHE_MISS; static final String METRIC_NAME_IMAGE_SIZE; static final String METRIC_NAME_BUFFER_RESIZE; }
@Test public void testBufferResize() throws Exception { for (byte i = 0; i < BUFFER_TEST_DATA_SIZE; i++) { message.getBodyBuffer().writeByte(i); } cut.allocateNewBuffer(1); producer.send(message); await().atMost(MESSAGE_TIMEOUT).until(() -> metrics.getCounters().get(ResizerNode.METRIC_NAME_BUFFER_RESIZE).getCount(), is(1L)); }
ResizerNode implements MessageHandler, Node { @Override public void onMessage(ClientMessage message) { String pathPropterty = null; resizeRequests.mark(); Context resizeTimeContext = resizeDuration.time(); try { pathPropterty = message.getStringProperty(MessageProperty.path.toString()); LOGGER.debug("Resize request for image {}", pathPropterty); if (pendingCache.getIfPresent(pathPropterty) != null) { LOGGER.trace("{} found in cache, skipping...", pathPropterty); pendingCacheHit.mark(); return; } else { pendingCacheMiss.mark(); } checkBufferCapacity(message.getBodySize()); messageBuffer.limit(message.getBodySize()); imageSize.update(message.getBodySize()); messageBuffer.rewind(); message.getBodyBuffer().readBytes(messageBuffer); messageBuffer.rewind(); Path path = Paths.get(pathPropterty); Path filename = path.getFileName(); InputStream is = new ByteBufferInputstream(messageBuffer); if (filename != null && filename.toString().toLowerCase().endsWith(".gif")) { GifImage gi = GifDecoder.read(is); is = new ByteArrayInputStream(ImageUtil.imageToBytes(gi.getFrame(0))); } BufferedImage originalImage = ImageIO.read(is); byte[] resizedImageData = resizer.resize(originalImage); UUID uuid = UUID.randomUUID(); ClientMessage trackMessage = messageFactory.trackPath(path, uuid); producer.send(QueueAddress.RESULT.toString(), trackMessage); LOGGER.trace("Sent tracking message for {} with UUID {}", pathPropterty, uuid); ClientMessage response = messageFactory.hashRequestMessage(resizedImageData, uuid); LOGGER.trace("Sending hash request with id {} instead of path {}", uuid, path); producer.send(response); pendingCache.put(pathPropterty, DUMMY); resizeTimeContext.stop(); } catch (ActiveMQException e) { LOGGER.error("Failed to send message: {}", e.toString()); } catch (IIOException | ArrayIndexOutOfBoundsException ie) { markImageCorrupt(pathPropterty); } catch (IOException e) { if (isImageError(e.getMessage())) { markImageCorrupt(pathPropterty); } else { LOGGER.error("Failed to process image: {}", e.toString()); } } catch (Exception e) { LOGGER.error("Unhandled exception: {}", e.toString()); LOGGER.debug("", e); } } @Inject ResizerNode(ClientSession session, ImageResizer resizer, MetricRegistry metrics); protected ResizerNode(ClientSession session, ImageResizer resizer, String requestAddress, String resultAddress, QueryMessage queryMessage, MetricRegistry metrics); @Override void onMessage(ClientMessage message); @Override void stop(); @Override String toString(); static final String METRIC_NAME_RESIZE_MESSAGES; static final String METRIC_NAME_RESIZE_DURATION; static final String METRIC_NAME_PENDING_CACHE_HIT; static final String METRIC_NAME_PENDING_CACHE_MISS; static final String METRIC_NAME_IMAGE_SIZE; static final String METRIC_NAME_BUFFER_RESIZE; }
@Test public void testImageSizeHistogramCount() throws Exception { message = new MessageFactory(session).resizeRequest(Paths.get(PATH_NEW), is); for (byte i = 0; i < BUFFER_TEST_DATA_SIZE; i++) { message.getBodyBuffer().writeByte(i); } cut.onMessage(message); assertThat(metrics.getHistograms().get(ResizerNode.METRIC_NAME_IMAGE_SIZE).getCount(), is(1L)); } @Test public void testImageSizeHistogramSize() throws Exception { message = new MessageFactory(session).resizeRequest(Paths.get(PATH_NEW), is); for (byte i = 0; i < BUFFER_TEST_DATA_SIZE; i++) { message.getBodyBuffer().writeByte(i); } cut.onMessage(message); assertThat(metrics.getHistograms().get(ResizerNode.METRIC_NAME_IMAGE_SIZE).getSnapshot().getMean(), is((double) BUFFER_TEST_DATA_SIZE)); }
ByteBufferInputstream extends InputStream { @Override public int read() throws IOException { if (buffer.hasRemaining()) { return buffer.get() & 0xFF; } else { return -1; } } ByteBufferInputstream(ByteBuffer buffer); @Override int read(); @Override int available(); }
@Test public void testReadFirstByte() throws Exception { assertThat(input.read(), is(2)); } @Test public void testReadAllData() throws Exception { byte[] read = new byte[TEST_DATA.length]; input.read(read); assertThat(read, is(TEST_DATA)); } @Test public void testReadAllDataByteRead() throws Exception { byte[] read = new byte[BUFFER_CAPACITY *2]; int actualRead = input.read(read); assertThat(actualRead, is(TEST_DATA.length)); } @Test public void testReadAllDataBuffered() throws Exception { byte[] read = new byte[TEST_DATA.length]; BufferedInputStream bis = new BufferedInputStream(input); bis.read(read); assertThat(read, is(TEST_DATA)); }
MessageCollector { private void onDrain() { ImmutableList<ClientMessage> immutable; LOGGER.trace("Draining {} collected messsages...", collectedMessages.size()); synchronized (collectedMessages) { immutable = ImmutableList.copyOf(collectedMessages); collectedMessages.clear(); } for (CollectedMessageConsumer drain : consumers) { drain.onDrain(immutable); } } MessageCollector(int collectedMessageThreshold, CollectedMessageConsumer... consumers); void addMessage(ClientMessage message); void drain(); }
@Test public void testAddMessageAboveThreshold() throws Exception { addNumberOfMessages(MESSAGE_THRESHOLD); verify(collector).onDrain(anyListOf(ClientMessage.class)); } @Test public void testAddMessageReTrigger() throws Exception { addNumberOfMessages(2 * MESSAGE_THRESHOLD); verify(collector, times(2)).onDrain(anyListOf(ClientMessage.class)); }
TaskMessageHandler implements MessageHandler { @Override public void onMessage(ClientMessage msg) { try { if (isTaskType(msg, TaskType.track)) { String path = msg.getStringProperty(MessageProperty.path.toString()); long most = msg.getBodyBuffer().readLong(); long least = msg.getBodyBuffer().readLong(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Tracking new path {} with UUID {}", path, new UUID(most, least)); } pendingMessages.inc(); pendingRepository.store(new PendingHashImage(path, most, least)); } else { LOGGER.error("Unhandled message: {}", msg); } } catch (RepositoryException e) { String cause = "unknown"; if(e.getCause() != null) { cause = e.getCause().toString(); } LOGGER.warn("Failed to store result message: {}, cause:{}", e.toString(), cause); } } @Inject TaskMessageHandler(PendingHashImageRepository pendingRepository, ImageRepository imageRepository, MetricRegistry metrics); @Deprecated TaskMessageHandler(PendingHashImageRepository pendingRepository, ImageRepository imageRepository, ClientSession session, MetricRegistry metrics); @Deprecated TaskMessageHandler(PendingHashImageRepository pendingRepository, ImageRepository imageRepository, ClientSession session, String eaUpdateAddress, MetricRegistry metrics); TaskMessageHandler(PendingHashImageRepository pendingRepository, ImageRepository imageRepository, String eaUpdateAddress, MetricRegistry metrics); @Override void onMessage(ClientMessage msg); static final String METRIC_NAME_PENDING_MESSAGES; }
@Test public void testMetricPendingMessagesTrack() throws Exception { ClientMessage message = messageFactory.trackPath(Paths.get(TEST_PATH), UUID); cut.onMessage(message); assertThat(metrics.getCounters().get(TaskMessageHandler.METRIC_NAME_PENDING_MESSAGES).getCount(), is(1L)); }
ResultMessageSink implements Node { @Override public void stop() { LOGGER.info("Stopping {}", WORKER_THREAD_NAME); sink.interrupt(); try { sink.join(); } catch (InterruptedException ie) { LOGGER.warn("Interrupted while wating for sink to terminate: {}", ie.toString()); } try { consumer.close(); } catch (ActiveMQException e) { LOGGER.warn("Failed to close consumer: {}", e.toString()); } } ResultMessageSink(ClientSession transactedSession, MessageCollector collector, String resultQueueName, long messageIdleTimeout); ResultMessageSink(ClientSession transactedSession, MessageCollector collector); @Override void stop(); }
@Test public void testStop() throws Exception { cut.stop(); verify(collector, timeout(VERIFY_TIMEOUT)).drain(); verify(consumer).close(); } @Test(timeout = TEST_TIMEOUT) public void testDrainOnNoMessage() throws Exception { cut.stop(); Mockito.reset(collector); when(consumer.receive(anyLong())).thenReturn(null); cut = new ResultMessageSink(session, collector); verify(collector, timeout(VERIFY_TIMEOUT).atLeastOnce()).drain(); verify(collector, never()).addMessage(message); } @Test public void testMessageReadFailure() throws Exception { cut.stop(); Mockito.reset(collector); when(consumer.receive(anyLong())).thenThrow(new ActiveMQException("test")); cut = new ResultMessageSink(session, collector); verify(collector, atMost(1)).drain(); verify(collector, never()).addMessage(any(ClientMessage.class)); }
HasherNode implements MessageHandler, Node { @Override public void onMessage(ClientMessage message) { hashRequests.mark(); Context hashTimeContext = hashDuration.time(); try { long most = message.getBodyBuffer().readLong(); long least = message.getBodyBuffer().readLong(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Got hash request with UUID {}, size {}", new UUID(most, least), message.getBodySize()); } checkBufferCapacity(message.getBodySize()); buffer.limit(message.getBodySize()); LOGGER.trace("Reading resized image with size {}", message.getBodySize()); buffer.rewind(); message.getBodyBuffer().readBytes(buffer); buffer.rewind(); long hash = doHash(ImageIO.read(new ByteBufferInputstream(buffer))); ClientMessage response = messageFactory.resultMessage(hash, most, least); producer.send(response); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Sent result for request with UUID {} to {}", new UUID(most, least), producer.getAddress()); } hashTimeContext.stop(); } catch (ActiveMQException e) { LOGGER.error("Failed to process message: {}", e.toString()); } catch (Exception e) { LOGGER.error("Failed to process image: {}", e.toString()); } } HasherNode(ClientSession session, ImagePHash hasher, String requestAddress, String resultAddress, MetricRegistry metrics); @Override void stop(); @Override String toString(); @Override void onMessage(ClientMessage message); static final String METRIC_NAME_HASH_MESSAGES; static final String METRIC_NAME_HASH_DURATION; static final String METRIC_NAME_BUFFER_RESIZE; }
@Test public void testBufferResize() throws Exception { hashRequestMessage = messageFactory.hashRequestMessage(new byte[LARGE_DATA_SIZE], TEST_UUID); cut.onMessage(hashRequestMessage); assertThat(metrics.getMeters().get(HasherNode.METRIC_NAME_BUFFER_RESIZE).getCount(), is(1L)); } @Test public void testHashDuration() throws Exception { cut.onMessage(hashRequestMessage); assertThat(metrics.getTimers().get(HasherNode.METRIC_NAME_HASH_DURATION).getSnapshot().getMean(), is(not(0.0))); } @Test public void testHashDurationOnFailure() throws Exception { Mockito.reset(hasher); when(hasher.getLongHash(nullable(BufferedImage.class))).thenThrow(new IOException("Testing")); cut.onMessage(hashRequestMessage); assertThat(metrics.getTimers().get(HasherNode.METRIC_NAME_HASH_DURATION).getSnapshot().getMean(), is(0.0)); }
HasherNode implements MessageHandler, Node { @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(HasherNode.class.getSimpleName()).append(" {").append(identity.toString()).append("}"); return sb.toString(); } HasherNode(ClientSession session, ImagePHash hasher, String requestAddress, String resultAddress, MetricRegistry metrics); @Override void stop(); @Override String toString(); @Override void onMessage(ClientMessage message); static final String METRIC_NAME_HASH_MESSAGES; static final String METRIC_NAME_HASH_DURATION; static final String METRIC_NAME_BUFFER_RESIZE; }
@Test public void testToStringStart() throws Exception { assertThat(cut.toString(), startsWith("HasherNode {")); } @Test public void testToStringEnd() throws Exception { assertThat(cut.toString(), endsWith("}")); }
HasherNode implements MessageHandler, Node { @Override public void stop() { LOGGER.info("Stopping {}...", this.toString()); MessagingUtil.silentClose(consumer); MessagingUtil.silentClose(producer); MessagingUtil.silentClose(session); } HasherNode(ClientSession session, ImagePHash hasher, String requestAddress, String resultAddress, MetricRegistry metrics); @Override void stop(); @Override String toString(); @Override void onMessage(ClientMessage message); static final String METRIC_NAME_HASH_MESSAGES; static final String METRIC_NAME_HASH_DURATION; static final String METRIC_NAME_BUFFER_RESIZE; }
@Test public void testStop() throws Exception { cut.stop(); assertThat(session.isClosed(), is(true)); }
RepositoryNode implements MessageHandler, Node { @Override public String toString() { return RepositoryNode.class.getSimpleName(); } RepositoryNode(ClientSession session, String queryAddress, String taskAddress, PendingHashImageRepository pendingRepository, ImageRepository imageRepository, TaskMessageHandler taskMessageHandler, MetricRegistry metrics); @Inject RepositoryNode(@Named("normal") ClientSession session, PendingHashImageRepository pendingRepository, TaskMessageHandler taskMessageHandler, MetricRegistry metrics); @Override void onMessage(ClientMessage message); @Override void stop(); @Override String toString(); }
@Test public void testQueryPending() throws Exception { List<String> pending = queryMessage.pendingImagePaths(); assertThat(pending, hasItem(PATH.toString())); } @Test public void testToString() throws Exception { assertThat(cut.toString(), is("RepositoryNode")); }
StorageNode implements MessageHandler, Node { public boolean processFile(Path path) { LOGGER.trace("Processing {}", path); if (isAlreadySent(path)) { LOGGER.trace("File {} has already been sent, ignoring...", path); return true; } try (InputStream bis = new BufferedInputStream(Files.newInputStream(path))) { ClientMessage request = messageFactory.resizeRequest(path, bis); producer.send(request); sentRequests.put(path, 0); LOGGER.trace("Sent resize request for {}", path); return true; } catch (IOException e) { LOGGER.warn("Failed to access file {}: {}", path, e.toString()); } catch (ActiveMQException e) { LOGGER.warn("Failed to send resize request for {}: {}", path, e.toString()); } return false; } StorageNode(ClientSession session, ExtendedAttributeQuery eaQuery, HashAttribute hashAttribute, List<Path> pendingPaths, String resizeAddress, String eaUpdateAddress); @Inject StorageNode(@Named("normal") ClientSession session, ExtendedAttributeQuery eaQuery, HashAttribute hashAttribute, @Named("pending") List<Path> pendingPaths); @Override void onMessage(ClientMessage message); boolean processFile(Path path); @Override void stop(); @Override String toString(); }
@Test public void testProcessFile() throws Exception { cut.processFile(testFile); await().until(messages::size, is(1)); ClientMessage message = messages.get(0); assertThat(message.getStringProperty(MessageProperty.path.toString()), is(testFile.toString())); } @Test public void testProcessFileSkipDuplicateCached() throws Exception { cut.processFile(cachedFile); await().pollDelay(1, TimeUnit.SECONDS).until(messages::size, is(0)); }
StorageNode implements MessageHandler, Node { @Override public String toString() { return StorageNode.class.getSimpleName(); } StorageNode(ClientSession session, ExtendedAttributeQuery eaQuery, HashAttribute hashAttribute, List<Path> pendingPaths, String resizeAddress, String eaUpdateAddress); @Inject StorageNode(@Named("normal") ClientSession session, ExtendedAttributeQuery eaQuery, HashAttribute hashAttribute, @Named("pending") List<Path> pendingPaths); @Override void onMessage(ClientMessage message); boolean processFile(Path path); @Override void stop(); @Override String toString(); }
@Test public void testToString() throws Exception { assertThat(cut.toString(), is("StorageNode")); }
ByteBufferInputstream extends InputStream { @Override public int available() throws IOException { return buffer.remaining(); } ByteBufferInputstream(ByteBuffer buffer); @Override int read(); @Override int available(); }
@Test public void testAvailable() throws Exception { assertThat(input.available(), is(TEST_DATA.length)); }
ImageFileFilter implements Filter<Path> { @Override public boolean accept(Path entry) throws IOException { return extFilter.accept(entry); } ImageFileFilter(); @Override boolean accept(Path entry); }
@Test public void testJpg() throws Exception { assertThat(cut.accept(createFile("foo.jpg")), is(true)); } @Test public void testJpeg() throws Exception { assertThat(cut.accept(createFile("foo.jpeg")), is(true)); } @Test public void testPng() throws Exception { assertThat(cut.accept(createFile("foo.png")), is(true)); } @Test public void testGif() throws Exception { assertThat(cut.accept(createFile("foo.gif")), is(true)); } @Test public void testNonLowerCase() throws Exception { assertThat(cut.accept(createFile("foo.Jpg")), is(true)); } @Test public void testNonImageExtension() throws Exception { assertThat(cut.accept(createFile("foo.txt")), is(false)); }
ImageUtil { public static BufferedImage loadImage(Path path) throws IOException { try (InputStream is = new BufferedInputStream(Files.newInputStream(path))) { BufferedImage bi; try { bi = ImageIO.read(is); } catch (ArrayIndexOutOfBoundsException e) { bi = GifDecoder.read(is).getFrame(0); } return bi; } } static BufferedImage bytesToImage(byte[] data); static byte[] imageToBytes(BufferedImage image); static BufferedImage loadImage(Path path); }
@Test public void testLoadImageJpg() throws Exception { BufferedImage image = ImageUtil.loadImage(jpgPath); assertThat(image.getHeight(), is(IMAGE_SIZE)); assertThat(image.getWidth(), is(IMAGE_SIZE)); } @Test public void testLoadImageGif() throws Exception { BufferedImage image = ImageUtil.loadImage(gifPath); assertThat(image.getHeight(), is(IMAGE_SIZE)); assertThat(image.getWidth(), is(IMAGE_SIZE)); }
Statistics { public void incrementFailedFiles() { dispatchEvent(StatisticsEvent.FAILED_FILES, failedFiles.incrementAndGet()); } int getFoundFiles(); void incrementFoundFiles(); int getProcessedFiles(); void incrementProcessedFiles(); int getFailedFiles(); void incrementFailedFiles(); int getSkippedFiles(); void incrementSkippedFiles(); void reset(); void addStatisticsListener(StatisticsChangedListener listener); void removeStatisticsListener(StatisticsChangedListener listener); }
@Test public void testIncrementFailedFilesEvent() throws Exception { cut.incrementFailedFiles(); verify(listener).statisticsChangedEvent(eq(StatisticsEvent.FAILED_FILES), eq(1)); }
Statistics { public void incrementFoundFiles() { dispatchEvent(StatisticsEvent.FOUND_FILES, foundFiles.incrementAndGet()); } int getFoundFiles(); void incrementFoundFiles(); int getProcessedFiles(); void incrementProcessedFiles(); int getFailedFiles(); void incrementFailedFiles(); int getSkippedFiles(); void incrementSkippedFiles(); void reset(); void addStatisticsListener(StatisticsChangedListener listener); void removeStatisticsListener(StatisticsChangedListener listener); }
@Test public void testIncrementFoundFilesEvent() throws Exception { cut.incrementFoundFiles(); verify(listener).statisticsChangedEvent(eq(StatisticsEvent.FOUND_FILES), eq(1)); }
Statistics { public void incrementProcessedFiles() { dispatchEvent(StatisticsEvent.PROCESSED_FILES, processedFiles.incrementAndGet()); } int getFoundFiles(); void incrementFoundFiles(); int getProcessedFiles(); void incrementProcessedFiles(); int getFailedFiles(); void incrementFailedFiles(); int getSkippedFiles(); void incrementSkippedFiles(); void reset(); void addStatisticsListener(StatisticsChangedListener listener); void removeStatisticsListener(StatisticsChangedListener listener); }
@Test public void testIncrementProcessedFilesFiles() throws Exception { cut.incrementProcessedFiles(); verify(listener).statisticsChangedEvent(eq(StatisticsEvent.PROCESSED_FILES), eq(1)); }
Statistics { public void incrementSkippedFiles() { dispatchEvent(StatisticsEvent.SKIPPED_FILES, skippedFiles.incrementAndGet()); } int getFoundFiles(); void incrementFoundFiles(); int getProcessedFiles(); void incrementProcessedFiles(); int getFailedFiles(); void incrementFailedFiles(); int getSkippedFiles(); void incrementSkippedFiles(); void reset(); void addStatisticsListener(StatisticsChangedListener listener); void removeStatisticsListener(StatisticsChangedListener listener); }
@Test public void testIncrementSkippedFilesEvent() throws Exception { cut.incrementSkippedFiles(); verify(listener).statisticsChangedEvent(eq(StatisticsEvent.SKIPPED_FILES), eq(1)); }
Statistics { public void removeStatisticsListener(StatisticsChangedListener listener) { statisticsChangedListners.remove(listener); } int getFoundFiles(); void incrementFoundFiles(); int getProcessedFiles(); void incrementProcessedFiles(); int getFailedFiles(); void incrementFailedFiles(); int getSkippedFiles(); void incrementSkippedFiles(); void reset(); void addStatisticsListener(StatisticsChangedListener listener); void removeStatisticsListener(StatisticsChangedListener listener); }
@Test public void testRemoveStatisticsListener() throws Exception { cut.removeStatisticsListener(listener); cut.incrementFailedFiles(); cut.incrementFoundFiles(); cut.incrementProcessedFiles(); cut.incrementSkippedFiles(); verifyZeroInteractions(listener); }
GroupList { public void remove(Result result) { Collection<ResultGroup> groupsToRemoveFrom = resultsToGroups.removeAll(result); LOGGER.debug("Removing {} from {} group(s).", result, groupsToRemoveFrom.size()); for (ResultGroup g : groupsToRemoveFrom) { g.remove(result, false); checkAndremoveEmptyGroup(g); } } GroupList(); GroupList(DefaultListModel<ResultGroup> mappedListModel); void populateList(Collection<ResultGroup> groupsToAdd); int groupCount(); void remove(Result result); ResultGroup getGroup(long hash); List<ResultGroup> getAllGroups(); void setMappedListModel(DefaultListModel<ResultGroup> mappedListeModel); ResultGroup nextGroup(ResultGroup currentGroup); ResultGroup previousGroup(ResultGroup currentGroup); }
@Test public void testRemoveViaGroup() throws Exception { Result result = new Result(groupB, recordC); assertThat(groupB.getResults(), hasItem(result)); groupA.remove(result); assertThat(groupB.getResults(), not(hasItem(result))); } @Test public void testEmptyGroupRemovedFromGui() throws Exception { cut = new GroupList(dlm); initGroupList(); groupA.remove(new Result(groupA, recordC)); groupA.remove(new Result(groupA, recordA)); assertThat(dlm.contains(groupA), is(false)); }
GroupList { public int groupCount() { return groups.size(); } GroupList(); GroupList(DefaultListModel<ResultGroup> mappedListModel); void populateList(Collection<ResultGroup> groupsToAdd); int groupCount(); void remove(Result result); ResultGroup getGroup(long hash); List<ResultGroup> getAllGroups(); void setMappedListModel(DefaultListModel<ResultGroup> mappedListeModel); ResultGroup nextGroup(ResultGroup currentGroup); ResultGroup previousGroup(ResultGroup currentGroup); }
@Test public void testGroupCount() throws Exception { assertThat(cut.groupCount(), is(2)); }
GroupList { public ResultGroup getGroup(long hash) throws IllegalArgumentException { ResultGroup group = hashToGroup.get(hash); if (group == null) { throw new IllegalArgumentException("Query for unknown hash"); } return group; } GroupList(); GroupList(DefaultListModel<ResultGroup> mappedListModel); void populateList(Collection<ResultGroup> groupsToAdd); int groupCount(); void remove(Result result); ResultGroup getGroup(long hash); List<ResultGroup> getAllGroups(); void setMappedListModel(DefaultListModel<ResultGroup> mappedListeModel); ResultGroup nextGroup(ResultGroup currentGroup); ResultGroup previousGroup(ResultGroup currentGroup); }
@Test public void testGetGroup() throws Exception { assertThat(cut.getGroup(HASH_A), is(groupA)); } @Test(expected = IllegalArgumentException.class) public void testGetInvalidHash() throws Exception { cut.getGroup(-1); }
GroupList { public ResultGroup previousGroup(ResultGroup currentGroup) { int index = groups.indexOf(currentGroup); index = boundsCheckedIndex(--index); return groups.get(index); } GroupList(); GroupList(DefaultListModel<ResultGroup> mappedListModel); void populateList(Collection<ResultGroup> groupsToAdd); int groupCount(); void remove(Result result); ResultGroup getGroup(long hash); List<ResultGroup> getAllGroups(); void setMappedListModel(DefaultListModel<ResultGroup> mappedListeModel); ResultGroup nextGroup(ResultGroup currentGroup); ResultGroup previousGroup(ResultGroup currentGroup); }
@Test public void testPreviousGroup() throws Exception { assertThat(cut.previousGroup(groupB), is(groupA)); } @Test public void testPreviousGroupWithFirstGroup() throws Exception { assertThat(cut.previousGroup(groupA), is(groupA)); } @Test public void testPreviousGroupWithUnknownGroup() throws Exception { assertThat(cut.previousGroup(groupUnknown), is(groupA)); }
GroupList { public ResultGroup nextGroup(ResultGroup currentGroup) { int index = groups.indexOf(currentGroup); index = boundsCheckedIndex(++index); return groups.get(index); } GroupList(); GroupList(DefaultListModel<ResultGroup> mappedListModel); void populateList(Collection<ResultGroup> groupsToAdd); int groupCount(); void remove(Result result); ResultGroup getGroup(long hash); List<ResultGroup> getAllGroups(); void setMappedListModel(DefaultListModel<ResultGroup> mappedListeModel); ResultGroup nextGroup(ResultGroup currentGroup); ResultGroup previousGroup(ResultGroup currentGroup); }
@Test public void testNextGroup() throws Exception { assertThat(cut.nextGroup(groupA), is(groupB)); } @Test public void testNextGroupWithLastGroup() throws Exception { assertThat(cut.nextGroup(groupB), is(groupB)); } @Test public void testNextGroupWithUnknownGroup() throws Exception { assertThat(cut.nextGroup(groupUnknown), is(groupA)); }
Result { public ImageRecord getImageRecord() { return imageRecord; } Result(ResultGroup parentGroup, ImageRecord imageRecord); ImageRecord getImageRecord(); void remove(); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); }
@Test public void testGetImageRecord() throws Exception { assertThat(cut.getImageRecord(), is(imageRecord)); }
StringUtil { public static String sanitizeTag(String tagFromGui) { if (tagFromGui == null || "".equals(tagFromGui)) { return MATCH_ALL_TAGS; } return tagFromGui; } private StringUtil(); static String sanitizeTag(String tagFromGui); static final String MATCH_ALL_TAGS; }
@Test public void testSanitizeTag() throws Exception { assertThat(StringUtil.sanitizeTag(TEST_TAG), is(TEST_TAG)); } @Test public void testSanitizeTagNull() throws Exception { assertThat(StringUtil.sanitizeTag(null), is(StringUtil.MATCH_ALL_TAGS)); } @Test public void testSanitizeTagEmpty() throws Exception { assertThat(StringUtil.sanitizeTag(""), is(StringUtil.MATCH_ALL_TAGS)); }
Result { public void remove() { LOGGER.debug("Removing result {}", this); parentGroup.remove(this); } Result(ResultGroup parentGroup, ImageRecord imageRecord); ImageRecord getImageRecord(); void remove(); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); }
@Test public void testRemoveResult() throws Exception { cut.remove(); verify(parentGroup).remove(cut); }
ResultGroup { public long getHash() { return hash; } ResultGroup(GroupList parent, long hash, Collection<ImageRecord> records); long getHash(); List<Result> getResults(); boolean remove(Result result); boolean remove(Result result, boolean notifyParent); @Override String toString(); boolean hasResults(); @Override final int hashCode(); @Override final boolean equals(Object obj); }
@Test public void testGetHash() throws Exception { assertThat(cut.getHash(), is(HASH)); }
ResultGroup { public List<Result> getResults() { return results; } ResultGroup(GroupList parent, long hash, Collection<ImageRecord> records); long getHash(); List<Result> getResults(); boolean remove(Result result); boolean remove(Result result, boolean notifyParent); @Override String toString(); boolean hasResults(); @Override final int hashCode(); @Override final boolean equals(Object obj); }
@Test public void testGetResults() throws Exception { assertThat(cut.getResults(), hasItems(resultA, new Result(cut, recordB))); }
ResultGroup { public boolean remove(Result result) { return remove(result, true); } ResultGroup(GroupList parent, long hash, Collection<ImageRecord> records); long getHash(); List<Result> getResults(); boolean remove(Result result); boolean remove(Result result, boolean notifyParent); @Override String toString(); boolean hasResults(); @Override final int hashCode(); @Override final boolean equals(Object obj); }
@Test public void testRemove() throws Exception { assertThat(cut.remove(resultA), is(true)); } @Test public void testRemoveNonExistingResult() throws Exception { cut.remove(resultA); assertThat(cut.remove(resultA), is(false)); } @Test public void testNotifyParentOnResultRemoval() throws Exception { cut.remove(resultA); verify(parent).remove(resultA); } @Test public void testRemoveWithoutNotification() throws Exception { cut.remove(resultA, false); verify(parent, never()).remove(resultA); }
ResultGroup { public boolean hasResults() { return !results.isEmpty(); } ResultGroup(GroupList parent, long hash, Collection<ImageRecord> records); long getHash(); List<Result> getResults(); boolean remove(Result result); boolean remove(Result result, boolean notifyParent); @Override String toString(); boolean hasResults(); @Override final int hashCode(); @Override final boolean equals(Object obj); }
@Test public void testHasResults() throws Exception { assertThat(cut.hasResults(), is(true)); }
ResultGroup { @Override public String toString() { return String.format("%d (%d)", this.hash, results.size()); } ResultGroup(GroupList parent, long hash, Collection<ImageRecord> records); long getHash(); List<Result> getResults(); boolean remove(Result result); boolean remove(Result result, boolean notifyParent); @Override String toString(); boolean hasResults(); @Override final int hashCode(); @Override final boolean equals(Object obj); }
@Test public void testToString() throws Exception { assertThat(cut.toString(), is("42 (2)")); }
ImageRecord implements Comparable<ImageRecord> { public String getPath() { return path; } @Deprecated ImageRecord(); ImageRecord(String path, long pHash); String getPath(); long getpHash(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(ImageRecord o); @Override String toString(); static final String PATH_COLUMN_NAME; }
@Test public void testGetPath() throws Exception { assertThat(imageRecord.getPath(), is("foo")); }
ImageRecord implements Comparable<ImageRecord> { public long getpHash() { return pHash; } @Deprecated ImageRecord(); ImageRecord(String path, long pHash); String getPath(); long getpHash(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(ImageRecord o); @Override String toString(); static final String PATH_COLUMN_NAME; }
@Test public void testGetpHash() throws Exception { assertThat(imageRecord.getpHash(), is(42L)); }
ImageRecord implements Comparable<ImageRecord> { @Override public int compareTo(ImageRecord o) { if (o == null) { throw new NullPointerException(); } if (this.pHash == o.getpHash()) { return 0; } else if (this.getpHash() > o.pHash) { return 1; } else { return -1; } } @Deprecated ImageRecord(); ImageRecord(String path, long pHash); String getPath(); long getpHash(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(ImageRecord o); @Override String toString(); static final String PATH_COLUMN_NAME; }
@Test public void testCompareToSelf() throws Exception { assertThat(imageRecord.compareTo(imageRecord), is(0)); } @Test(expected = NullPointerException.class) public void testCompareToNull() throws Exception { imageRecord.compareTo(null); } @Test public void testCompareToBigger() throws Exception { assertThat(imageRecord.compareTo(new ImageRecord("bar", 55)), is(-1)); } @Test public void testCompareToSmaller() throws Exception { assertThat(imageRecord.compareTo(new ImageRecord("bar", 7)), is(1)); } @Test public void testCompareToEqual() throws Exception { assertThat(imageRecord.compareTo(new ImageRecord("bar", 42)), is(0)); }