src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
|---|---|
DuplicateDetector { public DuplicateDetectionResult detectDuplicates(Set<SearchResultItem> results) { Map<String, List<SearchResultItem>> groupedByTitle = results.stream().collect(Collectors.groupingBy(x -> x.getTitle().toLowerCase().replaceAll("[ .\\-_]", ""))); Multiset<Indexer> countUniqueResultsPerIndexer = HashMultiset.create(); List<LinkedHashSet<SearchResultItem>> duplicateGroups = new ArrayList<>(); int countDetectedDuplicates = 0; for (List<SearchResultItem> titleGroup : groupedByTitle.values()) { titleGroup = titleGroup.stream().sorted(Comparator.comparing(SearchResultItem::getBestDate).reversed()).collect(Collectors.toList()); List<LinkedHashSet<SearchResultItem>> listOfBuckets = new ArrayList<>(); listOfBuckets.add(new LinkedHashSet<>(newArrayList(titleGroup.get(0)))); for (int i = 1; i < titleGroup.size(); i++) { SearchResultItem searchResultItem = titleGroup.get(i); boolean foundBucket = false; for (LinkedHashSet<SearchResultItem> bucket : listOfBuckets) { if (bucket.stream().map(SearchResultItem::getIndexer).collect(Collectors.toList()).contains(searchResultItem.getIndexer())) { continue; } for (SearchResultItem other : bucket) { boolean same = testForSameness(searchResultItem, other); if (same) { foundBucket = true; bucket.add(searchResultItem); countDetectedDuplicates++; break; } } if (foundBucket) { break; } } if (!foundBucket) { listOfBuckets.add(new LinkedHashSet<>(newArrayList(searchResultItem))); } } LinkedHashSet<SearchResultItem> lastBucket = Iterables.getLast(listOfBuckets); if (lastBucket.size() == 1) { countUniqueResultsPerIndexer.add(lastBucket.iterator().next().getIndexer()); } duplicateGroups.addAll(listOfBuckets); } int duplicateIdentifier = 0; for (LinkedHashSet<SearchResultItem> group : duplicateGroups) { for (SearchResultItem x : group) { x.setDuplicateIdentifier(duplicateIdentifier); } duplicateIdentifier++; } logger.debug("Duplicate detection for {} search results found {} duplicates", results.size(), countDetectedDuplicates); return new DuplicateDetectionResult(duplicateGroups, countUniqueResultsPerIndexer, countDetectedDuplicates); } DuplicateDetectionResult detectDuplicates(Set<SearchResultItem> results); }
|
@Test public void shouldDetectThatTheSame() throws Exception { SearchResultItem item1 = new SearchResultItem(); setValues(item1, "1", "poster", "group", Instant.now()); SearchResultItem item2 = new SearchResultItem(); setValues(item2, "2", "poster", "group", Instant.now()); SearchResultItem item3 = new SearchResultItem(); setValues(item3, "3", "poster", "group", Instant.now()); DuplicateDetectionResult result = testee.detectDuplicates(Sets.newHashSet(item1, item2, item3)); assertThat(result.getDuplicateGroups().size()).isEqualTo(1); List<SearchResultItem> items = new ArrayList<>(result.getDuplicateGroups().get(0)); assertThat(items.get(0).getDuplicateIdentifier()).isEqualTo(items.get(1).getDuplicateIdentifier()).isEqualTo(items.get(2).getDuplicateIdentifier()); }
@Test public void shouldWorkWithOneIndexerProvidingGroupAndPosterAndOneNot() throws Exception { SearchResultItem item1 = new SearchResultItem(); setValues(item1, "Indexer1", "chuck@norris.com", "alt.binaries.triballs", Instant.ofEpochSecond(1447928064)); item1.setUsenetDate(item1.getPubDate()); item1.setSize(11565521038L); SearchResultItem item2 = new SearchResultItem(); setValues(item2, "Indexer1", "moovee@4u.tv (moovee)", "alt.binaries.moovee", Instant.ofEpochSecond(1447930279)); item2.setUsenetDate(item2.getPubDate()); item2.setSize(12100381412L); SearchResultItem item3 = new SearchResultItem(); setValues(item3, "Indexer1", "chuck@norris.com", "alt.binaries.triballs", Instant.ofEpochSecond(1447927640)); item3.setUsenetDate(item3.getPubDate()); item3.setSize(11565520866L); SearchResultItem item4 = new SearchResultItem(); setValues(item4, "Indexer1", "moovee@4u.tv (moovee)", "alt.binaries.moovee", Instant.ofEpochSecond(1447930279)); item4.setUsenetDate(item4.getPubDate()); item4.setSize(12100382514L); SearchResultItem item5 = new SearchResultItem(); setValues(item5, "Indexer2", null, null, Instant.ofEpochSecond(1447973616)); item5.setSize(12096598793L); SearchResultItem item6 = new SearchResultItem(); setValues(item6, "Indexer2", null, null, Instant.ofEpochSecond(1447945386)); item6.setSize(12078310717L); SearchResultItem item7 = new SearchResultItem(); setValues(item7, "Indexer2", null, null, Instant.ofEpochSecond(1447930475)); item7.setSize(12099830939L); SearchResultItem item8 = new SearchResultItem(); setValues(item8, "Indexer2", null, null, Instant.ofEpochSecond(1447928088)); item8.setSize(11566348892L); HashSet<SearchResultItem> results = Sets.newHashSet(item1, item2, item3, item4, item5, item6, item7, item8); DuplicateDetectionResult result = testee.detectDuplicates(results); assertThat(result.getDuplicateGroups().size()).isEqualTo(6); assertThat(result.getDuplicateGroups().get(0).size()).isEqualTo(1); assertThat(result.getDuplicateGroups().get(1).size()).isEqualTo(1); assertThat(result.getDuplicateGroups().get(2).size()).isEqualTo(2); assertThat(result.getDuplicateGroups().get(3).size()).isEqualTo(1); assertThat(result.getDuplicateGroups().get(4).size()).isEqualTo(2); assertThat(result.getDuplicateGroups().get(5).size()).isEqualTo(1); }
@Test public void duplicateIdsShouldBeSameForDuplicates() throws Exception { SearchResultItem item1 = new SearchResultItem(); setValues(item1, "1", "poster1", "group", Instant.now()); SearchResultItem item2 = new SearchResultItem(); setValues(item2, "2", "poster1", "group", Instant.now()); SearchResultItem item3 = new SearchResultItem(); setValues(item3, "3", "poster2", "group", Instant.now()); SearchResultItem item4 = new SearchResultItem(); setValues(item4, "4", "poster2", "group", Instant.now()); DuplicateDetectionResult result = testee.detectDuplicates(Sets.newHashSet(item1, item2, item3, item4)); assertThat(result.getDuplicateGroups().size()).isEqualTo(2); List<SearchResultItem> items = new ArrayList<>(result.getDuplicateGroups().get(0)); assertThat(items.get(0).getDuplicateIdentifier()).isEqualTo(items.get(1).getDuplicateIdentifier()).as("Duplicates should have the same duplicate identifiers"); items = new ArrayList<>(result.getDuplicateGroups().get(1)); assertThat(items.get(0).getDuplicateIdentifier()).isEqualTo(items.get(1).getDuplicateIdentifier()).as("Duplicates should have the same duplicate identifiers"); }
|
DuplicateDetector { protected boolean testForDuplicateAge(SearchResultItem result1, SearchResultItem result2, float duplicateAgeThreshold) { Instant date1 = result1.getBestDate(); Instant date2 = result2.getBestDate(); if (date1 == null || date2 == null) { logger.debug(LoggingMarkers.DUPLICATES, "At least one result has no usenet date and no pub date"); return false; } boolean isSameAge = Math.abs(date1.getEpochSecond() - date2.getEpochSecond()) / (60 * 60) <= duplicateAgeThreshold; logger.debug(LoggingMarkers.DUPLICATES, "Same age: {}", isSameAge); return isSameAge; } DuplicateDetectionResult detectDuplicates(Set<SearchResultItem> results); }
|
@Test public void shouldUseUsenetDateForComparison() throws Exception { SearchResultItem item1 = new SearchResultItem(); setValues(item1, "1", "poster1", "group", Instant.now()); item1.setPubDate(Instant.now().minus(100, ChronoUnit.DAYS)); SearchResultItem item2 = new SearchResultItem(); setValues(item2, "2", "poster1", "group", Instant.now()); item2.setPubDate(Instant.now().minus(300, ChronoUnit.DAYS)); item1.setUsenetDate(Instant.now()); item2.setUsenetDate(Instant.now()); assertThat(testee.testForDuplicateAge(item1, item2, 1F)).isTrue(); item2.setUsenetDate(null); assertThat(testee.testForDuplicateAge(item1, item2, 1F)).isFalse(); }
|
InternalSearchResultProcessor { protected SearchResultWebTOBuilder setSearchResultDateRelatedValues(SearchResultWebTOBuilder builder, SearchResultItem item) { Instant date = item.getBestDate(); long ageInDays = date.until(Instant.now(), ChronoUnit.DAYS); if (ageInDays > 0) { builder.age(ageInDays + "d"); } else { long ageInHours = date.until(Instant.now(), ChronoUnit.HOURS); if (ageInHours > 0) { builder.age(ageInHours + "h"); } else { long ageInMinutes = date.until(Instant.now(), ChronoUnit.MINUTES); builder.age(ageInMinutes + "m"); } } builder = builder .age_precise(item.isAgePrecise()) .date(LocalDateTime.ofInstant(date, ZoneId.of("UTC")).format(item.isAgePrecise() ? DATE_TIME_FORMATTER : DATE_FORMATTER)) .epoch(date.getEpochSecond()); return builder; } SearchResponse createSearchResponse(org.nzbhydra.searching.SearchResult searchResult); }
|
@Test public void setSearchResultDateRelatedValues() { SearchResultWebTOBuilder builder = SearchResultWebTO.builder(); SearchResultItem item = new SearchResultItem(); item.setPubDate(Instant.now().minus(100, ChronoUnit.DAYS)); item.setUsenetDate(Instant.now().minus(10, ChronoUnit.DAYS)); builder = testee.setSearchResultDateRelatedValues(builder, item); assertThat(builder.build().getAge()).isEqualTo("10d"); item.setUsenetDate(Instant.now().minus(10, ChronoUnit.HOURS)); builder = testee.setSearchResultDateRelatedValues(builder, item); assertThat(builder.build().getAge()).isEqualTo("10h"); item.setUsenetDate(Instant.now().minus(10, ChronoUnit.MINUTES)); builder = testee.setSearchResultDateRelatedValues(builder, item); assertThat(builder.build().getAge()).isEqualTo("10m"); item.setUsenetDate(null); builder = testee.setSearchResultDateRelatedValues(builder, item); assertThat(builder.build().getAge()).isEqualTo("100d"); }
|
DownloadStatusUpdater { protected void checkStatus(List<FileDownloadStatus> nzbDownloadStatuses, long maxAgeDownloadEntitiesInSeconds, StatusCheckType statusCheckType) { if ((!queueCheckEnabled && statusCheckType == StatusCheckType.QUEUE) || (!historyCheckEnabled && statusCheckType == StatusCheckType.HISTORY)) { logger.debug(LoggingMarkers.DOWNLOAD_STATUS_UPDATE, "Not executing {} status update because it's disabled", statusCheckType); return; } if (lastDownload.isBefore(Instant.now().minusSeconds(MIN_SECONDS_SINCE_LAST_DOWNLOAD_TO_CHECK_STATUSES))) { logger.debug(LoggingMarkers.DOWNLOAD_STATUS_UPDATE, "Not executing {} status update because last download was {}", statusCheckType, lastDownload); return; } List<FileDownloadEntity> downloadsWaitingForUpdate = downloadRepository.findByStatusInAndTimeAfterOrderByTimeDesc(nzbDownloadStatuses, Instant.now().minusSeconds(maxAgeDownloadEntitiesInSeconds)); if (downloadsWaitingForUpdate.isEmpty()) { if (statusCheckType == StatusCheckType.QUEUE) { queueCheckEnabled = false; } else { historyCheckEnabled = false; } logger.debug(LoggingMarkers.DOWNLOAD_STATUS_UPDATE, "Returning and setting {} status update disabled because no current downloads are waiting for updates", statusCheckType); return; } List<FileDownloadEntity> updatedDownloads = new ArrayList<>(); logger.debug(LoggingMarkers.DOWNLOAD_STATUS_UPDATE, "{} downloads waiting for {} update", downloadsWaitingForUpdate.size(), statusCheckType); for (Downloader downloader : downloaderProvider.getAllDownloaders()) { if (downloader.isEnabled()) { updatedDownloads.addAll(downloader.checkForStatusUpdates(downloadsWaitingForUpdate, statusCheckType)); } } downloadRepository.saveAll(updatedDownloads); } @HydraTask(configId = "downloadHistoryCheck", name = "Download history check", interval = TEN_MINUTES_MS) @Transactional void checkHistoryStatus(); @HydraTask(configId = "downloadQueueCheck", name = "Download queue check", interval = TEN_SECONDS_MS) @Transactional void checkQueueStatus(); @EventListener void onNzbDownloadEvent(FileDownloadEvent downloadEvent); }
|
@Test public void shouldNotRunWhenNotEnabled() { testee.queueCheckEnabled = false; testee.lastDownload = Instant.now(); testee.checkStatus(Collections.singletonList(FileDownloadStatus.REQUESTED), 10000, StatusCheckType.QUEUE); verifyNoMoreInteractions(downloadRepository); }
@Test public void shouldNotRunWhenLastDownloadTooLongGone() { testee.queueCheckEnabled = true; testee.lastDownload = Instant.ofEpochSecond(1L); testee.checkStatus(Collections.singletonList(FileDownloadStatus.REQUESTED), 10000, StatusCheckType.HISTORY); verifyNoMoreInteractions(downloadRepository); }
@Test public void shouldSetDisabledAndNotRunIfNoDownloadsInDatabase() { testee.historyCheckEnabled = true; testee.lastDownload = Instant.now(); List<FileDownloadStatus> statuses = Collections.singletonList(FileDownloadStatus.REQUESTED); when(downloadRepository.findByStatusInAndTimeAfterOrderByTimeDesc(eq(statuses), any())).thenReturn(Collections.emptyList()); testee.checkStatus(statuses, 10000, StatusCheckType.HISTORY); assertThat(testee.historyCheckEnabled).isFalse(); }
@Test public void shouldCallDownloader() { testee.historyCheckEnabled = true; testee.lastDownload = Instant.now(); List<FileDownloadStatus> statuses = Collections.singletonList(FileDownloadStatus.REQUESTED); List<FileDownloadEntity> downloadsWaitingForUpdate = Collections.singletonList(new FileDownloadEntity()); when(downloadRepository.findByStatusInAndTimeAfterOrderByTimeDesc(eq(statuses), any())).thenReturn(downloadsWaitingForUpdate); List<FileDownloadEntity> downloadsReturnedFromDownloader = Collections.singletonList(new FileDownloadEntity()); when(downloaderMock.checkForStatusUpdates(any(),eq(StatusCheckType.HISTORY))).thenReturn(downloadsReturnedFromDownloader); testee.checkStatus(statuses, 10000, StatusCheckType.HISTORY); verify(downloaderMock).checkForStatusUpdates(downloadsWaitingForUpdate, StatusCheckType.HISTORY); verify(downloadRepository).saveAll(downloadsReturnedFromDownloader); }
|
DownloadStatusUpdater { @EventListener public void onNzbDownloadEvent(FileDownloadEvent downloadEvent) { if (!configProvider.getBaseConfig().getMain().isKeepHistory()) { return; } lastDownload = Instant.now(); queueCheckEnabled = true; historyCheckEnabled = true; logger.debug(LoggingMarkers.DOWNLOAD_STATUS_UPDATE, "Received download event. Will enable status updates for the next {} minutes", (MIN_SECONDS_SINCE_LAST_DOWNLOAD_TO_CHECK_STATUSES / 60)); } @HydraTask(configId = "downloadHistoryCheck", name = "Download history check", interval = TEN_MINUTES_MS) @Transactional void checkHistoryStatus(); @HydraTask(configId = "downloadQueueCheck", name = "Download queue check", interval = TEN_SECONDS_MS) @Transactional void checkQueueStatus(); @EventListener void onNzbDownloadEvent(FileDownloadEvent downloadEvent); }
|
@Test public void shouldSetEnabledOnDownloadEvent() { testee.queueCheckEnabled = false; testee.lastDownload = null; testee.onNzbDownloadEvent(new FileDownloadEvent(new FileDownloadEntity(), new SearchResultEntity())); assertThat(testee.queueCheckEnabled).isTrue(); assertThat(testee.lastDownload).isNotNull(); }
|
RssItemBuilder { public static RssItemBuilder builder() { RssItemBuilder builder = new RssItemBuilder(); return builder; } private RssItemBuilder(); static RssItemBuilder builder(); static RssItemBuilder builder(String title); RssItemBuilder title(String title); RssItemBuilder link(String link); RssItemBuilder size(long size); RssItemBuilder pubDate(Instant pubDate); RssItemBuilder rssGuid(NewznabXmlGuid rssGuid); RssItemBuilder description(String description); RssItemBuilder comments(String comments); RssItemBuilder category(String category); RssItemBuilder grabs(Integer grabs); RssItemBuilder newznabAttributes(List<NewznabAttribute> newznabAttributes); RssItemBuilder torznabAttributes(List<NewznabAttribute> torznabAttributes); RssItemBuilder enclosure(NewznabXmlEnclosure enclosure); RssItemBuilder hasNfo(boolean hasNfo); RssItemBuilder poster(String poster); RssItemBuilder group(String group); RssItemBuilder linksFromBaseUrl(String baseUrl); RssItemBuilder categoryNewznab(String... categories); NewznabXmlItem build(); }
|
@Test public void testBuilder() { NewznabXmlItem item = RssItemBuilder.builder("title") .group("group") .poster("poster") .size(1000L) .category("category") .categoryNewznab("5000") .description("desc") .link("link") .hasNfo(true) .grabs(10).build(); Map<String, String> attributes = item.getNewznabAttributes().stream().collect(Collectors.toMap(NewznabAttribute::getName, NewznabAttribute::getValue)); assertEquals("group", attributes.get("group")); assertEquals("poster", attributes.get("poster")); assertEquals("5000", attributes.get("category")); assertEquals("1", attributes.get("nfo")); assertEquals(Long.valueOf(1000), item.getEnclosure().getLength()); assertEquals("desc", item.getDescription()); assertEquals("category", item.getCategory()); assertEquals("link", item.getEnclosure().getUrl()); }
|
DownloaderStatus { public List<Long> getDownloadingRatesInKilobytes() { if (downloadingRatesInKilobytes.isEmpty() || downloadingRatesInKilobytes.size() < 5) { return downloadingRatesInKilobytes; } if (downloadingRatesInKilobytes.get(downloadingRatesInKilobytes.size() - 1) / (float) 10 > downloadingRatesInKilobytes.get(downloadingRatesInKilobytes.size() - 2)) { if (downloadingRatesInKilobytes.get(downloadingRatesInKilobytes.size() - 1) / (float) 10 > downloadingRatesInKilobytes.get(downloadingRatesInKilobytes.size() - 3)) { return downloadingRatesInKilobytes.subList(0, downloadingRatesInKilobytes.size() - 1); } } return downloadingRatesInKilobytes; } Long getLastDownloadRate(); String getDownloadRateFormatted(); String getRemainingSizeFormatted(); List<Long> getDownloadingRatesInKilobytes(); }
|
@Test public void getDownloadingRatesInKilobytes() { List<Long> list = new ArrayList<>(Arrays.asList(100L, 100L, 100L, 100L, 100L, 100L, 100L)); testee.setDownloadingRatesInKilobytes(list); assertThat(testee.getDownloadingRatesInKilobytes()).containsExactlyElementsOf(list); list = new ArrayList<>(Arrays.asList(100L, 100L, 100L, 100L, 100L, 100L, 100L, 50000L)); testee.setDownloadingRatesInKilobytes(list); assertThat(testee.getDownloadingRatesInKilobytes()).containsExactly(100L, 100L, 100L, 100L, 100L, 100L, 100L); list = new ArrayList<>(Arrays.asList(100L, 100L, 100L, 100L, 100L, 100L, 100L, 50000L, 50000L)); testee.setDownloadingRatesInKilobytes(list); assertThat(testee.getDownloadingRatesInKilobytes()).containsExactlyElementsOf(list); }
|
OutOfMemoryDetector implements ProblemDetector { @Override public void executeCheck() { try { AtomicReference<State> state = new AtomicReference<>(); state.set(State.LOOKING_FOR_OOM); AtomicReference<String> lastTimeStampLine = new AtomicReference<>(); Files.lines(logContentProvider.getCurrentLogfile(false).toPath()).forEach(line -> { if (line.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}.*")) { if (state.get() == State.LOOKING_FOR_OOM) { lastTimeStampLine.set(line); } if (state.get() == State.LOOKING_FOR_OOM_END) { state.set(State.LOOKING_FOR_OOM); } return; } if (line.contains("java.lang.OutOfMemoryError")) { if (state.get() == State.LOOKING_FOR_OOM) { String key = "outOfMemoryDetected-" + lastTimeStampLine.get(); boolean alreadyDetected = genericStorage.get(key, String.class).isPresent(); if (!alreadyDetected) { logger.warn("The log indicates that the process ran out of memory. Please increase the XMX value in the main config and restart."); genericStorage.save(key, true); genericStorage.save("outOfMemoryDetected", true); } state.set(State.LOOKING_FOR_OOM_END); } } }); } catch (IOException e) { logger.warn("Unable to read log file: " + e.getMessage()); } catch (Exception e) { logger.warn("Unable to detect problems in log file", e); } } @Override void executeCheck(); }
|
@Ignore @Test public void executeCheck() throws Exception { MockitoAnnotations.initMocks(this); final Path tempFile = Files.createTempFile("nzbhydra", ".log"); try { tempFile.toFile().delete(); Files.copy(getClass().getResourceAsStream("logWithOom.log"), tempFile); } catch (Exception e) { return; } when(logContentProviderMock.getCurrentLogfile(false)).thenReturn(tempFile.toFile()); testee.executeCheck(); verify(genericStorageMock, times(4)).save(stringArgumentCaptor.capture(), objectArgumentCaptor.capture()); assertThat(stringArgumentCaptor.getAllValues().get(0)).isEqualTo("outOfMemoryDetected-2018-11-09 00:17:46 database: close"); assertThat(stringArgumentCaptor.getAllValues().get(1)).isEqualTo("outOfMemoryDetected"); assertThat(stringArgumentCaptor.getAllValues().get(2)).isEqualTo("outOfMemoryDetected-2018-11-09 11:11:46 database: close"); assertThat(stringArgumentCaptor.getAllValues().get(3)).isEqualTo("outOfMemoryDetected"); assertThat(objectArgumentCaptor.getAllValues().get(0)).isEqualTo(true); assertThat(objectArgumentCaptor.getAllValues().get(1)).isEqualTo(true); }
|
BackupTask { @HydraTask(configId = "Backup", name = "Backup", interval = HOUR) public void createBackup() { boolean backupEnabled = configProvider.getBaseConfig().getMain().getBackupEveryXDays().isPresent(); if (!backupEnabled) { logger.debug("Automatic backup is disabled"); return; } int backupEveryXDays = configProvider.getBaseConfig().getMain().getBackupEveryXDays().get(); Optional<LocalDateTime> firstStartOptional = genericStorage.get("FirstStart", LocalDateTime.class); if (!firstStartOptional.isPresent()) { logger.debug("First start date time not set (for some reason), aborting backup"); return; } long daysSinceFirstStart = ChronoUnit.DAYS.between(firstStartOptional.get(), LocalDateTime.now(clock)); if (daysSinceFirstStart < backupEveryXDays) { logger.debug("{} days since first start but backup is to be executed every {} days", daysSinceFirstStart, backupEveryXDays); return; } Optional<BackupData> backupData = genericStorage.get(KEY, BackupData.class); if (!backupData.isPresent()) { logger.debug("Executing first backup: {} days since first start and backup is to be executed every {} days", daysSinceFirstStart, backupEveryXDays); executeBackup(); return; } long daysSinceLastBackup = ChronoUnit.DAYS.between(backupData.get().getLastBackup(), LocalDateTime.now(clock)); if (daysSinceLastBackup >= backupEveryXDays) { logger.debug("Executing backup: {} days since last backup and backup is to be executed every {} days", daysSinceLastBackup, backupEveryXDays); executeBackup(); } } @HydraTask(configId = "Backup", name = "Backup", interval = HOUR) void createBackup(); static final String KEY; }
|
@Test public void shouldCreateBackupIfEnabledAndNoBackupExecutedYet() throws Exception { when(genericStorage.get("FirstStart", LocalDateTime.class)).thenReturn(Optional.of(LocalDateTime.now(testee.clock).minus(200, ChronoUnit.DAYS))); testee.createBackup(); verify(backupAndRestore).backup(); verify(genericStorage).save(eq("BackupData"), backupDataArgumentCaptor.capture()); BackupData backupData = backupDataArgumentCaptor.getValue(); assertThat(backupData.getLastBackup(), is(LocalDateTime.now(testee.clock))); }
@Test public void shouldCreateBackupIfEnabledAndLastBackupAndStartupWasNotToday() throws Exception { when(genericStorage.get("FirstStart", LocalDateTime.class)).thenReturn(Optional.of(LocalDateTime.now(testee.clock).minus(200, ChronoUnit.DAYS))); when(genericStorage.get(BackupTask.KEY, BackupData.class)).thenReturn(Optional.of(new BackupData(LocalDateTime.now(testee.clock).minus(8, ChronoUnit.DAYS)))); testee.createBackup(); verify(backupAndRestore).backup(); verify(genericStorage).save(eq("BackupData"), backupDataArgumentCaptor.capture()); BackupData backupData = backupDataArgumentCaptor.getValue(); assertThat(backupData.getLastBackup(), is(LocalDateTime.now(testee.clock))); }
@Test public void shouldNotCreateBackupIfEnabledAndLastBackupWasTooRecently() throws Exception { when(genericStorage.get("FirstStart", LocalDateTime.class)).thenReturn(Optional.of(LocalDateTime.now(testee.clock).minus(200, ChronoUnit.DAYS))); when(genericStorage.get(BackupTask.KEY, BackupData.class)).thenReturn(Optional.of(new BackupData(LocalDateTime.now(testee.clock).minus(5, ChronoUnit.DAYS)))); testee.createBackup(); verify(backupAndRestore, never()).backup(); verify(genericStorage, never()).save(eq("BackupData"), backupDataArgumentCaptor.capture()); }
@Test public void shouldNotCreateBackupIfDisabled() throws Exception { config.getMain().setBackupEveryXDays(null); testee.createBackup(); verify(backupAndRestore, never()).backup(); }
@Test public void shouldNotCreateBackupIfStartedToday() throws Exception { when(genericStorage.get("FirstStart", LocalDateTime.class)).thenReturn(Optional.of(LocalDateTime.now(testee.clock))); testee.createBackup(); verify(backupAndRestore, never()).backup(); }
@Test public void shouldNotCreateBackupIfLastBackupWasToday() throws Exception { when(genericStorage.get("BackupData", BackupData.class)).thenReturn(Optional.of(new BackupData(LocalDateTime.now(testee.clock)))); testee.createBackup(); verify(backupAndRestore, never()).backup(); }
|
SensitiveDataRemovingPatternLayoutEncoder extends PatternLayoutEncoder { protected String removeSensitiveData(String txt) { return txt.replaceAll("(?i)(username|apikey|password)(=|:|%3D)([^&\\s]{2,})", "$1$2<$1>") .replaceAll("(\"name\" ?: ?\"apiKey\",(\\s*\"label\": ?\".*\",)?\\s*\"value\" ?: \")([^\"\\s*]*)", "$1<apikey>") .replaceAll("(\"name\" ?: ?\"baseUrl\",(\\s*\"label\": ?\".*\",)?\\s*\"value\" ?: \")([^\"\\s*]*)", "$1<url>") ; } Charset getCharset(); void setCharset(Charset charset); byte[] encode(ILoggingEvent event); }
|
@Test public void shouldRemoveSensitiveData() { SensitiveDataRemovingPatternLayoutEncoder encoder = new SensitiveDataRemovingPatternLayoutEncoder(); String result = encoder.removeSensitiveData("https: assertThat(result).isEqualTo("https: result = encoder.removeSensitiveData("https: assertThat(result).isEqualTo("https: result = encoder.removeSensitiveData("http: assertThat(result).isEqualTo("http: result = encoder.removeSensitiveData("https: assertThat(result).isEqualTo("https: result = encoder.removeSensitiveData("https: assertThat(result).isEqualTo("https: result = encoder.removeSensitiveData("https: assertThat(result).isEqualTo("https: result = encoder.removeSensitiveData("https: assertThat(result).isEqualTo("https: result = encoder.removeSensitiveData("https: assertThat(result).isEqualTo("https: final String darrApiKeyField = " \"name\": \"apiKey\",\n" + " \"label\": \"API Key\",\n" + " \"value\": \"12345678\","; result = encoder.removeSensitiveData(darrApiKeyField); assertThat(result).isEqualTo(darrApiKeyField.replace("12345678", "<apikey>")); final String darrUrlField = " \"name\": \"baseUrl\",\n" + " \"label\": \"URL\",\n" + " \"value\": \"http: result = encoder.removeSensitiveData(darrUrlField); assertThat(result).isEqualTo(darrUrlField.replace("http: final String darrUrlField2 = "\"name\" : \"baseUrl\",\n" + " \"value\" : \"http: result = encoder.removeSensitiveData(darrUrlField2); assertThat(result).isEqualTo(darrUrlField2.replace("http: final String darrUrlField3 = "\"name\" : \"baseUrl\",\n" + " \"value\" : \"http: result = encoder.removeSensitiveData(darrUrlField3); assertThat(result).isEqualTo(darrUrlField3.replace("http: }
|
LogAnonymizer { public String getAnonymizedLog(String log) { for (UserAuthConfig userAuthConfig : configProvider.getBaseConfig().getAuth().getUsers()) { logger.debug("Removing username from log"); log = log.replaceAll("(?i)(user|username)([=:])" + userAuthConfig.getUsername(), "$1$2<USERNAME>"); } for (IndexerConfig indexerConfig : configProvider.getBaseConfig().getIndexers()) { if (Strings.isNullOrEmpty(indexerConfig.getApiKey()) || indexerConfig.getApiKey().length() < 5) { continue; } logger.debug("Removing API key for indexer {} from log", indexerConfig.getName()); log = log.replace(indexerConfig.getApiKey(), "<APIKEY>"); } logger.debug("Removing URL username/password from log"); log = log.replaceAll("(https?):\\/\\/((.+?)(:(.+?)|)@)", "$1: logger.debug("Removing cookies from log"); log = log.replaceAll("Set-Cookie: (\\w+)=(\\w)+;?", "Set-Cookie: $1:<HIDDEN>"); log = log.replaceAll("remember-me=(\\w)+;?", "remember-me=$1:<HIDDEN>"); log = log.replaceAll("Auth-Token=(\\w)+;?", "Auth-Token=$1:<HIDDEN>"); log = log.replaceAll("HYDRA-XSRF-TOKEN=([\\w\\-])+;?", "HYDRA-XSRF-TOKEN=$1:<HIDDEN>"); logger.debug("Removing base path from log"); log = log.replace(new File("").getAbsolutePath(), "<BASEPATH>"); log = removeIpsFromLog(log); return log; } String getAnonymizedLog(String log); }
|
@Test public void shouldAnonymizeIPs() throws Exception { String toAnonymize = "192.168.0.1 127.0.0.1 2001:db8:3:4:: 64:ff9b:: 2001:db8:a0b:12f0::1 2001:0db8:0a0b:12f0:0000:0000:0000:0001"; String anonymized = testee.getAnonymizedLog(toAnonymize); Arrays.stream(toAnonymize.split(" ")).skip(2).forEach(x -> { Assertions.assertThat(anonymized).doesNotContain(x); }); Assertions.assertThat(anonymized).contains("192.168.0.1"); Assertions.assertThat(anonymized).contains("<localhost>"); }
@Test public void shouldAnonymizeUsernameFromUrl() throws Exception { String anonymized = testee.getAnonymizedLog("http: assertThat(anonymized, is("http: }
@Test public void shouldAnonymizeUsernameFromConfig() throws Exception { String anonymized = testee.getAnonymizedLog("user=someusername USER:someusername username=someusername username:someusername"); assertThat(anonymized, is("user=<USERNAME> USER:<USERNAME> username=<USERNAME> username:<USERNAME>")); }
@Test public void shouldAnonymizeApikeysFromConfig() throws Exception { String anonymized = testee.getAnonymizedLog("r=apikey"); assertThat(anonymized, is("r=<APIKEY>")); }
@Test public void shouldAnonymizeCookiesFromConfig() throws Exception { String anonymized = testee.getAnonymizedLog("Cookies: Parsing b[]: remember-me=MTAI4MjHY0MjcXxMTpjM2U0Zjk3OWQwMjk0; Auth-Type=http; Auth-Token=C8wSA1AXvpFVjXCRGKryWtIIZS2TRqf69aZb; HYDRA-XSRF-TOKEN=1a0f551f-2178-4ad7-a0b5-3af8f77675e2"); assertThat(anonymized, is("Cookies: Parsing b[]: remember-me=0:<HIDDEN> Auth-Type=http; Auth-Token=b:<HIDDEN> HYDRA-XSRF-TOKEN=2:<HIDDEN>")); }
|
IndexerForSearchSelector { protected boolean checkIndexerSelectedByUser(Indexer indexer) { boolean indexerNotSelectedByUser = (searchRequest.getIndexers().isPresent() && !searchRequest.getIndexers().get().isEmpty()) && !searchRequest.getIndexers().get().contains(indexer.getName()); if (indexerNotSelectedByUser) { logger.info(String.format("Not using %s because it was not selected by the user", indexer.getName())); notSelectedIndersWithReason.put(indexer, "Not selected by the user"); return false; } return true; } IndexerForSearchSelection pickIndexers(SearchRequest searchRequest); static final Pattern SCHEDULER_PATTERN; }
|
@Test public void shouldCheckIfSelectedByUser() { when(searchModuleProviderMock.getIndexers()).thenReturn(Arrays.asList(indexer)); when(searchRequest.getSource()).thenReturn(SearchSource.INTERNAL); when(searchRequest.getIndexers()).thenReturn(Optional.of(Sets.newSet("anotherIndexer"))); assertFalse(testee.checkIndexerSelectedByUser(indexer)); when(searchRequest.getSource()).thenReturn(SearchSource.API); assertFalse(testee.checkIndexerSelectedByUser(indexer)); when(searchRequest.getIndexers()).thenReturn(Optional.of(Sets.newSet("indexer"))); when(searchRequest.getSource()).thenReturn(SearchSource.INTERNAL); assertTrue(testee.checkIndexerSelectedByUser(indexer)); when(searchRequest.getSource()).thenReturn(SearchSource.API); assertTrue(testee.checkIndexerSelectedByUser(indexer)); }
|
CategoryConverter implements AttributeConverter<Category, String> { @Override public String convertToDatabaseColumn(Category category) { if (category == null) { return null; } return category.getName(); } @Autowired void setCategoryProvider(CategoryProvider categoryProvider); @Override String convertToDatabaseColumn(Category category); @Override Category convertToEntityAttribute(String categoryName); }
|
@Test public void convertToDatabaseColumn() throws Exception { Category category = new Category(); category.setName("name"); assertThat(testee.convertToDatabaseColumn(category), is("name")); }
|
CategoryConverter implements AttributeConverter<Category, String> { @Override public Category convertToEntityAttribute(String categoryName) { return categoryProvider.getByInternalName(categoryName); } @Autowired void setCategoryProvider(CategoryProvider categoryProvider); @Override String convertToDatabaseColumn(Category category); @Override Category convertToEntityAttribute(String categoryName); }
|
@Test public void convertToEntityAttribute() throws Exception { Category category = new Category(); when(categoryProviderMock.getByInternalName("name")).thenReturn(category); assertThat(testee.convertToEntityAttribute("name"), is(category)); }
|
NewznabXmlTransformer { NewznabXmlItem buildRssItem(SearchResultItem searchResultItem, boolean isNzb) { NewznabXmlItem rssItem = new NewznabXmlItem(); String link = nzbHandler.getDownloadLinkForResults(searchResultItem.getSearchResultId(), false, isNzb ? DownloadType.NZB : DownloadType.TORRENT); rssItem.setLink(link); rssItem.setTitle(searchResultItem.getTitle()); rssItem.setRssGuid(new NewznabXmlGuid(String.valueOf(searchResultItem.getGuid()), false)); rssItem.setSize(searchResultItem.getSize()); if (searchResultItem.getPubDate() != null) { rssItem.setPubDate(searchResultItem.getPubDate()); } else { rssItem.setPubDate(searchResultItem.getBestDate()); } searchResultItem.getAttributes().put("guid", String.valueOf(searchResultItem.getSearchResultId())); List<NewznabAttribute> newznabAttributes = searchResultItem.getAttributes().entrySet().stream().map(attribute -> new NewznabAttribute(attribute.getKey(), attribute.getValue())).sorted(Comparator.comparing(NewznabAttribute::getName)).collect(Collectors.toList()); if (searchResultItem.getIndexer() != null) { newznabAttributes.add(new NewznabAttribute("hydraIndexerScore", String.valueOf(searchResultItem.getIndexer().getConfig().getScore()))); newznabAttributes.add(new NewznabAttribute("hydraIndexerHost", getIndexerHost(searchResultItem))); newznabAttributes.add(new NewznabAttribute("hydraIndexerName", String.valueOf(searchResultItem.getIndexer().getName()))); } String resultType; if (isNzb) { rssItem.setNewznabAttributes(newznabAttributes); resultType = APPLICATION_TYPE_NZB; } else { rssItem.setTorznabAttributes(newznabAttributes); resultType = APPLICATION_TYPE_TORRENT; } rssItem.setEnclosure(new NewznabXmlEnclosure(link, searchResultItem.getSize(), resultType)); rssItem.setComments(searchResultItem.getCommentsLink()); rssItem.setDescription(searchResultItem.getDescription()); rssItem.setCategory(configProvider.getBaseConfig().getSearching().isUseOriginalCategories() ? searchResultItem.getOriginalCategory() : searchResultItem.getCategory().getName()); return rssItem; } }
|
@Test public void shouldUseCorrectApplicationType() { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); SearchResultItem searchResultItem = new SearchResultItem(); searchResultItem.setIndexer(indexerMock); searchResultItem.setCategory(new Category()); searchRequest.setDownloadType(DownloadType.NZB); NewznabXmlItem item = testee.buildRssItem(searchResultItem, searchRequest.getDownloadType() == DownloadType.NZB); assertThat(item.getEnclosure().getType()).isEqualTo("application/x-nzb"); searchRequest.setDownloadType(DownloadType.TORRENT); item = testee.buildRssItem(searchResultItem, searchRequest.getDownloadType() == DownloadType.NZB); assertThat(item.getEnclosure().getType()).isEqualTo("application/x-bittorrent"); }
|
CapsGenerator { CapsXmlCategories getCapsXmlCategories() { if (configProvider.getBaseConfig().getSearching().isTransformNewznabCategories()) { Map<Integer, CapsXmlCategory> mainXmlCategoriesMap = new HashMap<>(); Set<String> alreadyAdded = new HashSet<>(); for (Category category : configProvider.getBaseConfig().getCategoriesConfig().getCategories()) { category.getNewznabCategories().stream().flatMap(Collection::stream).sorted(Comparator.naturalOrder()).filter(x -> x % 1000 == 0).forEach(x -> { CapsXmlCategory xmlCategory = new CapsXmlCategory(x, category.getName(), new ArrayList<>()); mainXmlCategoriesMap.put(x, xmlCategory); alreadyAdded.add(category.getName()); }); } for (Category category : configProvider.getBaseConfig().getCategoriesConfig().getCategories()) { List<Integer> subCategories = category.getNewznabCategories().stream().flatMap(Collection::stream).filter(x -> x % 1000 != 0) .sorted(Comparator.naturalOrder()) .collect(Collectors.toList()); for (Integer subCategory : subCategories) { if (alreadyAdded.contains(category.getName())) { continue; } int itsMainCategoryNumber = subCategory / 1000 * 1000; if (mainXmlCategoriesMap.containsKey(itsMainCategoryNumber)) { boolean alreadyPresent = mainXmlCategoriesMap.get(itsMainCategoryNumber).getSubCategories().stream().anyMatch(x -> x.getName().equals(category.getName())); if (!alreadyPresent) { mainXmlCategoriesMap.get(itsMainCategoryNumber).getSubCategories().add(new CapsXmlCategory(subCategory, category.getName(), new ArrayList<>())); } } else { mainXmlCategoriesMap.put(subCategory, new CapsXmlCategory(subCategory, category.getName(), new ArrayList<>())); } alreadyAdded.add(category.getName()); } } ArrayList<CapsXmlCategory> categories = new ArrayList<>(mainXmlCategoriesMap.values()); categories.sort(Comparator.comparing(CapsXmlCategory::getId)); return new CapsXmlCategories(categories); } else { List<CapsXmlCategory> mainCategories = new ArrayList<>(); mainCategories.add(new CapsXmlCategory(1000, "Console", Arrays.asList( new CapsXmlCategory(1010, "NDS"), new CapsXmlCategory(1020, "PSP"), new CapsXmlCategory(1030, "Wii"), new CapsXmlCategory(1040, "XBox"), new CapsXmlCategory(1050, "Xbox 360"), new CapsXmlCategory(1060, "Wiiware"), new CapsXmlCategory(1070, "Xbox 360 DLC") ))); mainCategories.add(new CapsXmlCategory(2000, "Movies", Arrays.asList( new CapsXmlCategory(2010, "Foreign"), new CapsXmlCategory(2020, "Other"), new CapsXmlCategory(2030, "SD"), new CapsXmlCategory(2040, "HD"), new CapsXmlCategory(2045, "UHD"), new CapsXmlCategory(2050, "Bluray"), new CapsXmlCategory(2060, "3D") ))); mainCategories.add(new CapsXmlCategory(3000, "Audio", Arrays.asList( new CapsXmlCategory(3010, "MP3"), new CapsXmlCategory(3020, "Video"), new CapsXmlCategory(3030, "Audiobook"), new CapsXmlCategory(3040, "Lossless") ))); mainCategories.add(new CapsXmlCategory(4000, "PC", Arrays.asList( new CapsXmlCategory(4010, "0day"), new CapsXmlCategory(4020, "ISO"), new CapsXmlCategory(4030, "Mac"), new CapsXmlCategory(4040, "Mobile Oher"), new CapsXmlCategory(4050, "Games"), new CapsXmlCategory(4060, "Mobile IOS"), new CapsXmlCategory(4070, "Mobile Android") ))); mainCategories.add(new CapsXmlCategory(5000, "TV", Arrays.asList( new CapsXmlCategory(5020, "Foreign"), new CapsXmlCategory(5030, "SD"), new CapsXmlCategory(5040, "HD"), new CapsXmlCategory(5045, "UHD"), new CapsXmlCategory(5050, "Other"), new CapsXmlCategory(5060, "Sport"), new CapsXmlCategory(5070, "Anime"), new CapsXmlCategory(5080, "Documentary") ))); mainCategories.add(new CapsXmlCategory(6000, "XXX", Arrays.asList( new CapsXmlCategory(6010, "DVD"), new CapsXmlCategory(6020, "WMV"), new CapsXmlCategory(6030, "XviD"), new CapsXmlCategory(6040, "x264"), new CapsXmlCategory(6050, "Pack"), new CapsXmlCategory(6060, "Imgset"), new CapsXmlCategory(6070, "Other") ))); mainCategories.add(new CapsXmlCategory(7000, "Books", Arrays.asList( new CapsXmlCategory(7010, "Mags"), new CapsXmlCategory(7020, "Ebook"), new CapsXmlCategory(7030, "COmics") ))); mainCategories.add(new CapsXmlCategory(8000, "Other", Arrays.asList( new CapsXmlCategory(8010, "Misc") ))); return new CapsXmlCategories(mainCategories); } } }
|
@Test public void shouldGenerateCategoriesFromConfig() throws Exception { CapsXmlCategories xmlCategories = testee.getCapsXmlCategories(); assertThat(xmlCategories.getCategories().size()).isEqualTo(3); assertThat(xmlCategories.getCategories().get(0).getName()).isEqualTo("Misc"); assertThat(xmlCategories.getCategories().get(1).getName()).isEqualTo("Movies"); assertThat(xmlCategories.getCategories().get(1).getSubCategories().size()).isEqualTo(1); assertThat(xmlCategories.getCategories().get(1).getSubCategories().get(0).getName()).isEqualTo("Movies HD"); assertThat(xmlCategories.getCategories().get(2).getName()).isEqualTo("Musc"); }
|
ExternalApi { @RequestMapping(value = {"/api", "/rss", "/torznab/api", "/torznab/api/{indexerName}", "/api/{indexerName}"}, consumes = MediaType.ALL_VALUE) public ResponseEntity<? extends Object> api(NewznabParameters params, @PathVariable(value = "indexerName", required = false) String indexerName, @PathVariable(value = "mock", required = false) String mock) throws Exception { int searchRequestId = random.nextInt(100000); if (params.getT() != null && params.getT().isSearch()) { MDC.put("SEARCH", String.valueOf(searchRequestId)); } NewznabResponse.SearchType searchType = getSearchType(); logger.info("Received external {} API call: {}", searchType.name().toLowerCase(), params); if (!noApiKeyNeeded && !Objects.equals(params.getApikey(), configProvider.getBaseConfig().getMain().getApiKey())) { logger.error("Received API call with wrong API key"); throw new WrongApiKeyException("Wrong api key"); } if (!params.getIndexers().isEmpty() && indexerName != null) { logger.error("Received call with parameters set in path and request variables"); NewznabXmlError error = new NewznabXmlError("200", "Received call with parameters set in path and request variables"); return new ResponseEntity<Object>(error, HttpStatus.OK); } else if (indexerName != null) { params.setIndexers(Sets.newHashSet(indexerName)); } if (params.getT() == ActionAttribute.CAPS) { return capsGenerator.getCaps(params.getO(), searchType); } if (Stream.of(ActionAttribute.SEARCH, ActionAttribute.BOOK, ActionAttribute.TVSEARCH, ActionAttribute.MOVIE).anyMatch(x -> x == params.getT())) { if (inMockingMode) { logger.debug("Will mock results for this request"); return new ResponseEntity<>(mockSearch.mockSearch(params, getSearchType() == NewznabResponse.SearchType.NEWZNAB), HttpStatus.OK); } if (params.getCachetime() != null || configProvider.getBaseConfig().getSearching().getGlobalCacheTimeMinutes().isPresent()) { return handleCachingSearch(params, searchType, searchRequestId); } NewznabResponse searchResult = search(params, searchRequestId); HttpHeaders httpHeaders = setSearchTypeAndGetHeaders(params, searchResult); return new ResponseEntity<>(searchResult, httpHeaders, HttpStatus.OK); } if (params.getT() == ActionAttribute.GET) { return getNzb(params); } logger.error("Incorrect API request: {}", params); NewznabXmlError error = new NewznabXmlError("200", "Unknown or incorrect parameter"); return new ResponseEntity<Object>(error, HttpStatus.OK); } @RequestMapping(value = {"/api", "/rss", "/torznab/api", "/torznab/api/{indexerName}", "/api/{indexerName}"}, consumes = MediaType.ALL_VALUE) ResponseEntity<? extends Object> api(NewznabParameters params, @PathVariable(value = "indexerName", required = false) String indexerName, @PathVariable(value = "mock", required = false) String mock); static void setInMockingMode(boolean newValue); @ExceptionHandler(value = ExternalApiException.class) NewznabXmlError handler(ExternalApiException e); @ExceptionHandler(value = Exception.class) ResponseEntity handleUnexpectedError(Exception e); }
|
@Test public void shouldUseCorrectHeaders() throws Exception { NewznabJsonRoot jsonRoot = new NewznabJsonRoot(); when(newznabJsonTransformerMock.transformToRoot(any(), any(), anyInt(), any())).thenReturn(jsonRoot); NewznabParameters parameters = new NewznabParameters(); parameters.setQ("q1"); parameters.setApikey("apikey"); parameters.setT(ActionAttribute.SEARCH); parameters.setO(OutputType.JSON); ResponseEntity<?> responseEntity = testee.api(parameters, null, null); assertThat(responseEntity.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON_UTF8); NewznabXmlRoot xmlRoot = new NewznabXmlRoot(); when(newznabXmlTransformerMock.getRssRoot(any(), any(), anyInt(), any())).thenReturn(xmlRoot); parameters.setO(OutputType.XML); responseEntity = testee.api(parameters, null, null); assertThat(responseEntity.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_XML); }
|
BaseConfig extends ValidatingConfig<BaseConfig> { @Override public ConfigValidationResult validateConfig(BaseConfig oldConfig, BaseConfig newConfig, BaseConfig newBaseConfig) { ConfigValidationResult configValidationResult = new ConfigValidationResult(); ConfigValidationResult authValidation = newConfig.getAuth().validateConfig(oldConfig, newConfig.getAuth(), newBaseConfig); configValidationResult.getErrorMessages().addAll(authValidation.getErrorMessages()); configValidationResult.getWarningMessages().addAll(authValidation.getWarningMessages()); configValidationResult.setRestartNeeded(configValidationResult.isRestartNeeded() || authValidation.isRestartNeeded()); ConfigValidationResult categoriesValidation = newConfig.getCategoriesConfig().validateConfig(oldConfig, newConfig.getCategoriesConfig(), newBaseConfig); configValidationResult.getErrorMessages().addAll(categoriesValidation.getErrorMessages()); configValidationResult.getWarningMessages().addAll(categoriesValidation.getWarningMessages()); configValidationResult.setRestartNeeded(configValidationResult.isRestartNeeded() || categoriesValidation.isRestartNeeded()); ConfigValidationResult mainValidation = newConfig.getMain().validateConfig(oldConfig, newConfig.getMain(), newBaseConfig); configValidationResult.getErrorMessages().addAll(mainValidation.getErrorMessages()); configValidationResult.getWarningMessages().addAll(mainValidation.getWarningMessages()); configValidationResult.setRestartNeeded(configValidationResult.isRestartNeeded() || mainValidation.isRestartNeeded()); ConfigValidationResult searchingValidation = newConfig.getSearching().validateConfig(oldConfig, newConfig.getSearching(), newBaseConfig); configValidationResult.getErrorMessages().addAll(searchingValidation.getErrorMessages()); configValidationResult.getWarningMessages().addAll(searchingValidation.getWarningMessages()); configValidationResult.setRestartNeeded(configValidationResult.isRestartNeeded() || searchingValidation.isRestartNeeded()); ConfigValidationResult downloadingValidation = newConfig.getDownloading().validateConfig(oldConfig, newConfig.getDownloading(), newBaseConfig); configValidationResult.getErrorMessages().addAll(downloadingValidation.getErrorMessages()); configValidationResult.getWarningMessages().addAll(downloadingValidation.getWarningMessages()); configValidationResult.setRestartNeeded(configValidationResult.isRestartNeeded() || downloadingValidation.isRestartNeeded()); for (IndexerConfig indexer : newConfig.getIndexers()) { ConfigValidationResult indexerValidation = indexer.validateConfig(oldConfig, indexer, newBaseConfig); configValidationResult.getErrorMessages().addAll(indexerValidation.getErrorMessages()); configValidationResult.getWarningMessages().addAll(indexerValidation.getWarningMessages()); configValidationResult.setRestartNeeded(configValidationResult.isRestartNeeded() || indexerValidation.isRestartNeeded()); } validateIndexers(newConfig, configValidationResult); if (!configValidationResult.getErrorMessages().isEmpty()) { logger.warn("Config validation returned errors:\n" + Joiner.on("\n").join(configValidationResult.getErrorMessages())); } if (!configValidationResult.getWarningMessages().isEmpty()) { logger.warn("Config validation returned warnings:\n" + Joiner.on("\n").join(configValidationResult.getWarningMessages())); } if (configValidationResult.isRestartNeeded()) { logger.warn("Settings were changed that require a restart to become effective"); } configValidationResult.setOk(configValidationResult.getErrorMessages().isEmpty()); return configValidationResult; } void replace(BaseConfig newConfig); void save(boolean saveInstantly); @PostConstruct void init(); void load(); @EventListener void onShutdown(ShutdownEvent event); @Override ConfigValidationResult validateConfig(BaseConfig oldConfig, BaseConfig newConfig, BaseConfig newBaseConfig); @Override BaseConfig prepareForSaving(BaseConfig oldBaseConfig); @Override BaseConfig updateAfterLoading(); @Override BaseConfig initializeNewConfig(); static boolean isProductive; }
|
@Test public void shouldValidateIndexers() { IndexerConfig indexerConfigMock = mock(IndexerConfig.class); when(indexerConfigMock.validateConfig(any(), any(), any())).thenReturn(new ValidatingConfig.ConfigValidationResult(true, false, new ArrayList<String>(), new ArrayList<String>())); testee.getIndexers().add(indexerConfigMock); testee.validateConfig(new BaseConfig(), testee, new BaseConfig()); verify(indexerConfigMock).validateConfig(any(), any(), any()); }
@Test public void shouldRecognizeDuplicateIndexerNames() { IndexerConfig indexerConfigMock = mock(IndexerConfig.class); when(indexerConfigMock.getName()).thenReturn("name"); IndexerConfig indexerConfigMock2 = mock(IndexerConfig.class); when(indexerConfigMock2.getName()).thenReturn("name"); when(indexerConfigMock.validateConfig(any(), any(), any())).thenReturn(new ValidatingConfig.ConfigValidationResult(true, false, new ArrayList<String>(), new ArrayList<String>())); when(indexerConfigMock2.validateConfig(any(), any(), any())).thenReturn(new ValidatingConfig.ConfigValidationResult(true, false, new ArrayList<String>(), new ArrayList<String>())); testee.getIndexers().add(indexerConfigMock); testee.getIndexers().add(indexerConfigMock2); ValidatingConfig.ConfigValidationResult result = testee.validateConfig(new BaseConfig(), testee, new BaseConfig()); assertEquals(3, result.getErrorMessages().size()); assertTrue(result.getErrorMessages().get(2).contains("Duplicate")); }
|
IndexerForSearchSelector { protected boolean checkIndexerStatus(Indexer indexer) { if (indexer.getConfig().getState() == IndexerConfig.State.DISABLED_SYSTEM_TEMPORARY) { if (indexer.getConfig().getDisabledUntil() == null || Instant.ofEpochMilli(indexer.getConfig().getDisabledUntil()).isBefore(clock.instant())) { return true; } String message = String.format("Not using %s because it's disabled until %s due to a previous error ", indexer.getName(), Instant.ofEpochMilli(indexer.getConfig().getDisabledUntil())); return handleIndexerNotSelected(indexer, message, "Disabled temporarily because of previous errors"); } if (indexer.getConfig().getState() == IndexerConfig.State.DISABLED_SYSTEM) { String message = String.format("Not using %s because it's disabled due to a previous unrecoverable error", indexer.getName()); return handleIndexerNotSelected(indexer, message, "Disabled permanently because of previous unrecoverable error"); } return true; } IndexerForSearchSelection pickIndexers(SearchRequest searchRequest); static final Pattern SCHEDULER_PATTERN; }
|
@Test public void shouldCheckIfDisabledBySystem() { when(searchingConfig.isIgnoreTemporarilyDisabled()).thenReturn(false); indexerConfigMock.setState(IndexerConfig.State.ENABLED); indexerConfigMock.setDisabledUntil(null); assertTrue(testee.checkIndexerStatus(indexer)); indexerConfigMock.setState(IndexerConfig.State.DISABLED_SYSTEM_TEMPORARY); indexerConfigMock.setDisabledUntil(Instant.now().plus(1, ChronoUnit.DAYS).toEpochMilli()); assertFalse(testee.checkIndexerStatus(indexer)); indexerConfigMock.setState(IndexerConfig.State.DISABLED_SYSTEM); assertFalse(testee.checkIndexerStatus(indexer)); }
|
ConfigMigration { public Map<String, Object> migrate(Map<String, Object> map) { int foundConfigVersion = (int) ((Map<String, Object>) map.get("main")).get("configVersion"); if (foundConfigVersion > expectedConfigVersion) { throw new RuntimeException("The existing config file has version " + foundConfigVersion + " but the program expects version " + expectedConfigVersion + ". You might be trying to use an older code base with settings created by a newer version of the program"); } for (ConfigMigrationStep step : steps) { if (foundConfigVersion <= step.forVersion()) { logger.info("Migrating config from version {}", step.forVersion()); map = step.migrate(map); foundConfigVersion = step.forVersion() + 1; } ((Map<String, Object>) map.get("main")).put("configVersion", foundConfigVersion); } if (foundConfigVersion != expectedConfigVersion) { throw new RuntimeException(String.format("Expected the config after migration to be at version %d but it's at version %d", expectedConfigVersion, foundConfigVersion)); } return map; } ConfigMigration(); Map<String, Object> migrate(Map<String, Object> map); }
|
@Test public void shouldMigrate() { BaseConfig input = new BaseConfig(); input.getMain().setConfigVersion(1); BaseConfig afterMigration = new BaseConfig(); afterMigration.getMain().setConfigVersion(2); Map<String, Object> map = objectMapper.convertValue(input, typeRef); when(configMigrationStepMock.forVersion()).thenReturn(1); when(configMigrationStepMock.migrate(any())).thenReturn(map); testee.steps = Arrays.asList(configMigrationStepMock); testee.expectedConfigVersion = 2; Map<String, Object> result = testee.migrate(map); input = objectMapper.convertValue(result, BaseConfig.class); verify(configMigrationStepMock).migrate(map); assertThat(input.getMain().getConfigVersion()).isEqualTo(2); }
@Test(expected = RuntimeException.class) public void shouldThrowExceptionIfWrongConfigVersionAfterMigration() { BaseConfig input = new BaseConfig(); input.getMain().setConfigVersion(1); Map<String, Object> map = objectMapper.convertValue(input, typeRef); testee.steps = Collections.emptyList(); testee.expectedConfigVersion = 2; testee.migrate(map); }
|
ConfigMigration { protected static List<ConfigMigrationStep> getMigrationSteps() { ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); provider.addIncludeFilter(new AssignableTypeFilter(ConfigMigrationStep.class)); Set<BeanDefinition> candidates = provider.findCandidateComponents(ConfigMigrationStep.class.getPackage().getName()); List<ConfigMigrationStep> steps = new ArrayList<>(); for (BeanDefinition beanDefinition : candidates) { try { ConfigMigrationStep instance = (ConfigMigrationStep) Class.forName(beanDefinition.getBeanClassName()).getConstructor().newInstance(); steps.add(instance); } catch (Exception e) { logger.error("Unable to instantiate migration step from class " + beanDefinition.getBeanClassName(), e); } } Collections.sort(steps); return steps; } ConfigMigration(); Map<String, Object> migrate(Map<String, Object> map); }
|
@Test public void shouldFindMigrationStepsForAllPossibleConfigVersions() { Integer currentConfigVersion = new MainConfig().getConfigVersion(); List<ConfigMigrationStep> steps = ConfigMigration.getMigrationSteps(); for (int i = 3; i < currentConfigVersion; i++) { int finalI = i; assertThat(steps.stream().anyMatch(x -> x.forVersion() == finalI)).isTrue(); } }
|
ConfigMigrationStep005to006 implements ConfigMigrationStep { @Override public Map<String, Object> migrate(Map<String, Object> toMigrate) { Map<String, Object> categoriesConfig = getFromMap(toMigrate, "categoriesConfig"); List<Map<String, Object>> categories = getListFromMap(categoriesConfig, "categories"); for (Map<String, Object> category : categories) { List<Integer> existingNumbers = (List<Integer>) category.get("newznabCategories"); category.put("newznabCategories", existingNumbers.stream().map(Object::toString).collect(Collectors.toList())); } return toMigrate; } @Override int forVersion(); @Override Map<String, Object> migrate(Map<String, Object> toMigrate); }
|
@Test public void migrate() throws Exception { String yaml = Resources.toString(ConfigMigrationStep005to006Test.class.getResource("migrate5to6.yaml"), Charset.defaultCharset()); Map<String, Object> map = Jackson.YAML_MAPPER.readValue(yaml, ConfigReaderWriter.MAP_TYPE_REFERENCE); Map<String, Object> migrated = testee.migrate(map); String newYaml = Jackson.YAML_MAPPER.writeValueAsString(migrated); BaseConfig baseConfig = Jackson.YAML_MAPPER.readValue(newYaml, BaseConfig.class); assertThat(baseConfig.getCategoriesConfig().getCategories().get(0).getNewznabCategories().get(0).get(0)).isEqualTo(1000); assertThat(baseConfig.getCategoriesConfig().getCategories().get(1).getNewznabCategories().get(0).get(0)).isEqualTo(3000); assertThat(baseConfig.getCategoriesConfig().getCategories().get(1).getNewznabCategories().get(1).get(0)).isEqualTo(3030); }
|
NewsProvider { public List<NewsEntry> getNews() throws IOException { if (Instant.now().minus(2, ChronoUnit.HOURS).isAfter(lastCheckedForNews)) { newsEntries = webAccess.callUrl(newsUrl, new TypeReference<List<NewsEntry>>() { }); newsEntries.sort(Comparator.comparing(NewsEntry::getShowForVersion).reversed()); lastCheckedForNews = Instant.now(); } return newsEntries; } List<NewsEntry> getNews(); void saveShownForCurrentVersion(); List<NewsEntry> getNewsForCurrentVersionAndAfter(); }
|
@Test public void getNews() throws Exception { List<NewsEntry> entries = testee.getNews(); assertThat(entries.size(), is(3)); assertThat(entries.get(0).getNewsAsMarkdown(), is("news3.0.0")); assertThat(entries.get(0).getShowForVersion().major, is(3)); }
|
NewsProvider { public List<NewsEntry> getNewsForCurrentVersionAndAfter() throws IOException { List<ShownNews> shownNews = shownNewsRepository.findAll(); if (shownNews == null || shownNews.isEmpty()) { return Collections.emptyList(); } SemanticVersion from = shownNews.size() == 1 ? new SemanticVersion(shownNews.get(0).getVersion()) : null; SemanticVersion to = new SemanticVersion(updateManager.getCurrentVersionString()); List<NewsEntry> news = getNews(); return news.stream() .filter(x -> isShowNewsEntry(from, to, x)) .collect(Collectors.toList()); } List<NewsEntry> getNews(); void saveShownForCurrentVersion(); List<NewsEntry> getNewsForCurrentVersionAndAfter(); }
|
@Test public void shouldOnlyGetNewsNewerThanShownButNotNewerThanCurrentVersion() throws Exception { when(updateManagerMock.getCurrentVersionString()).thenReturn("2.0.0"); when(shownNewsRepositoryMock.findAll()).thenReturn(Collections.singletonList(new ShownNews("1.0.0"))); List<NewsEntry> entries = testee.getNewsForCurrentVersionAndAfter(); assertThat(entries.size(), is(1)); assertThat(entries.get(0).getNewsAsMarkdown(), is("news2.0.0")); }
@Test public void shouldOnlyGetNewstNotNewerThanCurrentVersion() throws Exception { when(updateManagerMock.getCurrentVersionString()).thenReturn("2.0.0"); when(shownNewsRepositoryMock.findAll()).thenReturn(Collections.singletonList(new ShownNews("0.0.1"))); List<NewsEntry> entries = testee.getNewsForCurrentVersionAndAfter(); assertThat(entries.size(), is(2)); assertThat(entries.get(0).getNewsAsMarkdown(), is("news2.0.0")); assertThat(entries.get(1).getNewsAsMarkdown(), is("news1.0.0")); }
@Test public void shouldNoNewsWhenNewInstall() throws Exception { when(updateManagerMock.getCurrentVersionString()).thenReturn("2.0.0"); when(shownNewsRepositoryMock.findAll()).thenReturn(Collections.emptyList()); List<NewsEntry> entries = testee.getNewsForCurrentVersionAndAfter(); assertThat(entries.size(), is(0)); }
@Test public void shouldNotGetNewsWhenAlreadyShown() throws Exception { when(updateManagerMock.getCurrentVersionString()).thenReturn("3.0.0"); when(shownNewsRepositoryMock.findAll()).thenReturn(Collections.singletonList(new ShownNews("3.0.0"))); List<NewsEntry> entries = testee.getNewsForCurrentVersionAndAfter(); assertThat(entries.size(), is(0)); }
|
IndexerForSearchSelector { protected boolean checkDisabledForCategory(Indexer indexer) { if (searchRequest.getCategory().getSubtype().equals(Subtype.ALL)) { return true; } boolean indexerDisabledForThisCategory = !indexer.getConfig().getEnabledCategories().isEmpty() && !indexer.getConfig().getEnabledCategories().contains(searchRequest.getCategory().getName()); if (indexerDisabledForThisCategory) { String message = String.format("Not using %s because it's disabled for category %s", indexer.getName(), searchRequest.getCategory().getName()); return handleIndexerNotSelected(indexer, message, "Disabled for category"); } return true; } IndexerForSearchSelection pickIndexers(SearchRequest searchRequest); static final Pattern SCHEDULER_PATTERN; }
|
@Test public void shouldCheckForCategory() { when(searchRequest.getCategory()).thenReturn(category); indexerConfigMock.setEnabledCategories(Collections.emptyList()); assertTrue(testee.checkDisabledForCategory(indexer)); indexerConfigMock.setEnabledCategories(Arrays.asList("anotherCategory")); assertFalse(testee.checkDisabledForCategory(indexer)); indexerConfigMock.setEnabledCategories(Arrays.asList(("category"))); assertTrue(testee.checkDisabledForCategory(indexer)); }
|
DevIndexer extends Newznab { protected Xml getAndStoreResultToDatabase(URI uri, IndexerApiAccessType apiAccessType) throws IndexerAccessException { NewznabXmlRoot rssRoot = new NewznabXmlRoot(); if (uri.toString().contains("oneduplicate")) { NewznabMockRequest mockRequest = NewznabMockRequest.builder().numberOfResults(1).titleBase("oneresult").titleWords(Collections.emptyList()).total(1).build(); rssRoot = NewznabMockBuilder.generateResponse(mockRequest); rssRoot.getRssChannel().getNewznabResponse().setTotal(1); rssRoot.getRssChannel().getItems().get(0).getEnclosure().setLength(100000L); rssRoot.getRssChannel().getItems().get(0).getNewznabAttributes().clear(); } else if (uri.toString().contains("duplicatesandtitlegroups")) { NewznabMockRequest mockRequest = NewznabMockRequest.builder().numberOfResults(1).titleBase("oneresult").titleWords(Collections.emptyList()).total(1).build(); rssRoot = NewznabMockBuilder.generateResponse(mockRequest); rssRoot.getRssChannel().getItems().get(0).getEnclosure().setLength(100000L); rssRoot.getRssChannel().getItems().get(0).getNewznabAttributes().clear(); rssRoot.getRssChannel().getItems().get(0).getTorznabAttributes().clear(); rssRoot.getRssChannel().getItems().get(0).getNewznabAttributes().add(new NewznabAttribute("grabs", "100")); mockRequest = NewznabMockRequest.builder().numberOfResults(1).titleBase("oneresult").titleWords(Collections.emptyList()).total(1).build(); NewznabXmlRoot rssRoot3 = NewznabMockBuilder.generateResponse(mockRequest); rssRoot3.getRssChannel().getItems().get(0).getEnclosure().setLength(200000L); rssRoot3.getRssChannel().getItems().get(0).getNewznabAttributes().clear(); rssRoot3.getRssChannel().getItems().get(0).getTorznabAttributes().clear(); rssRoot3.getRssChannel().getItems().get(0).getNewznabAttributes().add(new NewznabAttribute("grabs", "2000")); rssRoot3.getRssChannel().getItems().get(0).setLink("anotherlink"); rssRoot.getRssChannel().getItems().add(rssRoot3.getRssChannel().getItems().get(0)); mockRequest = NewznabMockRequest.builder().numberOfResults(1).titleBase("anotherresult").titleWords(Collections.emptyList()).total(1).build(); NewznabXmlRoot rssRoot2 = NewznabMockBuilder.generateResponse(mockRequest); rssRoot.getRssChannel().getItems().add(rssRoot2.getRssChannel().getItems().get(0)); rssRoot.getRssChannel().getNewznabResponse().setTotal(3); } else if (uri.toString().contains("duplicates")) { NewznabMockRequest mockRequest = NewznabMockRequest.builder().numberOfResults(10).titleBase("duplicates").titleWords(Collections.emptyList()).total(10).build(); rssRoot = NewznabMockBuilder.generateResponse(mockRequest); rssRoot.getRssChannel().getNewznabResponse().setTotal(10); for (NewznabXmlItem rssItem : rssRoot.getRssChannel().getItems()) { rssItem.getEnclosure().setLength(100000L); rssItem.getNewznabAttributes().clear(); rssItem.setPubDate(Instant.now()); rssItem.setDescription("Indexer: " + getName() + ", title:" + rssItem.getTitle()); } } else if (uri.toString().contains("tworesults")) { rssRoot = NewznabMockBuilder.generateResponse(0, 2, "results", false, Collections.emptyList(), false, 0); rssRoot.getRssChannel().getNewznabResponse().setTotal(2); } else { rssRoot = NewznabMockBuilder.generateResponse(0, 100, "results", false, Collections.emptyList(), false, 0); rssRoot.getRssChannel().getNewznabResponse().setTotal(100); } if (uri.toString().contains("punkte")) { rssRoot.getRssChannel().getItems().get(0).setTitle("a a"); rssRoot.getRssChannel().getItems().get(1).setTitle("ab"); rssRoot.getRssChannel().getItems().get(2).setTitle("a.c"); } return rssRoot; } }
|
@Test public void testGeneration() throws Exception { Xml xml = testee.getAndStoreResultToDatabase(URI.create("http: NewznabXmlRoot root = (NewznabXmlRoot) xml; System.out.println(root); }
|
NzbIndex extends Indexer<NewznabXmlRoot> { @Override protected List<SearchResultItem> getSearchResultItems(NewznabXmlRoot rssRoot, SearchRequest searchRequest) { if (rssRoot.getRssChannel().getItems() == null || rssRoot.getRssChannel().getItems().isEmpty()) { debug("No results found"); return Collections.emptyList(); } List<SearchResultItem> items = new ArrayList<>(); for (NewznabXmlItem rssItem : rssRoot.getRssChannel().getItems()) { SearchResultItem item = new SearchResultItem(); item.setPubDate(rssItem.getPubDate()); String nzbIndexLink = rssItem.getLink(); item.setTitle(rssItem.getTitle()); item.setAgePrecise(true); if (rssItem.getCategory() != null) { item.setGroup(rssItem.getCategory().replace("a.b", "alt.binaries")); } item.setLink(rssItem.getEnclosure().getUrl()); item.setSize(rssItem.getEnclosure().getLength()); Matcher matcher = GUID_PATTERN.matcher(nzbIndexLink); boolean found = matcher.find(); if (!found) { logger.error("Unable to parse '{}' result for link. Skipping it", nzbIndexLink); continue; } item.setIndexerGuid(matcher.group(1)); item.setCategory(categoryProvider.getNotAvailable()); item.setOriginalCategory("N/A"); item.setIndexerScore(config.getScore()); if (item.getDescription() != null) { item.setHasNfo(rssItem.getDescription().contains("1 NFO") ? HasNfo.YES : HasNfo.NO); } else { item.setHasNfo(HasNfo.NO); } item.setIndexer(this); item.setDownloadType(DownloadType.NZB); items.add(item); } return items; } @Override NfoResult getNfo(String guid); }
|
@Test public void shouldParseRows() throws Exception { Instant now = Instant.now(); String enclosureUrl = "https: String link = "https: NewznabXmlRoot root = RssBuilder.builder().items( Arrays.asList( RssItemBuilder .builder("Watchers.of.the.Universe.S02E09.1080p.WEB-DL.DD5.1.AAC2.0.H.264-YFN-0030-Watchers.of.the.Universe.S02E09.Cant.Get.You.out.of.My.Head.1080p.WEB-DL") .link(link) .description("<![CDATA[\n" + "<p><font color=\"gray\">alt.binaries.hdtv.x264</font><br /> <b>1.01 GB</b><br /> 7 hours<br /> <font color=\"#3DA233\">31 files (1405 parts)</font> <font color=\"gray\">by s@nd.p (SP)</font><br /> <font color=\"#E2A910\"> 1 NFO | 9 PAR2 | 1 NZB | 19 ARCHIVE</font> - <a href=\"http: "]]>") .category("alt.binaries.hdtv.x264") .pubDate(now) .rssGuid(new NewznabXmlGuid(link, true)) .enclosure(new NewznabXmlEnclosure(enclosureUrl, 1089197181L, "application/x-nzb")) .build())).build(); List<SearchResultItem> items = testee.getSearchResultItems(root, new SearchRequest()); assertThat(items.size(), is(1)); SearchResultItem item = items.get(0); assertThat(item.getTitle(), is("Watchers.of.the.Universe.S02E09.1080p.WEB-DL.DD5.1.AAC2.0.H.264-YFN-0030-Watchers.of.the.Universe.S02E09.Cant.Get.You.out.of.My.Head.1080p.WEB-DL")); assertThat(item.getGroup().get(), is("alt.binaries.hdtv.x264")); assertThat(item.getPubDate(), is(now)); assertThat(item.isAgePrecise(), is(true)); assertThat(item.getSize(), is(1089197181L)); assertThat(item.getIndexerGuid(), is("164950363")); assertThat(item.getDownloadType(), is(DownloadType.NZB)); assertThat(item.getHasNfo(), is(HasNfo.NO)); }
|
Binsearch extends Indexer<String> { @SuppressWarnings("ConstantConditions") @Override protected List<SearchResultItem> getSearchResultItems(String searchRequestResponse, SearchRequest searchRequest) throws IndexerParsingException { List<SearchResultItem> items = new ArrayList<>(); Document doc = Jsoup.parse(searchRequestResponse); if (doc.text().contains("No results in most popular groups")) { return Collections.emptyList(); } Elements mainTables = doc.select("table#r2"); if (mainTables.size() == 0) { throw new IndexerParsingException("Unable to find main table in binsearch page. This happens sometimes ;-)"); } Element mainTable = mainTables.get(0); Elements rows = mainTable.select("tr"); for (int i = 1; i < rows.size(); i++) { Element row = rows.get(i); SearchResultItem item = parseRow(row); if (item == null) { continue; } items.add(item); } debug("Finished parsing {} of {} rows", items.size(), rows.size()); return items; } @Override NfoResult getNfo(String guid); }
|
@Test public void shouldParseResultsCorrectly() throws Exception { String html = Resources.toString(Resources.getResource(BinsearchTest.class, "/org/nzbhydra/mapping/binsearch.html"), Charsets.UTF_8); List<SearchResultItem> searchResultItems = testee.getSearchResultItems(html, new SearchRequest()); assertThat(searchResultItems.size(), is(1)); SearchResultItem item = searchResultItems.get(0); assertThat(item.getTitle(), is("testtitle. 3D.TOPBOT.TrueFrench.1080p.X264.AC3.5.1-JKF.mkv")); assertThat(item.getLink(), is("https: assertThat(item.getDetails(), is("https: assertThat(item.getSize(), is(12209999872L)); assertThat(item.getIndexerGuid(), is("176073735")); assertThat(item.getPubDate(), is(Instant.ofEpochSecond(1443312000))); assertThat(item.isAgePrecise(), is(false)); assertThat(item.getPoster().get(), is("Ramer@marmer.com (Clown_nez)")); assertThat(item.getGroup().get(), is("alt.binaries.movies.mkv")); }
@Test public void shouldParseOtherResultsCorrectly() throws Exception { String html = Resources.toString(Resources.getResource(BinsearchTest.class, "/org/nzbhydra/mapping/binsearch_randm.html"), Charsets.UTF_8); List<SearchResultItem> searchResultItems = testee.getSearchResultItems(html, new SearchRequest()); assertThat(searchResultItems.size(), is(41)); }
@Test public void shouldRecognizeWhenNoResultsFound() throws Exception { String html = Resources.toString(Resources.getResource(BinsearchTest.class, "/org/nzbhydra/mapping/binsearch_noresults.html"), Charsets.UTF_8); List<SearchResultItem> searchResultItems = testee.getSearchResultItems(html, new SearchRequest()); assertThat(searchResultItems, is(empty())); }
|
Binsearch extends Indexer<String> { @Override protected void completeIndexerSearchResult(String response, IndexerSearchResult indexerSearchResult, AcceptorResult acceptorResult, SearchRequest searchRequest, int offset, Integer limit) { Document doc = Jsoup.parse(response); if (doc.select("table.xMenuT").size() > 0) { Element navigationTable = doc.select("table.xMenuT").get(1); Elements pageLinks = navigationTable.select("a"); boolean hasMore = !pageLinks.isEmpty() && pageLinks.last().text().equals(">"); boolean totalKnown = false; indexerSearchResult.setOffset(searchRequest.getOffset()); int total = searchRequest.getOffset() + 100; if (!hasMore) { total = searchRequest.getOffset() + indexerSearchResult.getSearchResultItems().size(); totalKnown = true; } indexerSearchResult.setHasMoreResults(hasMore); indexerSearchResult.setTotalResults(total); indexerSearchResult.setTotalResultsKnown(totalKnown); } else { indexerSearchResult.setHasMoreResults(false); indexerSearchResult.setTotalResults(0); indexerSearchResult.setTotalResultsKnown(true); } indexerSearchResult.setLimit(limit); indexerSearchResult.setOffset(offset); } @Override NfoResult getNfo(String guid); }
|
@Test public void shouldRecognizeIfSingleResultPage() throws Exception { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); String html = Resources.toString(Resources.getResource(BinsearchTest.class, "/org/nzbhydra/mapping/binsearch_singlepage.html"), Charsets.UTF_8); IndexerSearchResult indexerSearchResult = new IndexerSearchResult(testee, ""); List<SearchResultItem> items = new ArrayList<>(); for (int i = 0; i < 24; i++) { SearchResultItem searchResultItem = new SearchResultItem(); searchResultItem.setPubDate(Instant.now()); items.add(searchResultItem); } indexerSearchResult.setSearchResultItems(items); testee.completeIndexerSearchResult(html, indexerSearchResult, null, searchRequest, 0, 100); assertThat(indexerSearchResult.getOffset(), is(0)); assertThat(indexerSearchResult.getLimit(), is(100)); assertThat(indexerSearchResult.getTotalResults(), is(24)); assertThat(indexerSearchResult.isTotalResultsKnown(), is(true)); assertThat(indexerSearchResult.isHasMoreResults(), is(false)); }
@Test public void shouldRecognizeIfMoreResultsAvailable() throws Exception { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); String html = Resources.toString(Resources.getResource(BinsearchTest.class, "/org/nzbhydra/mapping/binsearch.html"), Charsets.UTF_8); IndexerSearchResult indexerSearchResult = new IndexerSearchResult(testee, ""); testee.completeIndexerSearchResult(html, indexerSearchResult, null, searchRequest, 0, 100); assertThat(indexerSearchResult.isTotalResultsKnown(), is(false)); assertThat(indexerSearchResult.isHasMoreResults(), is(true)); }
|
Binsearch extends Indexer<String> { @Override protected UriComponentsBuilder buildSearchUrl(SearchRequest searchRequest, Integer offset, Integer limit) throws IndexerSearchAbortedException { String query = super.generateQueryIfApplicable(searchRequest, ""); query = addRequiredWordsToQuery(searchRequest, query); if (Strings.isNullOrEmpty(query)) { throw new IndexerSearchAbortedException("Binsearch cannot search without a query"); } query = cleanupQuery(query); return UriComponentsBuilder.fromHttpUrl("https: } @Override NfoResult getNfo(String guid); }
|
@Test public void shouldBuildSimpleQuery() throws IndexerSearchAbortedException { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); searchRequest.setQuery("query"); UriComponentsBuilder builder = testee.buildSearchUrl(searchRequest, 0, 100); assertThat(builder.toUriString(), is("https: }
@Test public void shouldAddRequiredWords() throws IndexerSearchAbortedException { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); searchRequest.getInternalData().setRequiredWords(Arrays.asList("a", "b")); searchRequest.setQuery("query"); UriComponentsBuilder builder = testee.buildSearchUrl(searchRequest, 0, 100); assertThat(builder.build().toString(), is("https: }
@Test(expected = IndexerSearchAbortedException.class) public void shouldAbortIfSearchNotPossible() throws IndexerSearchAbortedException { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); testee.buildSearchUrl(searchRequest, 0, 100); }
|
IndexerForSearchSelector { protected boolean checkLoadLimiting(Indexer indexer) { boolean preventedByLoadLimiting = indexer.getConfig().getLoadLimitOnRandom().isPresent() && random.nextInt(indexer.getConfig().getLoadLimitOnRandom().get()) + 1 != 1; if (preventedByLoadLimiting) { boolean loadLimitIgnored = configProvider.getBaseConfig().getSearching().isIgnoreLoadLimitingForInternalSearches() && searchRequest.getSource() == SearchSource.INTERNAL; if (loadLimitIgnored) { logger.debug("Ignoring load limiting for internal search"); return true; } String message = String.format("Not using %s because load limiting prevented it. Chances of it being picked: 1/%d", indexer.getName(), indexer.getConfig().getLoadLimitOnRandom().get()); return handleIndexerNotSelected(indexer, message, "Load limiting"); } return true; } IndexerForSearchSelection pickIndexers(SearchRequest searchRequest); static final Pattern SCHEDULER_PATTERN; }
|
@Test public void shouldCheckForLoadLimiting() { indexerConfigMock.setLoadLimitOnRandom(null); assertTrue(testee.checkLoadLimiting(indexer)); indexerConfigMock.setLoadLimitOnRandom(1); for (int i = 0; i < 50; i++) { assertTrue(testee.checkLoadLimiting(indexer)); } indexerConfigMock.setLoadLimitOnRandom(2); int countNotPicked = 0; for (int i = 0; i < 500; i++) { countNotPicked += testee.checkLoadLimiting(indexer) ? 0 : 1; } assertTrue(countNotPicked > 0); }
|
Binsearch extends Indexer<String> { @Override protected String getAndStoreResultToDatabase(URI uri, IndexerApiAccessType apiAccessType) throws IndexerAccessException { return Failsafe.with(retry503policy) .onFailedAttempt(throwable -> logger.warn("Encountered 503 error. Will retry")) .get(() -> getAndStoreResultToDatabase(uri, String.class, apiAccessType)); } @Override NfoResult getNfo(String guid); }
|
@Test(expected = FailsafeException.class) public void shouldRetryOn503() throws Exception { testee = spy(testee); doThrow(new IndexerAccessException("503")).when(testee).getAndStoreResultToDatabase(uriCaptor.capture(), any(), any()); testee.getAndStoreResultToDatabase(null, IndexerApiAccessType.NFO); }
|
Indexer { @Transactional protected List<SearchResultItem> persistSearchResults(List<SearchResultItem> searchResultItems, IndexerSearchResult indexerSearchResult) { Stopwatch stopwatch = Stopwatch.createStarted(); synchronized (dbLock) { ArrayList<SearchResultEntity> searchResultEntities = new ArrayList<>(); Set<Long> alreadySavedIds = searchResultRepository.findAllIdsByIdIn(searchResultItems.stream().map(SearchResultIdCalculator::calculateSearchResultId).collect(Collectors.toList())); for (SearchResultItem item : searchResultItems) { long guid = SearchResultIdCalculator.calculateSearchResultId(item); if (!alreadySavedIds.contains(guid)) { SearchResultEntity searchResultEntity = new SearchResultEntity(); searchResultEntity.setIndexer(indexer); searchResultEntity.setTitle(item.getTitle()); searchResultEntity.setLink(item.getLink()); searchResultEntity.setDetails(item.getDetails()); searchResultEntity.setIndexerGuid(item.getIndexerGuid()); searchResultEntity.setFirstFound(Instant.now()); searchResultEntity.setDownloadType(item.getDownloadType()); searchResultEntity.setPubDate(item.getPubDate()); searchResultEntities.add(searchResultEntity); } item.setGuid(guid); item.setSearchResultId(guid); } debug("Found {} results which were already in the database and {} new ones", alreadySavedIds.size(), searchResultEntities.size()); try { searchResultRepository.saveAll(searchResultEntities); indexerSearchResult.setSearchResultEntities(new HashSet<>(searchResultEntities)); } catch (EntityExistsException e) { error("Unable to save the search results to the database", e); } } getLogger().debug(LoggingMarkers.PERFORMANCE, "Persisting {} search results took {}ms", searchResultItems.size(), stopwatch.elapsed(TimeUnit.MILLISECONDS)); return searchResultItems; } void initialize(IndexerConfig config, IndexerEntity indexer); @EventListener void handleNewConfig(ConfigChangedEvent configChangedEvent); IndexerSearchResult search(SearchRequest searchRequest, int offset, Integer limit); abstract NfoResult getNfo(String guid); String getName(); IndexerConfig getConfig(); IndexerEntity getIndexerEntity(); String cleanUpTitle(String title); Optional<Instant> tryParseDate(String dateString); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
|
@Test public void shouldCreateNewSearchResultEntityWhenNoneIsFound() throws Exception { SearchResultItem item = new SearchResultItem(); item.setIndexer(indexerMock); item.setTitle("title"); item.setDetails("details"); item.setIndexerGuid("guid"); testee.persistSearchResults(Collections.singletonList(item), new IndexerSearchResult()); verify(searchResultRepositoryMock).saveAll(searchResultEntitiesCaptor.capture()); List<SearchResultEntity> persistedEntities = searchResultEntitiesCaptor.getValue(); assertThat(persistedEntities.size(), is(1)); assertThat(persistedEntities.get(0).getTitle(), is("title")); assertThat(persistedEntities.get(0).getDetails(), is("details")); assertThat(persistedEntities.get(0).getIndexerGuid(), is("guid")); }
@Test public void shouldNotCreateNewSearchResultEntityWhenOneExists() throws Exception { SearchResultItem item = new SearchResultItem(); item.setIndexerGuid("guid"); item.setIndexer(indexerMock); when(searchResultEntityMock.getIndexerGuid()).thenReturn("guid"); when(searchResultRepositoryMock.findAllIdsByIdIn(anyList())).thenReturn(Sets.newHashSet(299225959498991027L)); testee.persistSearchResults(Collections.singletonList(item), new IndexerSearchResult()); verify(searchResultRepositoryMock).saveAll(searchResultEntitiesCaptor.capture()); List<SearchResultEntity> persistedEntities = searchResultEntitiesCaptor.getValue(); assertThat(persistedEntities.size(), is(0)); }
|
Indexer { protected void handleSuccess(IndexerApiAccessType accessType, Long responseTime) { if (getConfig().getDisabledLevel() > 0) { debug("Indexer was successfully called after {} failed attempts in a row", getConfig().getDisabledLevel()); } getConfig().setState(IndexerConfig.State.ENABLED); getConfig().setLastError(null); getConfig().setDisabledUntil(null); getConfig().setDisabledLevel(0); configProvider.getBaseConfig().save(false); saveApiAccess(accessType, responseTime, IndexerAccessResult.SUCCESSFUL, true); } void initialize(IndexerConfig config, IndexerEntity indexer); @EventListener void handleNewConfig(ConfigChangedEvent configChangedEvent); IndexerSearchResult search(SearchRequest searchRequest, int offset, Integer limit); abstract NfoResult getNfo(String guid); String getName(); IndexerConfig getConfig(); IndexerEntity getIndexerEntity(); String cleanUpTitle(String title); Optional<Instant> tryParseDate(String dateString); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
|
@Test public void handleSuccess() throws Exception { indexerConfig.setState(IndexerConfig.State.DISABLED_SYSTEM_TEMPORARY); indexerConfig.setDisabledLevel(1); indexerConfig.setDisabledUntil(Instant.now().toEpochMilli()); testee.handleSuccess(IndexerApiAccessType.SEARCH, 0L); assertThat(indexerConfig.getState(), is(IndexerConfig.State.ENABLED)); assertThat(indexerConfig.getDisabledLevel(), is(0)); assertThat(indexerConfig.getDisabledUntil(), is(nullValue())); }
|
Indexer { protected void handleFailure(String reason, Boolean disablePermanently, IndexerApiAccessType accessType, Long responseTime, IndexerAccessResult accessResult) { if (disablePermanently) { getLogger().warn("Because an unrecoverable error occurred {} will be permanently disabled until reenabled by the user", indexer.getName()); getConfig().setState(IndexerConfig.State.DISABLED_SYSTEM); } else if (!configProvider.getBaseConfig().getSearching().isIgnoreTemporarilyDisabled()) { getConfig().setState(IndexerConfig.State.DISABLED_SYSTEM_TEMPORARY); getConfig().setDisabledLevel(getConfig().getDisabledLevel() + 1); long minutesToAdd = DISABLE_PERIODS.get(Math.min(DISABLE_PERIODS.size() - 1, getConfig().getDisabledLevel())); Instant disabledUntil = Instant.now().plus(minutesToAdd, ChronoUnit.MINUTES); getConfig().setDisabledUntil(disabledUntil.toEpochMilli()); getLogger().warn("Because an error occurred {} will be temporarily disabled until {}. This is error number {} in a row", indexer.getName(), disabledUntil, getConfig().getDisabledLevel()); } getConfig().setLastError(reason); configProvider.getBaseConfig().save(false); saveApiAccess(accessType, responseTime, accessResult, false); } void initialize(IndexerConfig config, IndexerEntity indexer); @EventListener void handleNewConfig(ConfigChangedEvent configChangedEvent); IndexerSearchResult search(SearchRequest searchRequest, int offset, Integer limit); abstract NfoResult getNfo(String guid); String getName(); IndexerConfig getConfig(); IndexerEntity getIndexerEntity(); String cleanUpTitle(String title); Optional<Instant> tryParseDate(String dateString); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
|
@Test public void handleFailure() throws Exception { indexerConfig.setState(IndexerConfig.State.ENABLED); indexerConfig.setDisabledLevel(0); indexerConfig.setDisabledUntil(null); testee.handleFailure("reason", false, null, null, null); assertThat(indexerConfig.getState(), is(IndexerConfig.State.DISABLED_SYSTEM_TEMPORARY)); assertThat(indexerConfig.getDisabledLevel(), is(1)); long disabledPeriod = Math.abs(Instant.ofEpochMilli(indexerConfig.getDisabledUntil()).getEpochSecond() - Instant.now().getEpochSecond()); long delta = Math.abs(Indexer.DISABLE_PERIODS.get(1) * 60 - disabledPeriod); org.assertj.core.api.Assertions.assertThat(delta).isLessThan(5); indexerConfig.setState(IndexerConfig.State.ENABLED); indexerConfig.setDisabledLevel(0); indexerConfig.setDisabledUntil(null); testee.handleFailure("reason", true, null, null, null); assertThat(indexerConfig.getState(), is(IndexerConfig.State.DISABLED_SYSTEM)); }
|
Indexer { public String cleanUpTitle(String title) { if (Strings.isNullOrEmpty(title)) { return title; } title = title.trim(); List<String> removeTrailing = configProvider.getBaseConfig().getSearching().getRemoveTrailing().stream().map(x -> x.toLowerCase().trim()).collect(Collectors.toList()); if (removeTrailing.isEmpty()) { return title; } if (cleanupPattern == null) { String allPattern = "^(?<keep>.*)(" + removeTrailing.stream().map(x -> x.replace("*", "WILDCARDXXX").replaceAll("[-\\[\\]{}()*+?.,\\\\\\\\^$|#]", "\\\\$0").replace("WILDCARDXXX", ".*") + "$").collect(Collectors.joining("|")) + ")"; cleanupPattern = Pattern.compile(allPattern, Pattern.CASE_INSENSITIVE); } Matcher matcher = cleanupPattern.matcher(title); while (matcher.matches()) { title = matcher.replaceAll("$1").trim(); matcher = cleanupPattern.matcher(title); } return title; } void initialize(IndexerConfig config, IndexerEntity indexer); @EventListener void handleNewConfig(ConfigChangedEvent configChangedEvent); IndexerSearchResult search(SearchRequest searchRequest, int offset, Integer limit); abstract NfoResult getNfo(String guid); String getName(); IndexerConfig getConfig(); IndexerEntity getIndexerEntity(); String cleanUpTitle(String title); Optional<Instant> tryParseDate(String dateString); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
|
@Test public void shouldRemoveTrailing2() { List<String> collect = IntStream.range(1, 100).mapToObj(x -> "trailing" + x + "*********").collect(Collectors.toList()); List<String> all = new ArrayList<>(); all.addAll(collect); all.add("trailing*"); baseConfig.getSearching().setRemoveTrailing(all); testee.cleanUpTitle("abc trailing1 trailing2"); testee.cleanUpTitle("abc trailing1 trailing2"); testee.cleanUpTitle("abc trailing1 trailing2"); Stopwatch stopwatch = Stopwatch.createStarted(); for (int i = 0; i < 100; i++) { testee.cleanUpTitle("abc trailing1 trailing2"); } System.out.println(stopwatch.elapsed(TimeUnit.MILLISECONDS)); }
|
Torznab extends Newznab { protected SearchResultItem createSearchResultItem(NewznabXmlItem item) throws NzbHydraException { item.getRssGuid().setPermaLink(true); SearchResultItem searchResultItem = super.createSearchResultItem(item); searchResultItem.setGrabs(item.getGrabs()); searchResultItem.setIndexerGuid(item.getRssGuid().getGuid()); for (NewznabAttribute attribute : item.getTorznabAttributes()) { searchResultItem.getAttributes().put(attribute.getName(), attribute.getValue()); switch (attribute.getName()) { case "grabs": searchResultItem.setGrabs(Integer.valueOf(attribute.getValue())); break; case "guid": searchResultItem.setIndexerGuid(attribute.getValue()); break; case "seeders": searchResultItem.setSeeders(Integer.valueOf(attribute.getValue())); break; case "peers": searchResultItem.setPeers(Integer.valueOf(attribute.getValue())); break; } } if (item.getSize() != null) { searchResultItem.setSize(item.getSize()); } else if (item.getTorznabAttributes().stream().noneMatch(x -> x.getName().equals("size"))) { searchResultItem.getAttributes().put("size", String.valueOf(item.getSize())); } List<Integer> foundCategories = tryAndGetCategoryAsNumber(item); if (!foundCategories.isEmpty()) { computeCategory(searchResultItem, foundCategories); } else { searchResultItem.setCategory(categoryProvider.getNotAvailable()); } searchResultItem.setHasNfo(HasNfo.NO); searchResultItem.setIndexerScore(config.getScore()); searchResultItem.setDownloadType(DownloadType.TORRENT); searchResultItem.setGuid(SearchResultIdCalculator.calculateSearchResultId(searchResultItem)); return searchResultItem; } }
|
@Test public void shouldCreateSearchResultItem() throws Exception { NewznabXmlItem rssItem = buildBasicRssItem(); rssItem.setSize(456L); rssItem.getTorznabAttributes().add(new NewznabAttribute("password", "0")); rssItem.getTorznabAttributes().add(new NewznabAttribute("group", "group")); rssItem.getTorznabAttributes().add(new NewznabAttribute("poster", "poster")); rssItem.getTorznabAttributes().add(new NewznabAttribute("size", "456")); rssItem.getTorznabAttributes().add(new NewznabAttribute("files", "10")); rssItem.getTorznabAttributes().add(new NewznabAttribute("grabs", "20")); rssItem.getTorznabAttributes().add(new NewznabAttribute("comments", "30")); rssItem.getTorznabAttributes().add(new NewznabAttribute("usenetdate", new JaxbPubdateAdapter().marshal(Instant.ofEpochSecond(6666666)))); rssItem.getEnclosures().add(new NewznabXmlEnclosure("http: rssItem.setCategory("4000"); SearchResultItem item = testee.createSearchResultItem(rssItem); assertThat(item.getLink(), is("http: assertThat(item.getIndexerGuid(), is("http: assertThat(item.getSize(), is(456L)); assertThat(item.getCommentsLink(), is("http: assertThat(item.getDetails(), is("http: assertThat(item.isAgePrecise(), is(true)); assertThat(item.getGrabs(), is(20)); assertThat(item.getDownloadType(), is(DownloadType.TORRENT)); }
@Test public void shouldComputeCategory() throws Exception { when(categoryProviderMock.fromResultNewznabCategories(ArgumentMatchers.any())).thenReturn(categoryMock); NewznabXmlItem rssItem = buildBasicRssItem(); rssItem.getTorznabAttributes().add(new NewznabAttribute("category", "5070")); rssItem.getEnclosures().add(new NewznabXmlEnclosure("url", 1L, "application/x-bittorrent")); SearchResultItem item = testee.createSearchResultItem(rssItem); assertThat(item.getCategory(), is(categoryMock)); rssItem.getTorznabAttributes().clear(); rssItem.setCategory("5070"); item = testee.createSearchResultItem(rssItem); assertThat(item.getCategory(), is(categoryMock)); }
|
Torznab extends Newznab { @Override protected UriComponentsBuilder buildSearchUrl(SearchRequest searchRequest, Integer offset, Integer limit) throws IndexerSearchAbortedException { return super.buildSearchUrl(searchRequest, null, null); } }
|
@Test public void shouldNotAddExcludedWordsToQuery() throws Exception { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); searchRequest.getInternalData().setForbiddenWords(Arrays.asList("notthis", "alsonotthis")); searchRequest.setQuery("query"); UriComponentsBuilder builder = testee.buildSearchUrl(searchRequest, 0, 100); assertThat(builder.toUriString(), not(containsString("notthis"))); }
|
Torznab extends Newznab { protected List<Integer> tryAndGetCategoryAsNumber(NewznabXmlItem item) { Set<Integer> foundCategories = new HashSet<>(); if (item.getCategory() != null) { try { foundCategories.add(Integer.parseInt(item.getCategory())); } catch (NumberFormatException e) { } } foundCategories.addAll(item.getNewznabAttributes().stream().filter(x -> x.getName().equals("category")).map(x -> Integer.valueOf(x.getValue())).collect(Collectors.toList())); foundCategories.addAll(item.getTorznabAttributes().stream().filter(x -> x.getName().equals("category")).map(x -> Integer.valueOf(x.getValue())).collect(Collectors.toList())); return new ArrayList<>(foundCategories); } }
|
@Test public void shouldGetCorrectCategoryNumber() { NewznabXmlItem item = buildBasicRssItem(); item.setTorznabAttributes(Collections.singletonList(new NewznabAttribute("category", "2000"))); List<Integer> integers = testee.tryAndGetCategoryAsNumber(item); assertThat(integers.size(), is(1)); assertThat(integers.get(0), is(2000)); item.setTorznabAttributes(Collections.singletonList(new NewznabAttribute("category", "10000"))); integers = testee.tryAndGetCategoryAsNumber(item); assertThat(integers.size(), is(1)); assertThat(integers.get(0), is(10000)); item.setTorznabAttributes(Arrays.asList(new NewznabAttribute("category", "2000"), new NewznabAttribute("category", "10000"))); integers = testee.tryAndGetCategoryAsNumber(item); integers.sort(Comparator.naturalOrder()); assertThat(integers.size(), is(2)); assertThat(integers.get(0), is(2000)); assertThat(integers.get(1), is(10000)); item.setTorznabAttributes(Arrays.asList(new NewznabAttribute("category", "2000"), new NewznabAttribute("category", "2040"))); integers = testee.tryAndGetCategoryAsNumber(item); integers.sort(Comparator.naturalOrder()); assertThat(integers.size(), is(2)); assertThat(integers.get(0), is(2000)); assertThat(integers.get(1), is(2040)); item.setTorznabAttributes(Arrays.asList(new NewznabAttribute("category", "2000"), new NewznabAttribute("category", "2040"), new NewznabAttribute("category", "10000"))); integers = testee.tryAndGetCategoryAsNumber(item); integers.sort(Comparator.naturalOrder()); assertThat(integers.size(), is(3)); assertThat(integers.get(0), is(2000)); assertThat(integers.get(1), is(2040)); }
|
IndexerForSearchSelector { protected boolean checkSearchSource(Indexer indexer) { boolean wrongSearchSource = !indexer.getConfig().getEnabledForSearchSource().meets(searchRequest); if (wrongSearchSource) { String message = String.format("Not using %s because the search source is %s but the indexer is only enabled for %s searches", indexer.getName(), searchRequest.getSource(), indexer.getConfig().getEnabledForSearchSource()); return handleIndexerNotSelected(indexer, message, "Not enabled for this search context"); } return true; } IndexerForSearchSelection pickIndexers(SearchRequest searchRequest); static final Pattern SCHEDULER_PATTERN; }
|
@Test public void shouldCheckContext() { when(searchModuleProviderMock.getIndexers()).thenReturn(Arrays.asList(indexer)); when(searchRequest.getSource()).thenReturn(SearchSource.INTERNAL); indexerConfigMock.setEnabledForSearchSource(SearchSourceRestriction.API); assertFalse(testee.checkSearchSource(indexer)); when(searchRequest.getSource()).thenReturn(SearchSource.API); assertTrue(testee.checkSearchSource(indexer)); }
|
Anizb extends Indexer<NewznabXmlRoot> { @Override protected UriComponentsBuilder buildSearchUrl(SearchRequest searchRequest, Integer offset, Integer limit) throws IndexerSearchAbortedException { String query = super.generateQueryIfApplicable(searchRequest, ""); query = addRequiredWordsToQuery(searchRequest, query); if (Strings.isNullOrEmpty(query)) { throw new IndexerSearchAbortedException("Anizb cannot search without a query"); } query = cleanupQuery(query); return UriComponentsBuilder.fromHttpUrl("https: } @Override NfoResult getNfo(String guid); }
|
@Test public void shouldBuildSimpleQuery() throws IndexerSearchAbortedException { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); searchRequest.setQuery("query"); UriComponentsBuilder builder = testee.buildSearchUrl(searchRequest, 0, 100); assertThat(builder.toUriString(), is("https: }
@Test public void shouldAddRequiredWords() throws IndexerSearchAbortedException { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); searchRequest.getInternalData().setRequiredWords(Arrays.asList("a", "b")); searchRequest.setQuery("query"); UriComponentsBuilder builder = testee.buildSearchUrl(searchRequest, 0, 100); assertThat(builder.toUriString(), is("https: }
@Test(expected = IndexerSearchAbortedException.class) public void shouldAbortIfSearchNotPossible() throws IndexerSearchAbortedException { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); testee.buildSearchUrl(searchRequest, 0, 100); }
|
NzbsOrg extends Newznab { protected String addForbiddenWords(SearchRequest searchRequest, String query) { List<String> allForbiddenWords = new ArrayList<>(searchRequest.getInternalData().getForbiddenWords()); allForbiddenWords.addAll(configProvider.getBaseConfig().getSearching().getForbiddenWords()); allForbiddenWords.addAll(searchRequest.getCategory().getForbiddenWords()); List<String> allPossibleForbiddenWords = allForbiddenWords.stream().filter(x -> !(x.contains(" ") || x.contains("-") || x.contains("."))).collect(Collectors.toList()); if (allForbiddenWords.size() > allPossibleForbiddenWords.size()) { logger.debug("Not using some forbidden words in query because characters forbidden by newznab are contained"); } if (!allPossibleForbiddenWords.isEmpty()) { StringBuilder queryBuilder = new StringBuilder(query); for (String word : allForbiddenWords) { if ((queryBuilder + " --" + word).length() < 255) { queryBuilder.append(" --").append(word); } } query = queryBuilder.toString(); } return query; } }
|
@Test public void shouldLimitQueryLengthWhenAddingForbiddenWords() throws Exception { SearchRequest request = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); request.getInternalData().setForbiddenWords(Arrays.asList("characters50sssssssssssssssssssssssssssssssssssss1", "characters50sssssssssssssssssssssssssssssssssssss2", "characters50sssssssssssssssssssssssssssssssssssss3", "characters50sssssssssssssssssssssssssssssssssssss4", "characters40ssssssssssssssssssssssssssss", "aaaaa", "bbbbb")); String query = testee.addForbiddenWords(request, ""); assertThat(query.length()).isLessThan(255); }
|
NzbsOrg extends Newznab { protected String addRequiredWords(SearchRequest searchRequest, String query) { List<String> allRequiredWords = new ArrayList<>(searchRequest.getInternalData().getRequiredWords()); allRequiredWords.addAll(configProvider.getBaseConfig().getSearching().getRequiredWords()); allRequiredWords.addAll(searchRequest.getCategory().getRequiredWords()); List<String> allPossibleRequiredWords = allRequiredWords.stream().filter(x -> !(x.contains(" ") || x.contains("-") || x.contains("."))).collect(Collectors.toList()); if (allRequiredWords.size() > allPossibleRequiredWords.size()) { logger.debug("Not using some forbidden words in query because characters forbidden by newznab are contained"); } StringBuilder queryBuilder = new StringBuilder(query); for (String word : allPossibleRequiredWords) { if ((queryBuilder + word).length() < 255) { queryBuilder.append(" ").append(queryBuilder); } } query = queryBuilder.toString(); return query; } }
|
@Test public void shouldLimitQueryLengthWhenAddingRequiredWords() throws Exception { SearchRequest request = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); request.getInternalData().setRequiredWords(Arrays.asList("characters50sssssssssssssssssssssssssssssssssssss1", "characters50sssssssssssssssssssssssssssssssssssss2", "characters50sssssssssssssssssssssssssssssssssssss3", "characters50sssssssssssssssssssssssssssssssssssss4", "characters40ssssssssssssssssssssssssssss", "aaaaa", "bbbbb")); String query = testee.addRequiredWords(request, ""); assertThat(query.length()).isLessThan(255); }
|
NzbsOrg extends Newznab { @Override protected String cleanupQuery(String query) { query = super.cleanupQuery(query); if (query.length() > 255) { logger.warn("Truncating query because its length is {} but only 255 characters are supported", query.length()); StringBuilder shorterQuery = new StringBuilder(); for (String s : query.split(" ")) { if ((shorterQuery + s).length() < 255) { shorterQuery.append(" ").append(s); } else { break; } } query = shorterQuery.toString(); } return query; } }
|
@Test public void shouldTruncateLongQuery() { StringBuilder longQuery = new StringBuilder(); for (int i = 0; i < 56; i++) { longQuery.append(" " + "characters15sss"); }assertThat(longQuery.length()).isGreaterThan(255); String query = testee.cleanupQuery(longQuery.toString()); assertThat(query.length()).isLessThan(255); }
|
Newznab extends Indexer<Xml> { @Override protected List<SearchResultItem> getSearchResultItems(Xml rssRoot, SearchRequest searchRequest) { List<SearchResultItem> searchResultItems = new ArrayList<>(); final NewznabXmlRoot newznabXmlRoot = (NewznabXmlRoot) rssRoot; checkForTooManyResults(searchRequest, newznabXmlRoot); for (NewznabXmlItem item : newznabXmlRoot.getRssChannel().getItems()) { try { SearchResultItem searchResultItem = createSearchResultItem(item); searchResultItems.add(searchResultItem); } catch (NzbHydraException e) { } } return searchResultItems; } @Override NfoResult getNfo(String guid); }
|
@Test public void shouldReturnCorrectSearchResults() throws Exception { NewznabXmlRoot root = RssBuilder.builder().items(Arrays.asList(RssItemBuilder.builder("title").build())).newznabResponse(0, 1).build(); when(indexerWebAccessMock.get(any(), eq(testee.config), any())).thenReturn(root); IndexerSearchResult indexerSearchResult = testee.searchInternal(new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100), 0, 100); assertThat(indexerSearchResult.getSearchResultItems().size(), is(1)); assertThat(indexerSearchResult.getTotalResults(), is(1)); assertThat(indexerSearchResult.isHasMoreResults(), is(false)); assertThat(indexerSearchResult.isTotalResultsKnown(), is(true)); }
@Test public void shouldAccountForRejectedResults() throws Exception { List<NewznabXmlItem> items = Arrays.asList( RssItemBuilder.builder("title1").build(), RssItemBuilder.builder("title2").build(), RssItemBuilder.builder("title3").build(), RssItemBuilder.builder("title4").build(), RssItemBuilder.builder("title5").build() ); NewznabXmlRoot root = RssBuilder.builder().items(items).newznabResponse(100, 105).build(); when(indexerWebAccessMock.get(any(), eq(testee.config), any())).thenReturn(root); when(resultAcceptorMock.acceptResults(any(), any(), any())).thenAnswer(new Answer<AcceptorResult>() { @Override public AcceptorResult answer(InvocationOnMock invocation) throws Throwable { List<SearchResultItem> argument = invocation.getArgument(0); HashMultiset<String> reasonsForRejection = HashMultiset.create(); reasonsForRejection.add("some reason", 2); return new AcceptorResult(argument.subList(0, 3), reasonsForRejection); } }); IndexerSearchResult indexerSearchResult = testee.searchInternal(new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100), 0, 100); assertThat(indexerSearchResult.getSearchResultItems().size(), is(3)); assertThat(indexerSearchResult.getTotalResults(), is(105)); assertThat(indexerSearchResult.isHasMoreResults(), is(false)); assertThat(indexerSearchResult.isTotalResultsKnown(), is(true)); }
|
Newznab extends Indexer<Xml> { protected UriComponentsBuilder extendQueryUrlWithSearchIds(SearchRequest searchRequest, UriComponentsBuilder componentsBuilder) { if (!searchRequest.getIdentifiers().isEmpty()) { Map<MediaIdType, String> params = new HashMap<>(); boolean idConversionNeeded = isIdConversionNeeded(searchRequest); if (idConversionNeeded) { boolean canConvertAnyId = infoProvider.canConvertAny(searchRequest.getIdentifiers().keySet(), new HashSet<>(config.getSupportedSearchIds())); if (canConvertAnyId) { try { MediaInfo info = infoProvider.convert(searchRequest.getIdentifiers()); if (info.getImdbId().isPresent()) { if (searchRequest.getSearchType() == SearchType.MOVIE && config.getSupportedSearchIds().contains(MediaIdType.IMDB)) { params.put(MediaIdType.IMDB, info.getImdbId().get().replace("tt", "")); } if (searchRequest.getSearchType() == SearchType.TVSEARCH && config.getSupportedSearchIds().contains(MediaIdType.TVIMDB)) { params.put(MediaIdType.IMDB, info.getImdbId().get().replace("tt", "")); } } if (info.getTmdbId().isPresent()) { params.put(MediaIdType.TMDB, info.getTmdbId().get()); } if (info.getTvRageId().isPresent()) { params.put(MediaIdType.TVRAGE, info.getTvRageId().get()); } if (info.getTvMazeId().isPresent()) { params.put(MediaIdType.TVMAZE, info.getTvMazeId().get()); } if (info.getTvDbId().isPresent()) { params.put(MediaIdType.TVDB, info.getTvDbId().get()); } } catch (InfoProviderException e) { error("Error while converting search ID", e); } } else { debug("Unable to convert any of the provided IDs to any of these supported IDs: {}", Joiner.on(", ").join(config.getSupportedSearchIds())); } if (params.isEmpty()) { warn("Didn't find any usable IDs to add to search request"); } } params.forEach((key, value) -> searchRequest.getIdentifiers().putIfAbsent(key, value)); for (Map.Entry<MediaIdType, String> entry : searchRequest.getIdentifiers().entrySet()) { if (entry.getValue() == null) { continue; } if (!config.getSupportedSearchIds().contains(entry.getKey())) { continue; } componentsBuilder.queryParam(idTypeToParamValueMap.get(entry.getKey()), entry.getValue().replace("tt", "")); } } return componentsBuilder; } @Override NfoResult getNfo(String guid); }
|
@Test public void shouldGetIdsIfNoneOfTheProvidedAreSupported() throws Exception { when(infoProviderMock.canConvertAny(anySet(), anySet())).thenReturn(true); SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); searchRequest.getIdentifiers().put(MediaIdType.IMDB, "imdbId"); searchRequest.getIdentifiers().put(MediaIdType.TVMAZE, "tvmazeId"); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http: testee.config.getSupportedSearchIds().addAll(Arrays.asList(MediaIdType.TMDB, MediaIdType.TVRAGE, MediaIdType.TVMAZE)); builder = testee.extendQueryUrlWithSearchIds(searchRequest, builder); MultiValueMap<String, String> params = builder.build().getQueryParams(); assertFalse(params.containsKey("imdbid")); assertFalse(params.containsKey("tmdbid")); assertFalse(params.containsKey("rid")); assertTrue(params.containsKey("tvmazeid")); }
@Test public void shouldNotGetInfosIfAtLeastOneProvidedIsSupported() throws Exception { testee.config = new IndexerConfig(); testee.config.setSupportedSearchIds(Lists.newArrayList(MediaIdType.IMDB)); SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); searchRequest.getIdentifiers().put(MediaIdType.IMDB, "imdbId"); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http: builder = testee.extendQueryUrlWithSearchIds(searchRequest, builder); MultiValueMap<String, String> params = builder.build().getQueryParams(); assertTrue(params.containsKey("imdbid")); assertEquals(1, params.size()); verify(infoProviderMock, never()).convert(anyString(), any(MediaIdType.class)); }
@Test public void shouldRemoveTrailingTtFromImdbId() throws Exception { testee.config = new IndexerConfig(); testee.config.setSupportedSearchIds(Lists.newArrayList(MediaIdType.IMDB)); SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); searchRequest.getIdentifiers().put(MediaIdType.IMDB, "12345"); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http: builder = testee.extendQueryUrlWithSearchIds(searchRequest, builder); MultiValueMap<String, String> params = builder.build().getQueryParams(); assertTrue(params.containsKey("imdbid")); assertEquals(1, params.size()); assertEquals("12345", params.get("imdbid").get(0)); verify(infoProviderMock, never()).convert(anyString(), any(MediaIdType.class)); }
@Test public void shouldConvertIdIfNecessary() throws Exception { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); searchRequest.getIdentifiers().put(MediaIdType.IMDB, "imdbId"); testee.config.getSupportedSearchIds().add(MediaIdType.TMDB); when(infoProviderMock.canConvertAny(anySet(), anySet())).thenReturn(true); testee.extendQueryUrlWithSearchIds(searchRequest, uriComponentsBuilderMock); verify(uriComponentsBuilderMock).queryParam("tmdbid", "tmdbId"); }
@Test public void shouldNotConvertIdIfNotNecessary() throws Exception { SearchRequest searchRequest = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); searchRequest.getIdentifiers().put(MediaIdType.TMDB, "tmdbId"); testee.extendQueryUrlWithSearchIds(searchRequest, uriComponentsBuilderMock); verify(infoProviderMock, never()).convert(anyString(), eq(MediaIdType.TMDB)); }
|
IndexerForSearchSelector { protected boolean checkSearchId(Indexer indexer) { boolean needToSearchById = !searchRequest.getIdentifiers().isEmpty() && !searchRequest.getQuery().isPresent(); if (needToSearchById) { boolean canUseAnyProvidedId = !Collections.disjoint(searchRequest.getIdentifiers().keySet(), indexer.getConfig().getSupportedSearchIds()); boolean cannotSearchProvidedOrConvertableId = !canUseAnyProvidedId && !infoProvider.canConvertAny(searchRequest.getIdentifiers().keySet(), Sets.newHashSet(indexer.getConfig().getSupportedSearchIds())); boolean queryGenerationEnabled = configProvider.getBaseConfig().getSearching().getGenerateQueries().meets(searchRequest); if (cannotSearchProvidedOrConvertableId && !queryGenerationEnabled) { String message = String.format("Not using %s because the search did not provide any ID that the indexer can handle and query generation is disabled", indexer.getName()); return handleIndexerNotSelected(indexer, message, "No usable ID"); } } return true; } IndexerForSearchSelection pickIndexers(SearchRequest searchRequest); static final Pattern SCHEDULER_PATTERN; }
|
@Test public void shouldCheckIdConversion() { Set<MediaIdType> supported = Sets.newSet(MediaIdType.TVMAZE, MediaIdType.TVDB); Set<MediaIdType> provided = Sets.newSet(MediaIdType.TVMAZE); when(searchRequest.getQuery()).thenReturn(Optional.empty()); when(infoProviderMock.canConvertAny(provided, supported)).thenReturn(true); assertTrue(testee.checkSearchId(indexer)); when(searchRequest.getQuery()).thenReturn(Optional.of("a query")); when(infoProviderMock.canConvertAny(provided, supported)).thenReturn(false); assertTrue(testee.checkSearchId(indexer)); provided = new HashSet<>(); when(searchRequest.getQuery()).thenReturn(Optional.empty()); verify(infoProviderMock, never()).canConvertAny(provided, supported); assertTrue(testee.checkSearchId(indexer)); }
|
Newznab extends Indexer<Xml> { protected Xml getAndStoreResultToDatabase(URI uri, IndexerApiAccessType apiAccessType) throws IndexerAccessException { Xml response = getAndStoreResultToDatabase(uri, Xml.class, apiAccessType); if (response instanceof NewznabXmlError) { handleRssError((NewznabXmlError) response, uri.toString()); } else if (!(response instanceof NewznabXmlRoot)) { throw new UnknownResponseException("Indexer returned unknown response"); } return response; } @Override NfoResult getNfo(String guid); }
|
@Test(expected = IndexerAuthException.class) public void shouldThrowAuthException() throws Exception { doReturn(new NewznabXmlError("101", "Wrong API key")).when(testee).getAndStoreResultToDatabase(any(), eq(Xml.class), eq(IndexerApiAccessType.SEARCH)); doNothing().when(testee).handleFailure(errorMessageCaptor.capture(), disabledPermanentlyCaptor.capture(), any(IndexerApiAccessType.class), any(), indexerApiAccessResultCaptor.capture()); testee.searchInternal(new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100), 0, 100); }
@Test(expected = IndexerErrorCodeException.class) public void shouldThrowErrorCodeWhen100ApiHitLimits() throws Exception { doReturn(new NewznabXmlError("100", "Daily Hits Limit Reached\"")).when(testee).getAndStoreResultToDatabase(any(), eq(Xml.class), eq(IndexerApiAccessType.SEARCH)); doNothing().when(testee).handleFailure(errorMessageCaptor.capture(), disabledPermanentlyCaptor.capture(), any(IndexerApiAccessType.class), any(), indexerApiAccessResultCaptor.capture()); testee.searchInternal(new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100), 0, 100); }
@Test(expected = IndexerProgramErrorException.class) public void shouldThrowProgramErrorCodeException() throws Exception { doReturn(new NewznabXmlError("200", "Whatever")).when(testee).getAndStoreResultToDatabase(any(), eq(Xml.class), eq(IndexerApiAccessType.SEARCH)); doNothing().when(testee).handleFailure(errorMessageCaptor.capture(), disabledPermanentlyCaptor.capture(), any(IndexerApiAccessType.class), any(), indexerApiAccessResultCaptor.capture()); testee.searchInternal(new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100), 0, 100); }
@Test(expected = IndexerErrorCodeException.class) public void shouldThrowErrorCodeThatsNotMyFaultException() throws Exception { doReturn(new NewznabXmlError("123", "Whatever")).when(testee).getAndStoreResultToDatabase(any(), eq(Xml.class), eq(IndexerApiAccessType.SEARCH)); doNothing().when(testee).handleFailure(errorMessageCaptor.capture(), disabledPermanentlyCaptor.capture(), any(IndexerApiAccessType.class), any(), indexerApiAccessResultCaptor.capture()); testee.searchInternal(new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100), 0, 100); }
|
Newznab extends Indexer<Xml> { protected void parseAttributes(NewznabXmlItem item, SearchResultItem searchResultItem) { Map<String, String> attributes = item.getNewznabAttributes().stream().collect(Collectors.toMap(NewznabAttribute::getName, NewznabAttribute::getValue, (a, b) -> b)); List<Integer> newznabCategories = item.getNewznabAttributes().stream().filter(x -> x.getName().equals("category") && !"None".equals(x.getValue()) && !Strings.isNullOrEmpty(x.getValue())).map(newznabAttribute -> Integer.parseInt(newznabAttribute.getValue())).collect(Collectors.toList()); searchResultItem.setAttributes(attributes); if (attributes.containsKey("usenetdate")) { tryParseDate(attributes.get("usenetdate")).ifPresent(searchResultItem::setUsenetDate); } if (attributes.containsKey("password")) { String passwordValue = attributes.get("password"); try { if (Integer.parseInt(passwordValue) > 0) { searchResultItem.setPassworded(true); } } catch (NumberFormatException e) { searchResultItem.setPassworded(true); } } if (attributes.containsKey("nfo")) { searchResultItem.setHasNfo(attributes.get("nfo").equals("1") ? HasNfo.YES : HasNfo.NO); } if (attributes.containsKey("info") && (config.getBackend() == BackendType.NNTMUX || config.getBackend() == BackendType.NZEDB)) { searchResultItem.setHasNfo(HasNfo.YES); } Arrays.asList("coverurl", "cover").forEach(x -> { if (attributes.containsKey(x) && !attributes.get(x).equals("not available") && (attributes.get(x).toLowerCase().endsWith(".jpg") || attributes.get(x).toLowerCase().endsWith(".jpeg") || attributes.get(x).toLowerCase().endsWith(".png"))) { searchResultItem.setCover(attributes.get(x)); } }); if (attributes.containsKey("poster") && !attributes.get("poster").equals("not available")) { searchResultItem.setPoster(attributes.get("poster")); } if (attributes.containsKey("group") && !attributes.get("group").equals("not available")) { searchResultItem.setGroup(attributes.get("group")); } if (attributes.containsKey("files")) { searchResultItem.setFiles(Integer.valueOf(attributes.get("files"))); } if (attributes.containsKey("comments")) { searchResultItem.setCommentsCount(Integer.valueOf(attributes.get("comments"))); } if (attributes.containsKey("grabs")) { searchResultItem.setGrabs(Integer.valueOf(attributes.get("grabs"))); } if (attributes.containsKey("guid")) { searchResultItem.setIndexerGuid(attributes.get("guid")); } if (attributes.containsKey("size")) { searchResultItem.setSize(Long.valueOf(attributes.get("size"))); } if (attributes.containsKey("source")) { searchResultItem.setSource(attributes.get("source")); } computeCategory(searchResultItem, newznabCategories); if (searchResultItem.getHasNfo() == HasNfo.MAYBE && (config.getBackend() == BackendType.NNTMUX || config.getBackend() == BackendType.NZEDB)) { searchResultItem.setHasNfo(HasNfo.NO); } if (!searchResultItem.getGroup().isPresent() && !Strings.isNullOrEmpty(item.getDescription()) && item.getDescription().contains("Group:")) { Matcher matcher = GROUP_PATTERN.matcher(item.getDescription()); if (matcher.matches() && !Objects.equals(matcher.group(1), "not available")) { searchResultItem.setGroup(matcher.group(1)); } } try { if (searchResultItem.getCategory().getSearchType() == SearchType.TVSEARCH) { if (searchResultItem.getAttributes().containsKey("season")) { searchResultItem.getAttributes().put("season", searchResultItem.getAttributes().get("season").replaceAll("[sS]", "")); } if (searchResultItem.getAttributes().containsKey("episode")) { searchResultItem.getAttributes().put("episode", searchResultItem.getAttributes().get("episode").replaceAll("[eE]", "")); } if (searchResultItem.getAttributes().containsKey("showtitle")) { searchResultItem.getAttributes().put("showtitle", searchResultItem.getAttributes().get("showtitle")); } if (!attributes.containsKey("season") || !attributes.containsKey("episode") || !attributes.containsKey("showtitle")) { Matcher matcher = TV_PATTERN.matcher(item.getTitle()); if (matcher.find()) { putGroupMatchIfFound(searchResultItem, matcher, "season", "season"); putGroupMatchIfFound(searchResultItem, matcher, "season2", "season"); putGroupMatchIfFound(searchResultItem, matcher, "episode", "episode"); putGroupMatchIfFound(searchResultItem, matcher, "episode2", "episode"); putGroupMatchIfFound(searchResultItem, matcher, "showtitle", "showtitle"); } } if (attributes.containsKey("season")) { attributes.put("season", tryParseInt(attributes.get("season").replaceAll("\\D", "").toLowerCase())); } if (attributes.containsKey("episode")) { attributes.put("episode", tryParseInt(attributes.get("episode").replaceAll("\\D", "").toLowerCase())); } if (attributes.containsKey("showtitle")) { attributes.put("showtitle", attributes.get("showtitle").replaceAll("\\W", "").toLowerCase()); } } } catch (NumberFormatException e) { } } @Override NfoResult getNfo(String guid); }
|
@Test public void shouldUseIndexersCategoryMappingToBuildOriginalCategoryName() throws Exception { testee.config.getCategoryMapping().setCategories(Arrays.asList(new MainCategory(5000, "TV", Arrays.asList(new SubCategory(5040, "HD"))))); NewznabXmlItem rssItem = buildBasicRssItem(); rssItem.getNewznabAttributes().add(new NewznabAttribute("category", "5040")); rssItem.getNewznabAttributes().add(new NewznabAttribute("category", "5000")); SearchResultItem searchResultItem = new SearchResultItem(); Category category = new Category(); category.setSearchType(SearchType.TVSEARCH); searchResultItem.setCategory(category); testee.parseAttributes(rssItem, searchResultItem); assertThat(searchResultItem.getOriginalCategory(), is("TV HD")); rssItem.getNewznabAttributes().clear(); rssItem.getNewznabAttributes().add(new NewznabAttribute("category", "1234")); testee.parseAttributes(rssItem, searchResultItem); assertThat(searchResultItem.getOriginalCategory(), is("N/A")); }
|
PropertyUtils { public UploadProperties getUploadProperties(String[] args) throws ParseException, MissingConfigException { CommandLine cmd = parser.parse(OPTIONS, args); String user = cmd.getOptionValue(FLAG_USER); if (user == null) { throw new MissingConfigException(FLAG_USER); } String password = cmd.getOptionValue(FLAG_PASSWORD); if (password == null) { throw new MissingConfigException(FLAG_PASSWORD); } String server = cmd.getOptionValue(FLAG_SFTP_SERVER); if (server == null) { throw new MissingConfigException(FLAG_SFTP_SERVER); } String localDir = cmd.getOptionValue(FLAG_LOCAL_DIRECTORY); if (localDir == null) { throw new MissingConfigException(FLAG_LOCAL_DIRECTORY); } int port; try { port = Integer.parseInt(cmd.getOptionValue(FLAG_PORT)); } catch (NumberFormatException e) { throw new MissingConfigException(FLAG_PORT); } return new UploadProperties(user, password, server, localDir, port); } PropertyUtils(CommandLineParser parser); UploadProperties getUploadProperties(String[] args); static final String KEY_USER; static final String KEY_PASSWORD; static final String KEY_SFTP_SERVER; static final String KEY_LOCAL_DIRECTORY; static final String KEY_PORT; final static Options OPTIONS; }
|
@Test(expected = MissingConfigException.class) public void missingUser() throws ParseException, MissingConfigException { String[] args = new String[] { "-pass", "password", "-s", "server", "-d", "localDir", "-port", "22" }; propUtils.getUploadProperties(args); }
@Test public void parseProperties() throws ParseException, MissingConfigException { String[] args = new String[] { "-u", "user", "-pass", "password", "-s", "server", "-d", "localDir", "-port", "22" }; UploadProperties props = propUtils.getUploadProperties(args); Assert.assertNotNull("UploadProperties should not be null", props); Assert.assertEquals("user", props.getUser()); Assert.assertEquals("password", props.getPassword()); Assert.assertEquals("server", props.getSftpServer()); Assert.assertEquals("localDir", props.getLocalDir()); }
@Test(expected = MissingArgumentException.class) public void missingUserValue() throws ParseException, MissingConfigException { String[] args = new String[] { "-u", "-pass", "password", "-s", "server", "-d", "localDir", "-port", "22" }; propUtils.getUploadProperties(args); }
@Test(expected = MissingConfigException.class) public void missingPassword() throws ParseException, MissingConfigException { String[] args = new String[] { "-u", "user", "-s", "server", "-d", "localDir", "-port", "22" }; propUtils.getUploadProperties(args); }
@Test(expected = MissingArgumentException.class) public void missingPasswordValue() throws ParseException, MissingConfigException { String[] args = new String[] { "-u", "user", "-pass", "-s", "server", "-d", "localDir", "-port", "22" }; propUtils.getUploadProperties(args); }
@Test(expected = MissingConfigException.class) public void missingServer() throws ParseException, MissingConfigException { String[] args = new String[] { "-u", "user", "-pass", "password", "-d", "localDir", "-port", "22" }; propUtils.getUploadProperties(args); }
@Test(expected = MissingArgumentException.class) public void missingServerValue() throws ParseException, MissingConfigException { String[] args = new String[] { "-u", "user", "-pass", "password", "-s", "-d", "localDir", "-port", "22" }; propUtils.getUploadProperties(args); }
@Test(expected = MissingConfigException.class) public void missingLocalDir() throws ParseException, MissingConfigException { String[] args = new String[] { "-u", "user", "-pass", "password", "-s", "server", "-port", "22" }; propUtils.getUploadProperties(args); }
@Test(expected = MissingArgumentException.class) public void missingLocalDirValue() throws ParseException, MissingConfigException { String[] args = new String[] { "-u", "user", "-pass", "password", "-s", "server", "-d", "-port", "22" }; propUtils.getUploadProperties(args); }
@Test(expected = MissingConfigException.class) public void missingPort() throws ParseException, MissingConfigException { String[] args = new String[] { "-u", "user", "-pass", "password", "-s", "server", "-d", "localDir" }; propUtils.getUploadProperties(args); }
@Test(expected = MissingArgumentException.class) public void missingPortValue() throws ParseException, MissingConfigException { String[] args = new String[] { "-u", "user", "-pass", "password", "-s", "server", "-d", "localDir", "-port" }; propUtils.getUploadProperties(args); }
|
MongoQueryConverter { public Query convert(String entityName, NeutralQuery neutralQuery) { LOG.debug(">>>MongoQueryConverter.convery(entityName, neutralQuery)"); return convert(entityName, neutralQuery, false); } MongoQueryConverter(); Query convert(String entityName, NeutralQuery neutralQuery); Query convert(String entityName, NeutralQuery neutralQuery, boolean allFields); List<Criteria> convertToCriteria(String entityName, NeutralQuery neutralQuery, NeutralSchema entitySchema); }
|
@Test public void testNonEmptyIncludeFieldConvert() { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setIncludeFieldString("name"); Query query = mongoQueryConverter.convert("section", neutralQuery); assertNotNull("Should not be null", query); DBObject obj = query.getFieldsObject(); assertNotNull("Should not be null", obj); assertEquals("Should match", 1, obj.get("body.name")); assertEquals("Should match", 1, obj.get("type")); assertEquals("Should match", 1, obj.get("metaData")); assertNull("Should be null", obj.get("body")); }
@Test public void testIncludeFieldConvert() { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setIncludeFieldString("populationServed,uniqueSectionCode"); Query query = mongoQueryConverter.convert("section", neutralQuery); assertNotNull("Should not be null", query); DBObject obj = query.getFieldsObject(); assertNotNull("Should not be null", obj); assertEquals("Should match", 1, obj.get("body.populationServed")); assertEquals("Should match", 1, obj.get("body.uniqueSectionCode")); }
@Test public void testOffsetAndLimitConvert() { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(10); neutralQuery.setLimit(100); Query query = mongoQueryConverter.convert("section", neutralQuery); assertNotNull("Should not be null", query); assertEquals("Should match", 10, query.getSkip()); assertEquals("Should match", 100, query.getLimit()); }
@Test public void testSortConvert() { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setSortBy("populationServed"); neutralQuery.setSortOrder(NeutralQuery.SortOrder.ascending); Query query = mongoQueryConverter.convert("section", neutralQuery); assertNotNull("Should not be null", query); DBObject obj = query.getSortObject(); assertEquals("Should match", 1, obj.get("body.populationServed")); neutralQuery = new NeutralQuery(); neutralQuery.setSortBy("populationServed"); neutralQuery.setSortOrder(NeutralQuery.SortOrder.descending); query = mongoQueryConverter.convert("section", neutralQuery); assertNotNull("Should not be null", query); obj = query.getSortObject(); assertEquals("Should match", -1, obj.get("body.populationServed")); neutralQuery = new NeutralQuery(); neutralQuery.setSortBy(null); query = mongoQueryConverter.convert("section", neutralQuery); assertNotNull("Should not be null", query); assertNull("Should be null", query.getSortObject()); neutralQuery = new NeutralQuery(); neutralQuery.setSortBy("populationServed"); neutralQuery.setSortOrder(null); query = mongoQueryConverter.convert("section", neutralQuery); assertNotNull("Should not be null", query); obj = query.getSortObject(); assertEquals("Should match", 1, obj.get("body.populationServed")); }
@Test(expected = QueryParseException.class) public void testPIISort() throws QueryParseException { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setSortBy("birthData.birthDate"); neutralQuery.setSortOrder(NeutralQuery.SortOrder.ascending); mongoQueryConverter.convert("student", neutralQuery); }
@Test(expected = QueryParseException.class) public void testPIISearchGreaterThan() throws QueryParseException { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.addCriteria(new NeutralCriteria("birthData.birthDate", ">", "1960-01-01")); mongoQueryConverter.convert("student", neutralQuery); }
@Test(expected = QueryParseException.class) public void testPIISearchLessThan() throws QueryParseException { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.addCriteria(new NeutralCriteria("birthData.birthDate", "<", "1960-01-01")); mongoQueryConverter.convert("student", neutralQuery); }
@Test(expected = QueryParseException.class) public void testPIISearchNotEqual() throws QueryParseException { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.addCriteria(new NeutralCriteria("birthData.birthDate", "~", "1960-01-01")); mongoQueryConverter.convert("student", neutralQuery); }
@Test public void testPIISearchEquals() { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.addCriteria(new NeutralCriteria("birthData.birthDate", "=", "1960-01-01")); Query query = mongoQueryConverter.convert("student", neutralQuery); assertNotNull("Should not be null", query); DBObject obj = query.getQueryObject(); assertNotNull("Should not be null", obj); }
@Test public void testFieldsConvert() { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.addCriteria(new NeutralCriteria("populationServed", "=", "Regular Students")); Query query = mongoQueryConverter.convert("section", neutralQuery); assertNotNull("Should not be null", query); DBObject obj = query.getQueryObject(); assertNotNull("Should not be null", obj); assertEquals("Should match", "Regular Students", obj.get("body.populationServed")); neutralQuery = new NeutralQuery(); neutralQuery.addCriteria(new NeutralCriteria("populationServed", ">=", "Regular Students")); query = mongoQueryConverter.convert("section", neutralQuery); assertNotNull("Should not be null", query); obj = query.getQueryObject(); assertNotNull("Should not be null", obj); DBObject obj1 = (DBObject) obj.get("body.populationServed"); assertEquals("Should match", "Regular Students", obj1.get("$gte")); neutralQuery = new NeutralQuery(); neutralQuery.addCriteria(new NeutralCriteria("populationServed", "<=", "Regular Students")); query = mongoQueryConverter.convert("section", neutralQuery); assertNotNull("Should not be null", query); obj = query.getQueryObject(); assertNotNull("Should not be null", obj); obj1 = (DBObject) obj.get("body.populationServed"); assertEquals("Should match", "Regular Students", obj1.get("$lte")); List<String> list = new ArrayList<String>(); list.add("Regular Students"); list.add("Irregular Students"); neutralQuery = new NeutralQuery(); neutralQuery.addCriteria(new NeutralCriteria("populationServed", NeutralCriteria.CRITERIA_IN, list)); query = mongoQueryConverter.convert("section", neutralQuery); assertNotNull("Should not be null", query); obj = query.getQueryObject(); assertNotNull("Should not be null", obj); obj1 = (DBObject) obj.get("body.populationServed"); assertNotNull(obj1.get("$in")); neutralQuery = new NeutralQuery(); neutralQuery.addCriteria(new NeutralCriteria("populationServed", NeutralCriteria.CRITERIA_EXISTS, true)); query = mongoQueryConverter.convert("section", neutralQuery); assertNotNull("Should not be null", query); obj = query.getQueryObject(); assertNotNull("Should not be null", obj); obj1 = (DBObject) obj.get("body.populationServed"); assertNotNull(obj1.get("$exists")); }
@Test(expected = QueryParseException.class) public void testInNotList() throws QueryParseException { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.addCriteria(new NeutralCriteria("populationServed", NeutralCriteria.CRITERIA_IN, "Regular Students")); mongoQueryConverter.convert("section", neutralQuery); }
@Test public void testOrConvert() { NeutralQuery mainQuery = new NeutralQuery(); mainQuery.addCriteria(new NeutralCriteria("economicDisadvantaged=true")); NeutralQuery orQuery1 = new NeutralQuery(); NeutralQuery orQuery2 = new NeutralQuery(); orQuery2.addCriteria(new NeutralCriteria("studentUniqueStateId", "=", "000000054")); mainQuery.addOrQuery(orQuery1); mainQuery.addOrQuery(orQuery2); Query query = mongoQueryConverter.convert("student", mainQuery); assertNotNull("Should not be null", query); DBObject obj = query.getQueryObject(); assertNotNull("Should not be null", obj); assertNotNull("Should not be null", obj.get("$or")); assertTrue(((BasicBSONList) obj.get("$or")).size() == 1); }
@Test public void testEmptyIncludeFieldConvert() { NeutralQuery neutralQuery = new NeutralQuery(); Query query = mongoQueryConverter.convert("section", neutralQuery); assertNotNull("Should not be null", query); DBObject obj = query.getFieldsObject(); assertNotNull("Should not be null", obj); assertEquals("Should match", 1, obj.get("body")); assertEquals("Should match", 1, obj.get("type")); assertEquals("Should match", 1, obj.get("metaData")); }
@Test public void testEmbeddedFieldConvert() { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setEmbeddedFields(Arrays.asList("studentSectionAssociation", "teacherSectionAssociation")); Query query = mongoQueryConverter.convert("section", neutralQuery); assertNotNull("Should not be null", query); DBObject obj = query.getFieldsObject(); assertNotNull("Should not be null", obj); assertEquals("Should match", 1, obj.get("studentSectionAssociation")); assertEquals("Should match", 1, obj.get("teacherSectionAssociation")); assertEquals("Should match", 1, obj.get("body")); assertEquals("Should match", 1, obj.get("type")); assertEquals("Should match", 1, obj.get("metaData")); }
|
CurrentTenantHolder { public static String pop() { return getCurrentStack().pop(); } static void push(String tenantId); static String pop(); static String getCurrentTenant(); }
|
@Test(expected = EmptyStackException.class) public void testEmptyHolderPop() { CurrentTenantHolder.pop(); }
|
CurrentTenantHolder { public static String getCurrentTenant() { return getCurrentStack().peek(); } static void push(String tenantId); static String pop(); static String getCurrentTenant(); }
|
@Test(expected = EmptyStackException.class) public void testEmptyHolderPeek() { CurrentTenantHolder.getCurrentTenant(); }
|
DeltaJournal implements InitializingBean { public void journal(Collection<String> ids, String collection, boolean isDelete) { if ( collection.equals("applicationAuthorization") ) { return; } if (deltasEnabled && !TenantContext.isSystemCall()) { if (subdocCollectionsToCollapse.containsKey(collection)) { journalCollapsedSubDocs(ids, collection); } long now = new Date().getTime(); Update update = new Update(); update.set("t", now); update.set("c", collection); if (isDelete) { update.set("d", now); } else { update.set("u", now); } for (String id : ids) { List<byte[]> idbytes = getByteId(id); if(idbytes.size() > 1) { update.set("i", idbytes.subList(1, idbytes.size())); } template.upsert(Query.query(where("_id").is(idbytes.get(0))), update, DELTA_COLLECTION); } } } @Override void afterPropertiesSet(); void journal(Collection<String> ids, String collection, boolean isDelete); static List<byte[]> getByteId(String id); static String getEntityId(Map<String, Object> deltaRecord); void journal(String id, String collection, boolean isDelete); void journalCollapsedSubDocs(Collection<String> ids, String collection); void journalPurge(long timeOfPurge); Iterator<Map<String, Object>> findDeltaRecordBetween(final long start, final long end); void removeDeltaJournals(String tenant, long cleanUptoTime); static final String DELTA_COLLECTION; static final String PURGE; }
|
@Test public void testIgnoredOnSystemCall() { TenantContext.setIsSystemCall(true); deltaJournal.journal("test", "userSession", false); verify(template, never()).upsert(any(Query.class), any(Update.class), anyString()); TenantContext.setIsSystemCall(false); }
|
DeltaJournal implements InitializingBean { public void journalCollapsedSubDocs(Collection<String> ids, String collection) { LOG.debug("journaling {} to {}", ids, subdocCollectionsToCollapse.get(collection)); Set<String> newIds = new HashSet<String>(); for (String id : ids) { newIds.add(id.split("_id")[0] + "_id"); } journal(newIds, subdocCollectionsToCollapse.get(collection), false); } @Override void afterPropertiesSet(); void journal(Collection<String> ids, String collection, boolean isDelete); static List<byte[]> getByteId(String id); static String getEntityId(Map<String, Object> deltaRecord); void journal(String id, String collection, boolean isDelete); void journalCollapsedSubDocs(Collection<String> ids, String collection); void journalPurge(long timeOfPurge); Iterator<Map<String, Object>> findDeltaRecordBetween(final long start, final long end); void removeDeltaJournals(String tenant, long cleanUptoTime); static final String DELTA_COLLECTION; static final String PURGE; }
|
@Test public void testJournalCollapsedSubDocs() throws DecoderException { String assessment1id = "1234567890123456789012345678901234567890"; String assessment2id = "1234567890123456789012345678901234567892"; deltaJournal.journal( Arrays.asList(assessment1id + "_id1234567890123456789012345678901234567891_id", assessment1id + "_id1234567890123456789012345678901234567892_id", assessment2id + "_id1234567890123456789012345678901234567891_id"), "assessmentItem", false); Query q1 = Query.query(Criteria.where("_id").is(Hex.decodeHex(assessment1id.toCharArray()))); Query q2 = Query.query(Criteria.where("_id").is(Hex.decodeHex(assessment2id.toCharArray()))); BaseMatcher<Update> updateMatcher = new BaseMatcher<Update>() { @Override public boolean matches(Object arg0) { @SuppressWarnings("unchecked") Map<String, Object> o = (Map<String, Object>) ((Update) arg0).getUpdateObject().get("$set"); return o.get("c").equals("assessment"); } @Override public void describeTo(Description arg0) { arg0.appendText("Update with 'c' set to 'assessment'"); } }; verify(template).upsert(eq(q1), argThat(updateMatcher), eq("deltas")); verify(template).upsert(eq(q2), argThat(updateMatcher), eq("deltas")); }
|
DeltaJournal implements InitializingBean { public void journalPurge(long timeOfPurge) { String id = uuidGeneratorStrategy.generateId(); Update update = new Update(); update.set("t", timeOfPurge); update.set("c", PURGE); TenantContext.setIsSystemCall(false); template.upsert(Query.query(where("_id").is(id)), update, DELTA_COLLECTION); } @Override void afterPropertiesSet(); void journal(Collection<String> ids, String collection, boolean isDelete); static List<byte[]> getByteId(String id); static String getEntityId(Map<String, Object> deltaRecord); void journal(String id, String collection, boolean isDelete); void journalCollapsedSubDocs(Collection<String> ids, String collection); void journalPurge(long timeOfPurge); Iterator<Map<String, Object>> findDeltaRecordBetween(final long start, final long end); void removeDeltaJournals(String tenant, long cleanUptoTime); static final String DELTA_COLLECTION; static final String PURGE; }
|
@Test public void testJournalPurge() { final long time = new Date().getTime(); deltaJournal.journalPurge(time); BaseMatcher<Update> updateMatcher = new BaseMatcher<Update>() { @Override public boolean matches(Object arg0) { @SuppressWarnings("unchecked") Map<String, Object> o = (Map<String, Object>) ((Update) arg0).getUpdateObject().get("$set"); if (o.get("c").equals("purge") && o.get("t").equals(time)) { return true; } return false; } @Override public void describeTo(Description arg0) { arg0.appendText("Update with 'c' set to 'purge' and 't' set to time of purge"); } }; verify(template, Mockito.times(1)).upsert(Mockito.any(Query.class), argThat(updateMatcher), Mockito.eq("deltas")); }
|
DeltaJournal implements InitializingBean { public static List<byte[]> getByteId(String id) { try { List<byte[]> result = new ArrayList<byte[]>(); int idLength = id.length(); if(idLength < 43) { LOG.error("Short ID encountered: {}", id); return Arrays.asList(id.getBytes()); } for(String idPart: id.split("_id")){ if(!idPart.isEmpty()){ idPart = idPart.replaceAll("[^\\p{XDigit}]", ""); result.add(0, Hex.decodeHex(idPart.toCharArray())); } } return result; } catch (DecoderException e) { LOG.error("Decoder exception while decoding {}", id, e); return Arrays.asList(id.getBytes()); } } @Override void afterPropertiesSet(); void journal(Collection<String> ids, String collection, boolean isDelete); static List<byte[]> getByteId(String id); static String getEntityId(Map<String, Object> deltaRecord); void journal(String id, String collection, boolean isDelete); void journalCollapsedSubDocs(Collection<String> ids, String collection); void journalPurge(long timeOfPurge); Iterator<Map<String, Object>> findDeltaRecordBetween(final long start, final long end); void removeDeltaJournals(String tenant, long cleanUptoTime); static final String DELTA_COLLECTION; static final String PURGE; }
|
@Test public void testGetByteId() throws DecoderException { String id = "1234567890123456789012345678901234567890"; String superid = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; String extraid = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; assertEquals(id, Hex.encodeHexString(DeltaJournal.getByteId(id + "_id").get(0))); assertEquals(id, Hex.encodeHexString(DeltaJournal.getByteId(superid + "_id" + id + "_id").get(0))); assertEquals(superid, Hex.encodeHexString(DeltaJournal.getByteId(superid + "_id" + id + "_id").get(1))); assertEquals(superid, Hex.encodeHexString(DeltaJournal.getByteId(extraid + "_id" + superid + "_id" + id + "_id").get(1))); assertEquals(extraid, Hex.encodeHexString(DeltaJournal.getByteId(extraid + "_id" + superid + "_id" + id + "_id").get(2))); }
|
DeltaJournal implements InitializingBean { public static String getEntityId(Map<String, Object> deltaRecord) { Object deltaId = deltaRecord.get("_id"); if(deltaId instanceof String){ return (String) deltaId; } else if (deltaId instanceof byte[]) { StringBuilder id = new StringBuilder(""); @SuppressWarnings("unchecked") List<byte[]> parts = (List<byte[]>) deltaRecord.get("i"); if (parts != null) { for (byte[] part : parts) { id.insert(0, Hex.encodeHexString(part) + "_id"); } } id.append(Hex.encodeHexString((byte[]) deltaId) + "_id"); return id.toString(); } else { throw new IllegalArgumentException("Illegal id: " + deltaId); } } @Override void afterPropertiesSet(); void journal(Collection<String> ids, String collection, boolean isDelete); static List<byte[]> getByteId(String id); static String getEntityId(Map<String, Object> deltaRecord); void journal(String id, String collection, boolean isDelete); void journalCollapsedSubDocs(Collection<String> ids, String collection); void journalPurge(long timeOfPurge); Iterator<Map<String, Object>> findDeltaRecordBetween(final long start, final long end); void removeDeltaJournals(String tenant, long cleanUptoTime); static final String DELTA_COLLECTION; static final String PURGE; }
|
@Test public void testGetEntityId() throws DecoderException { String id = "1234567890123456789012345678901234567890"; String superid = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; String extraid = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; Map<String, Object> delta = new HashMap<String, Object>(); delta.put("_id", Hex.decodeHex(id.toCharArray())); assertEquals(id + "_id", DeltaJournal.getEntityId(delta)); delta.put("i", Arrays.asList(Hex.decodeHex(superid.toCharArray()))); assertEquals(superid + "_id" + id + "_id", DeltaJournal.getEntityId(delta)); delta.put("i", Arrays.asList(Hex.decodeHex(superid.toCharArray()), Hex.decodeHex(extraid.toCharArray()))); assertEquals(extraid + "_id" + superid + "_id" + id + "_id", DeltaJournal.getEntityId(delta)); }
|
SubDocAccessor { public Location subDoc(String docType) { return locations.get(docType); } SubDocAccessor(MongoTemplate template, UUIDGeneratorStrategy didGenerator,
INaturalKeyExtractor naturalKeyExtractor); LocationBuilder store(String type); Location createLocation(String type, String parentColl, Map<String, String> lookup, String subField); boolean isSubDoc(String docType); Location subDoc(String docType); static void main(String[] args); }
|
@Test public void testSingleInsert() { MongoEntity entity = new MongoEntity("studentSectionAssociation", studentSectionAssociation); assertTrue(underTest.subDoc("studentSectionAssociation").create(entity)); verify(sectionCollection).update(argThat(new ArgumentMatcher<DBObject>() { @Override public boolean matches(Object argument) { DBObject query = (DBObject) argument; DBObject sectionQuery = (DBObject) query.get("studentSectionAssociation._id"); return query.get("_id").equals(SECTION1) && sectionQuery != null && sectionQuery.get("$nin").equals(Arrays.asList("subdocid")); } }), argThat(new ArgumentMatcher<DBObject>() { @Override @SuppressWarnings("unchecked") public boolean matches(Object argument) { DBObject updateObject = (DBObject) argument; Map<String, Object> push = (Map<String, Object>) updateObject.get("$pushAll"); if (push == null) { return false; } Collection<Object> toPush = push.values(); if (toPush.size() != 1) { return false; } Object[] studentSectionsToPush = (Object[]) toPush.iterator().next(); List<String> ssaIds = new ArrayList<String>(push.keySet()); return ((Map<String, Map<String, Object>>) studentSectionsToPush[0]).get("body").get("beginDate") .equals(BEGINDATE) && ssaIds.get(0).equals("studentSectionAssociation"); } }), eq(false), eq(false), eq(WriteConcern.SAFE)); }
@Test public void testMultipleInsert() { Entity ssa1 = new MongoEntity("studentSectionAssociation", studentSectionAssociation); Entity ssa2 = new MongoEntity("studentSectionAssociation", new HashMap<String, Object>( studentSectionAssociation)); ssa2.getBody().put("studentId", STUDENT2); Entity ssa3 = new MongoEntity("studentSectionAssociation", new HashMap<String, Object>( studentSectionAssociation)); ssa3.getBody().put("sectionId", SECTION2); assertTrue(underTest.subDoc("studentSectionAssociation").insert(Arrays.asList(ssa1, ssa2, ssa3))); verify(sectionCollection).update(argThat(new ArgumentMatcher<DBObject>() { @Override public boolean matches(Object argument) { DBObject query = (DBObject) argument; DBObject sectionQuery = (DBObject) query.get("studentSectionAssociation._id"); return query.get("_id").equals(SECTION2) && sectionQuery != null && sectionQuery.get("$nin").equals(Arrays.asList("subdocid")); } }), argThat(new ArgumentMatcher<DBObject>() { @Override @SuppressWarnings("unchecked") public boolean matches(Object argument) { DBObject updateObject = (DBObject) argument; Map<String, Object> push = (Map<String, Object>) updateObject.get("$pushAll"); if (push == null) { return false; } Collection<Object> toPush = push.values(); if (toPush.size() != 1) { return false; } Object[] studentSectionsToPush = (Object[]) toPush.iterator().next(); List<String> ssaIds = new ArrayList<String>(push.keySet()); return ((Map<String, Map<String, Object>>) studentSectionsToPush[0]).get("body").get("beginDate") .equals(BEGINDATE) && ssaIds.get(0).equals("studentSectionAssociation"); } }), eq(false), eq(false), eq(WriteConcern.SAFE)); verify(sectionCollection).update(argThat(new ArgumentMatcher<DBObject>() { @Override public boolean matches(Object argument) { DBObject query = (DBObject) argument; DBObject sectionQuery = (DBObject) query.get("studentSectionAssociation._id"); return query.get("_id").equals(SECTION1) && sectionQuery != null && sectionQuery.get("$nin").equals(Arrays.asList("subdocid", "subdocid")); } }), argThat(new ArgumentMatcher<DBObject>() { @Override @SuppressWarnings("unchecked") public boolean matches(Object argument) { DBObject updateObject = (DBObject) argument; Map<String, Object> push = (Map<String, Object>) updateObject.get("$pushAll"); if (push == null) { return false; } Collection<Object> toPush = push.values(); if (toPush.size() != 1) { return false; } Object[] studentSectionsToPush = (Object[]) toPush.iterator().next(); return studentSectionsToPush.length == 2; } }), eq(false), eq(false), eq(WriteConcern.SAFE)); }
@Test public void testMakeSubDocQuery() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Query originalQuery = new Query(Criteria.where("_id").is("parent_idchild").and("someProperty").is("someValue")); DBObject parentQuery = underTest.subDoc("studentSectionAssociation").toSubDocQuery(originalQuery, true); DBObject childQuery = underTest.subDoc("studentSectionAssociation").toSubDocQuery(originalQuery, false); assertEquals("someValue", parentQuery.get("studentSectionAssociation.someProperty")); assertEquals("parent_id", parentQuery.get("_id")); assertEquals("parent_idchild", parentQuery.get("studentSectionAssociation._id")); assertEquals("someValue", childQuery.get("studentSectionAssociation.someProperty")); assertEquals("parent_idchild", childQuery.get("studentSectionAssociation._id")); assertNotNull(childQuery.get("_id")); }
@Test public void testSearchByParentId() { Query originalQuery = new Query(Criteria.where("body.sectionId").in("parentId1", "parentId2")); DBObject parentQuery = underTest.subDoc("studentSectionAssociation").toSubDocQuery(originalQuery, true); assertEquals(new BasicDBObject("$in", Arrays.asList("parentId1", "parentId2")), parentQuery.get("_id")); }
@Test public void testdoUpdate() { Query originalQuery = new Query(Criteria.where("_id").is("parent_idchild").and("someProperty").is("someValue")); Update update = new Update(); update.set("someProperty", "someNewValue"); boolean result = underTest.subDoc("studentSectionAssociation").doUpdate(originalQuery, update); assertTrue(result); originalQuery = new Query(Criteria.where("_id").is("parent_idchild").and("nonExistProperty").is("someValue")); update = new Update(); update.set("nonExistProperty", "someNewValue"); result = underTest.subDoc("studentSectionAssociation").doUpdate(originalQuery, update); assertFalse(result); }
@Test public void testFindById() { Entity resultEntity = underTest.subDoc("studentSectionAssociation").findById("parent_idchild"); assertNotNull(resultEntity); assertEquals("parent_idchild", resultEntity.getEntityId()); assertEquals("someValue", resultEntity.getBody().get("someProperty")); }
@Test public void testFindAll() { Query originalQuery = new Query(Criteria.where("_id").is("parent_idchild").and("someProperty").is("someValue")) .skip(0).limit(1); List<Entity> entityResults = underTest.subDoc("studentSectionAssociation").findAll(originalQuery); assertNotNull(entityResults); assertEquals(1, entityResults.size()); assertEquals("parent_idchild", entityResults.get(0).getEntityId()); assertEquals("someValue", entityResults.get(0).getBody().get("someProperty")); }
@Test public void testDelete() { Entity entity = underTest.subDoc("studentSectionAssociation").findById("parent_idchild"); boolean result = underTest.subDoc("studentSectionAssociation").delete(entity); assertTrue(result); entity = underTest.subDoc("studentSectionAssociation").findById("nonExistId"); result = underTest.subDoc("studentSectionAssociation").delete(entity); assertFalse(result); }
@Test public void testCount() { Query originalQuery = new Query(Criteria.where("_id").is("parent_idchild").and("someProperty").is("someValue")); long count = underTest.subDoc("studentSectionAssociation").count(originalQuery); assertEquals(1L, count); originalQuery = new Query(Criteria.where("_id").is("parent_idchild").and("nonExistProperty").is("someValue")); count = underTest.subDoc("studentSectionAssociation").count(originalQuery); assertEquals(0L, count); }
@Test public void testExists() { boolean exists = underTest.subDoc("studentSectionAssociation").exists("parent_idchild"); assertTrue(exists); boolean nonExists = underTest.subDoc("studentSectionAssociation").exists("nonExistId"); assertFalse(nonExists); }
|
EdfiRecordUnmarshaller extends EdfiRecordParser { public static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider, RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source) throws SAXException, IOException, XmlParseException { EdfiRecordUnmarshaller parser = new EdfiRecordUnmarshaller(typeProvider, messageReport, reportStats, source); parser.addVisitor(visitor); parser.process(input, schemaResource); } EdfiRecordUnmarshaller(TypeProvider typeProvider, AbstractMessageReport messageReport,
ReportStats reportStats, Source source); static void parse(InputStream input, Resource schemaResource, TypeProvider typeProvider,
RecordVisitor visitor, AbstractMessageReport messageReport, ReportStats reportStats, Source source); @Override void setDocumentLocator(Locator locator); @Override void startElement(String uri, String localName, String qName, Attributes attributes); @Override void endElement(String uri, String localName, String qName); @Override void characters(char[] ch, int start, int length); Location getCurrentLocation(); @Override void error(SAXParseException exception); @Override void fatalError(SAXParseException exception); void addVisitor(RecordVisitor recordVisitor); }
|
@Test public void testNewLineCharacter() throws Throwable { Resource schema = new ClassPathResource("edfiXsd-SLI/SLI-Interchange-StudentParent.xsd"); Resource xml = new ClassPathResource("parser/InterchangeStudentParent/StudentWithNewLine.xml"); Resource expectedJson = new ClassPathResource("parser/InterchangeStudentParent/Student.expected.json"); RecordVisitor mockVisitor = Mockito.mock(RecordVisitor.class); EdfiRecordUnmarshaller.parse(xml.getInputStream(), schema, tp, mockVisitor, new DummyMessageReport(), new SimpleReportStats(), new JobSource(xml.getFilename())); EntityTestHelper.captureAndCompare(mockVisitor, expectedJson); }
@Test public void testUnicodeCharacter() throws Throwable { Resource schema = new ClassPathResource("edfiXsd-SLI/SLI-Interchange-StudentParent.xsd"); Resource xml = new ClassPathResource("parser/InterchangeStudentParent/StudentWithUnicode.xml"); Resource expectedJson = new ClassPathResource("parser/InterchangeStudentParent/StudentWithUnicode.expected.json"); RecordVisitor mockVisitor = Mockito.mock(RecordVisitor.class); EdfiRecordUnmarshaller.parse(xml.getInputStream(), schema, tp, mockVisitor, new DummyMessageReport(), new SimpleReportStats(), new JobSource(xml.getFilename())); EntityTestHelper.captureAndCompare(mockVisitor, expectedJson); }
@Test public void testCDATA() throws Throwable { Resource schema = new ClassPathResource("edfiXsd-SLI/SLI-Interchange-StudentParent.xsd"); Resource xml = new ClassPathResource("parser/InterchangeStudentParent/StudentWithCDATA.xml"); Resource expectedJson = new ClassPathResource("parser/InterchangeStudentParent/StudentWithCDATA.expected.json"); RecordVisitor mockVisitor = Mockito.mock(RecordVisitor.class); EdfiRecordUnmarshaller.parse(xml.getInputStream(), schema, tp, mockVisitor, new DummyMessageReport(), new SimpleReportStats(), new JobSource(xml.getFilename())); EntityTestHelper.captureAndCompare(mockVisitor, expectedJson); }
@Test @SuppressWarnings("unchecked") public void testParsing() throws Throwable { Resource schema = new ClassPathResource("edfiXsd-SLI/SLI-Interchange-StudentParent.xsd"); Resource xml = new ClassPathResource("parser/InterchangeStudentParent/Student.xml"); RecordVisitor mockVisitor = Mockito.mock(RecordVisitor.class); EdfiRecordUnmarshaller.parse(xml.getInputStream(), schema, tp, mockVisitor, new DummyMessageReport(), new SimpleReportStats(), new JobSource(xml.getFilename())); verify(mockVisitor, atLeastOnce()).visit(any(RecordMeta.class), anyMap()); }
@Test(expected = IOException.class) public void testIOExceptionForSchema() throws Throwable { Resource schema = new ClassPathResource("does_not_exists.xsd"); Resource xml = new ClassPathResource("parser/InterchangeStudentParent/Student.xml"); RecordVisitor mockVisitor = Mockito.mock(RecordVisitor.class); EdfiRecordUnmarshaller.parse(xml.getInputStream(), schema, tp, mockVisitor, new DummyMessageReport(), new SimpleReportStats(), new JobSource(xml.getFilename())); }
@Test @SuppressWarnings("unchecked") public void testSourceLocation() throws Throwable { Resource schema = new ClassPathResource("edfiXsd-SLI/SLI-Interchange-StudentParent.xsd"); Resource xml = new ClassPathResource("parser/InterchangeStudentParent/ThirteenStudents.xml"); RecordVisitor mockVisitor = Mockito.mock(RecordVisitor.class); EdfiRecordUnmarshaller.parse(xml.getInputStream(), schema, tp, mockVisitor, new DummyMessageReport(), new SimpleReportStats(), new JobSource(xml.getFilename())); ArgumentCaptor<RecordMeta> recordMetaCaptor = ArgumentCaptor.forClass(RecordMeta.class); verify(mockVisitor, times(13)).visit(recordMetaCaptor.capture(), any(Map.class)); int recordCount = 0; for (RecordMeta recordMeta : recordMetaCaptor.getAllValues()) { recordCount++; if (recordCount == 11) { assertEquals(1574, recordMeta.getSourceStartLocation().getLineNumber()); assertEquals(1730, recordMeta.getSourceEndLocation().getLineNumber()); } else if (recordCount == 13) { assertEquals(1888, recordMeta.getSourceStartLocation().getLineNumber()); assertEquals(2044, recordMeta.getSourceEndLocation().getLineNumber()); } } }
|
Denormalizer { public Denormalization denormalization(String docType) { return denormalizations.get(docType); } Denormalizer(MongoTemplate template); DenormalizationBuilder denormalize(String type); boolean isDenormalizedDoc(String docType); Denormalization denormalization(String docType); boolean isCached(String docType); void addToCache(List<Entity> entityList, String collectionName); }
|
@Test public void testCreate() { MongoEntity entity = new MongoEntity("studentSectionAssociation", studentSectionAssociation); entity.getMetaData().put("tenantId", "TEST"); assertTrue(denormalizer.denormalization("studentSectionAssociation").create(entity)); verify(studentCollection).update(eq(BasicDBObjectBuilder.start("_id", STUDENT1).get()), argThat(new ArgumentMatcher<DBObject>() { @Override @SuppressWarnings("unchecked") public boolean matches(Object argument) { DBObject updateObject = (DBObject) argument; Map<String, Object> push = (Map<String, Object>) updateObject.get("$pushAll"); if (push == null) { return false; } Collection<Object> toPush = push.values(); if (toPush.size() != 1) { return false; } Object[] sectionRefsToPush = (Object[]) toPush.iterator().next(); List<String> ssaIds = new ArrayList<String>(push.keySet()); return ((((Map<String, Object>) sectionRefsToPush[0]).get("_id").equals(SECTION1)) && (((Map<String, Object>) sectionRefsToPush[0]).get("endDate").equals(ENDDATE1)) && (((Map<String, Object>) sectionRefsToPush[0]).get("beginDate").equals(BEGINDATE)) && ssaIds.get(0).equals("section")); } }), eq(true), eq(true), eq(WriteConcern.SAFE)); }
@Test public void testInsert() { Entity entity1 = new MongoEntity("studentSectionAssociation", new HashMap<String, Object>(studentSectionAssociation)); entity1.getBody().put("sectionId", SECTION2); entity1.getBody().put("endDate", ENDDATE2); entity1.getMetaData().put("tenantId", "TEST"); Entity entity2 = new MongoEntity("studentSectionAssociation", new HashMap<String, Object>(studentSectionAssociation)); entity2.getBody().put("studentId", STUDENT2); entity2.getMetaData().put("tenantId", "TEST"); assertTrue(denormalizer.denormalization("studentSectionAssociation").insert(Arrays.asList(entity1, entity2))); verify(studentCollection).update(eq(BasicDBObjectBuilder.start("_id", STUDENT2).get()), argThat(new ArgumentMatcher<DBObject>() { @Override @SuppressWarnings("unchecked") public boolean matches(Object argument) { DBObject updateObject = (DBObject) argument; Map<String, Object> push = (Map<String, Object>) updateObject.get("$pushAll"); if (push == null) { return false; } Collection<Object> toPush = push.values(); if (toPush.size() != 1) { return false; } Object[] sectionRefsToPush = (Object[]) toPush.iterator().next(); List<String> ssaIds = new ArrayList<String>(push.keySet()); return ((((Map<String, Object>) sectionRefsToPush[0]).get("_id").equals(SECTION1)) && (((Map<String, Object>) sectionRefsToPush[0]).get("endDate").equals(ENDDATE2)) && (((Map<String, Object>) sectionRefsToPush[0]).get("beginDate").equals(BEGINDATE)) && ssaIds.get(0).equals("section")); } }), eq(true), eq(true), eq(WriteConcern.SAFE)); verify(studentCollection).update(eq(BasicDBObjectBuilder.start("_id", STUDENT1).get()), argThat(new ArgumentMatcher<DBObject>() { @Override @SuppressWarnings("unchecked") public boolean matches(Object argument) { DBObject updateObject = (DBObject) argument; Map<String, Object> push = (Map<String, Object>) updateObject.get("$pushAll"); if (push == null) { return false; } Collection<Object> toPush = push.values(); if (toPush.size() != 1) { return false; } Object[] sectionRefsToPush = (Object[]) toPush.iterator().next(); List<String> ssaIds = new ArrayList<String>(push.keySet()); return ((((Map<String, Object>) sectionRefsToPush[0]).get("_id").equals(SECTION2)) && (((Map<String, Object>) sectionRefsToPush[0]).get("endDate").equals(ENDDATE2)) && (((Map<String, Object>) sectionRefsToPush[0]).get("beginDate").equals(BEGINDATE)) && ssaIds.get(0).equals("section")); } }), eq(true), eq(true), eq(WriteConcern.SAFE)); }
@Test public void testDelete() { MongoEntity entity = new MongoEntity("studentSectionAssociation", studentSectionAssociation); boolean result = denormalizer.denormalization("studentSectionAssociation").delete(entity, entity.getEntityId()); assertTrue(result); result = denormalizer.denormalization("studentSectionAssociation").delete(null, SSAID); assertTrue(result); result = denormalizer.denormalization("studentSectionAssociation").delete(null, "invalidID"); assertFalse(result); }
|
StudentAssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(STUDENT_ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } Entity assessment = retrieveAssessment(entity.getBody().get(ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_ASSESSMENT_ITEM, ASSESSMENT_ITEM_ID, ASSESSMENT_ITEM); subdocsToBody(entity, STUDENT_ASSESSMENT_ITEM, "studentAssessmentItems", Arrays.asList(STUDENT_ASSESSMENT_ID)); referenceEntityResolve(entity, assessment, STUDENT_OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT_ID, OBJECTIVE_ASSESSMENT); subdocsToBody(entity, STUDENT_OBJECTIVE_ASSESSMENT, "studentObjectiveAssessments", Arrays.asList(STUDENT_ASSESSMENT_ID)); entity.getEmbeddedData().clear(); } return entity; } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); }
|
@Test public void upconvertNoAssessmentShouldRemoveInvalidReference() { List<Entity> old = Arrays.asList(createUpConvertEntity()); assertNotNull(old.get(0).getEmbeddedData().get("studentAssessmentItem")); Iterable<Entity> entity = saConverter.subdocToBodyField(old); assertNull(entity.iterator().next().getEmbeddedData().get("studentAssessmentItem")); }
@SuppressWarnings("unchecked") @Test public void testUpConvertShouldCollapseAssessmentItem() { Entity saEntity = createUpConvertEntity(); saEntity.getBody().put("assessmentId", "assessmentId"); saEntity.getBody().put("studentId", "studentId"); List<Entity> old = Arrays.asList(saEntity); assertNull("studentAssessmentItem should not be in body", old.get(0).getBody() .get("studentAssessmentItem")); Entity assessment = createAssessment(); when(repo.getTemplate()).thenReturn(template); when(template.findById("assessmentId", Entity.class, EntityNames.ASSESSMENT)).thenReturn(assessment); Iterable<Entity> entities = saConverter.subdocToBodyField(old); assertNotNull("studentAssessmentItem should be moved into body", entities.iterator().next().getBody().get("studentAssessmentItems")); assertNotNull( "assessmentItem should be collapsed into the studentAssessmentItem", ((List<Map<String, Object>>) (entities.iterator().next().getBody().get("studentAssessmentItems"))).get(0).get( "assessmentItem")); Map<String, Object> assessmentItemBody = (Map<String, Object>) ((List<Map<String, Object>>) (entities.iterator().next() .getBody().get("studentAssessmentItems"))).get(0).get("assessmentItem"); assertEquals("collapsed assessmentItem should have assessmentId field is assessmentId", "assessmentId", assessmentItemBody.get("assessmentId")); assertEquals("collapsed assessmentItem should have identificationCode field is code1", "code1", assessmentItemBody.get("identificationCode")); assertEquals("collapsed assessmentItem should have itemCategory is Matching", "Matching", assessmentItemBody.get("itemCategory")); }
|
StudentAssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); }
|
@Test public void testBodyFieldToSubdoc() { List<Entity> entities = Arrays.asList(createDownConvertEntity()); assertNotNull("studentAssessment body should have studentAssessmentItem", entities.get(0).getBody().get("studentAssessmentItems")); assertNull("studentAssessmentItem should not be outside the studentAssessment body", entities.get(0) .getEmbeddedData().get("studentAssessmentItem")); saConverter.bodyFieldToSubdoc(entities); assertNull("studentAssessment body should not have studentAssessmentItem", entities.get(0).getBody().get("studentAssessmentItems")); assertNotNull("studentAssessmentItem should be moved outside body", entities.get(0).getEmbeddedData().get("studentAssessmentItem")); }
@SuppressWarnings("unchecked") @Test public void testSubdocDid() { List<Entity> entities = Arrays.asList(createDownConvertEntity()); assertNull( "studentAssessmentItem should not have id before transformation", ((List<Map<String, Object>>) (entities.get(0).getBody().get("studentAssessmentItems"))).get(0).get( "_id")); saConverter.bodyFieldToSubdoc(entities); assertFalse("subdoc id should be generated", entities.get(0).getEmbeddedData().get("studentAssessmentItem") .get(0).getEntityId().isEmpty()); }
|
ContainerDocumentAccessor { public boolean isContainerDocument(final String entity) { return containerDocumentHolder.isContainerDocument(entity); } ContainerDocumentAccessor(final UUIDGeneratorStrategy strategy, final INaturalKeyExtractor extractor,
final MongoTemplate mongoTemplate, final SchemaRepository schemaRepo); boolean isContainerDocument(final String entity); boolean isContainerSubdoc(final String entity); boolean insert(final List<Entity> entityList); String insert(final Entity entity); boolean update(final String type, final String id, Map<String, Object> newValues, String collectionName); String update(final Entity entity); Entity findById(String collectionName, String id); List<Entity> findAll(String collectionName, Query query); boolean delete(final Entity entity); @SuppressWarnings("unchecked") boolean deleteContainerNonSubDocs(final Entity containerDoc); long count(String collectionName, Query query); boolean exists(String collectionName, String id); String getEmbeddedDocType(final String containerDocType); }
|
@Test public void testIsContainerDocument() { when(mockHolder.isContainerDocument(ATTENDANCE)).thenReturn(true); boolean actual = testAccessor.isContainerDocument(ATTENDANCE); assertEquals(true, actual); }
|
ContainerDocumentAccessor { public boolean isContainerSubdoc(final String entity) { boolean isContainerSubdoc = false; if (containerDocumentHolder.isContainerDocument(entity)) { isContainerSubdoc = containerDocumentHolder.getContainerDocument(entity).isContainerSubdoc(); } return isContainerSubdoc; } ContainerDocumentAccessor(final UUIDGeneratorStrategy strategy, final INaturalKeyExtractor extractor,
final MongoTemplate mongoTemplate, final SchemaRepository schemaRepo); boolean isContainerDocument(final String entity); boolean isContainerSubdoc(final String entity); boolean insert(final List<Entity> entityList); String insert(final Entity entity); boolean update(final String type, final String id, Map<String, Object> newValues, String collectionName); String update(final Entity entity); Entity findById(String collectionName, String id); List<Entity> findAll(String collectionName, Query query); boolean delete(final Entity entity); @SuppressWarnings("unchecked") boolean deleteContainerNonSubDocs(final Entity containerDoc); long count(String collectionName, Query query); boolean exists(String collectionName, String id); String getEmbeddedDocType(final String containerDocType); }
|
@Test public void isContainerSubDoc() { final ContainerDocument cDoc2 = createContainerDocGrade(); when(mockHolder.isContainerDocument(ATTENDANCE)).thenReturn(true); when(mockHolder.isContainerDocument(GRADE)).thenReturn(true); when(mockHolder.getContainerDocument(GRADE)).thenReturn(cDoc2); assertFalse(testAccessor.isContainerSubdoc(ATTENDANCE)); assertTrue(testAccessor.isContainerSubdoc(GRADE)); }
|
ContainerDocumentAccessor { public boolean insert(final List<Entity> entityList) { boolean result = true; for (Entity entity : entityList) { result &= !insert(entity).isEmpty(); } return result; } ContainerDocumentAccessor(final UUIDGeneratorStrategy strategy, final INaturalKeyExtractor extractor,
final MongoTemplate mongoTemplate, final SchemaRepository schemaRepo); boolean isContainerDocument(final String entity); boolean isContainerSubdoc(final String entity); boolean insert(final List<Entity> entityList); String insert(final Entity entity); boolean update(final String type, final String id, Map<String, Object> newValues, String collectionName); String update(final Entity entity); Entity findById(String collectionName, String id); List<Entity> findAll(String collectionName, Query query); boolean delete(final Entity entity); @SuppressWarnings("unchecked") boolean deleteContainerNonSubDocs(final Entity containerDoc); long count(String collectionName, Query query); boolean exists(String collectionName, String id); String getEmbeddedDocType(final String containerDocType); }
|
@Test public void testInsert() { DBObject query = Mockito.mock(DBObject.class); DBObject docToPersist = ContainerDocumentHelper.buildDocumentToPersist(mockHolder, entity, generatorStrategy, naturalKeyExtractor); when(query.get("_id")).thenReturn(ID); when(mockHolder.getContainerDocument(ATTENDANCE)).thenReturn(createContainerDocAttendance()); when(mongoTemplate.getCollection(ATTENDANCE)).thenReturn(mockCollection); when(mockCollection.update(Mockito.any(DBObject.class), Mockito.eq(docToPersist), Mockito.eq(true), Mockito.eq(false), Mockito.eq(WriteConcern.SAFE))).thenReturn(writeResult); String result = testAccessor.insertContainerDoc(query, entity); assertTrue(result.equals(ID)); assertFalse("Wrong result returned by insert", result.equals("")); Mockito.verify(mockCollection, Mockito.times(1)).update(Mockito.any(DBObject.class), Mockito.eq(docToPersist), Mockito.eq(true), Mockito.eq(false), Mockito.eq(WriteConcern.SAFE)); }
|
ContainerDocumentAccessor { @SuppressWarnings("unchecked") public boolean deleteContainerNonSubDocs(final Entity containerDoc) { String collection = containerDoc.getType(); String embeddedDocType = getEmbeddedDocType(collection); List<Map<String, Object>> embeddedDocs = (List<Map<String, Object>>) containerDoc.getBody().get(embeddedDocType); String containerDocId = containerDoc.getEntityId(); final BasicDBObject query = new BasicDBObject(); query.put("_id", containerDocId); DBObject result = null; for (Map<String, Object> docToDelete : embeddedDocs) { Map<String, Object> filteredDocToDelete = filterByNaturalKeys(embeddedDocType, docToDelete); BasicDBObject dBDocToDelete = new BasicDBObject("body." + embeddedDocType, filteredDocToDelete); final BasicDBObject update = new BasicDBObject("$pull", dBDocToDelete); result = this.mongoTemplate.getCollection(collection).findAndModify(query, null, null, false, update, true, false); if (result == null) { LOG.error("Could not delete " + embeddedDocType + " instance from " + collection + " record with id " + containerDocId); return false; } } List<Map<String, Object>> remainingAttendanceEvents = (List<Map<String, Object>>) ((Map<String, Object>) result .get("body")).get(embeddedDocType); if (remainingAttendanceEvents == null || remainingAttendanceEvents.isEmpty()) { Query frQuery = new Query(Criteria.where("_id").is(containerDocId)); Entity deleted = this.mongoTemplate.findAndRemove(frQuery, Entity.class, collection); if (deleted == null) { LOG.error("Could not delete empty " + collection + " record with id " + containerDocId); return false; } } return true; } ContainerDocumentAccessor(final UUIDGeneratorStrategy strategy, final INaturalKeyExtractor extractor,
final MongoTemplate mongoTemplate, final SchemaRepository schemaRepo); boolean isContainerDocument(final String entity); boolean isContainerSubdoc(final String entity); boolean insert(final List<Entity> entityList); String insert(final Entity entity); boolean update(final String type, final String id, Map<String, Object> newValues, String collectionName); String update(final Entity entity); Entity findById(String collectionName, String id); List<Entity> findAll(String collectionName, Query query); boolean delete(final Entity entity); @SuppressWarnings("unchecked") boolean deleteContainerNonSubDocs(final Entity containerDoc); long count(String collectionName, Query query); boolean exists(String collectionName, String id); String getEmbeddedDocType(final String containerDocType); }
|
@Test public void testDeleteEntity() { ContainerDocumentAccessor cda = Mockito.spy(testAccessor); Map<String, Object> updateDocCriteria = new HashMap<String, Object>(); updateDocCriteria.put("event", "Tardy"); DBObject pullObject = BasicDBObjectBuilder.start().push("$pull").add("body.attendanceEvent", updateDocCriteria).get(); DBObject resultingAttendanceEvent = createResultAttendance("10-04-2013"); NeutralSchema attendanceSchema = createMockAttendanceSchema(); when(mongoTemplate.getCollection(ATTENDANCE)).thenReturn(mockCollection); when(mockCollection.findAndModify(Mockito.any(DBObject.class), (DBObject) Mockito.isNull(), (DBObject) Mockito.isNull(), Mockito.eq(false), Mockito.eq(pullObject),Mockito.eq(true), Mockito.eq(false))).thenReturn(resultingAttendanceEvent); when(schemaRepo.getSchema(EntityNames.ATTENDANCE)).thenReturn(attendanceSchema); boolean result = cda.deleteContainerNonSubDocs(entity); Mockito.verify(mockCollection, Mockito.times(1)).findAndModify(Mockito.any(DBObject.class), (DBObject) Mockito.isNull(), (DBObject) Mockito.isNull(), Mockito.eq(false), Mockito.eq(pullObject), Mockito.eq(true), Mockito.eq(false)); assertTrue(result); }
@Test public void testDeleteEntityAndContainerDoc() { ContainerDocumentAccessor cda = Mockito.spy(testAccessor); Map<String, Object> updateDocCriteria = new HashMap<String, Object>(); updateDocCriteria.put("event", "Tardy"); DBObject pullObject = BasicDBObjectBuilder.start().push("$pull").add("body.attendanceEvent", updateDocCriteria).get(); DBObject resultingAttendanceEvent = createResultAttendance(null); NeutralSchema attendanceSchema = createMockAttendanceSchema(); when(mongoTemplate.getCollection(ATTENDANCE)).thenReturn(mockCollection); when(mockCollection.findAndModify(Mockito.any(DBObject.class), (DBObject) Mockito.isNull(), (DBObject) Mockito.isNull(), Mockito.eq(false), Mockito.eq(pullObject), Mockito.eq(true), Mockito.eq(false))).thenReturn(resultingAttendanceEvent); when(mongoTemplate.findAndRemove(Mockito.any(Query.class), Mockito.eq(Entity.class), Mockito.eq(ATTENDANCE))).thenReturn(entity); when(schemaRepo.getSchema(EntityNames.ATTENDANCE)).thenReturn(attendanceSchema); boolean result = cda.deleteContainerNonSubDocs(entity); Mockito.verify(mockCollection, Mockito.times(1)).findAndModify(Mockito.any(DBObject.class), (DBObject) Mockito.isNull(), (DBObject) Mockito.isNull(), Mockito.eq(false), Mockito.eq(pullObject), Mockito.eq(true), Mockito.eq(false)); Mockito.verify(mongoTemplate, Mockito.times(1)).findAndRemove(Mockito.any(Query.class), Mockito.eq(Entity.class), Mockito.eq(ATTENDANCE)); assertTrue(result); }
|
AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public Entity subdocToBodyField(Entity entity) { if (entity != null && entity.getType().equals(ASSESSMENT)) { if (entity.getBody() == null || entity.getBody().isEmpty()) { return null; } transformToHierarchy(entity); subdocsToBody(entity, ASSESSMENT_ITEM, ASSESSMENT_ITEM, Arrays.asList(ASSESSMENT_ID)); subdocsToBody(entity, OBJECTIVE_ASSESSMENT, OBJECTIVE_ASSESSMENT, Arrays.asList(ASSESSMENT_ID)); entity.getEmbeddedData().clear(); collapseAssessmentPeriodDescriptor(entity); addFamilyHierarchy(entity); } return entity; } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); }
|
@Test public void upconvertShouldRemoveAPD_references() { Entity oldEntity = createUpConvertEntity(); Entity entity = assessmentConverter.subdocToBodyField(oldEntity); assertNull(entity.getBody().get("assessmentPeriodDescriptorId")); }
@Test public void upconvertNoEmbeddedSubdocShouldRemainUnchanged() { List<Entity> old = Arrays.asList(createDownConvertEntity()); Entity clone = createDownConvertEntity(); Iterable<Entity> entity = assessmentConverter.subdocToBodyField(old); assertEquals(clone.getBody(), entity.iterator().next().getBody()); }
@Test public void upconvertShouldConstructAssessmentFamilyHierarchy() { Entity oldEntity = createUpConvertEntity(); Entity entity = assessmentConverter.subdocToBodyField(oldEntity); assertNull(entity.getBody().get(ASSESSMENT_FAMILY_REFERENCE)); assertEquals("A.B.C", entity.getBody().get(ASSESSMENT_FAMILY_HIERARCHY)); }
@SuppressWarnings("unchecked") @Test public void upconvertEmbeddedSubdocShouldMoveInsideBody() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Entity oldEntity = createUpConvertEntity(); Entity clone = createUpConvertEntity(); assertNull(oldEntity.getBody().get("assessmentItem")); Entity entity = assessmentConverter.subdocToBodyField(oldEntity); assertNotNull(entity.getBody().get("assessmentItem")); assertEquals(clone.getEmbeddedData().get("assessmentItem").get(0).getBody().get("abc"), ((List<Map<String, Object>>) (entity.getBody().get("assessmentItem"))).get(0).get("abc")); assertEquals("somevalue1", PropertyUtils.getProperty(entity, "body.assessmentItem.[0].abc")); assertEquals("somevalue2", PropertyUtils.getProperty(entity, "body.assessmentItem.[1].abc")); assertNull(entity.getEmbeddedData().get("assessmentItem")); assertNull(entity.getBody().get("assessmentPeriodDescriptorId")); assertNotNull(entity.getBody().get("assessmentPeriodDescriptor")); assertEquals(((Map<String, Object>)(entity.getBody().get("assessmentPeriodDescriptor"))).get("codeValue"), assessmentPeriodDescriptor.getBody().get("codeValue")); }
@Test public void invalidApdIdShouldBeFilteredOutInUp() { when(template.findById("mydescriptorid", Entity.class, EntityNames.ASSESSMENT_PERIOD_DESCRIPTOR)).thenReturn(null); Entity old = createUpConvertEntity(); Entity entity = assessmentConverter.subdocToBodyField(Arrays.asList(old)).iterator().next(); assertNull(entity.getBody().get("assessmentPeriodDescriptor")); assertNull(entity.getBody().get("assessmentPeriodDescriptorId")); }
@Test @SuppressWarnings("unchecked") public void testHierachyInObjectiveAssessmentsToAPI() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Entity oldAssessment = createHierarchicalUpConvertEntity(); Entity assessment = assessmentConverter.subdocToBodyField(oldAssessment); List<Map<String, Object>> oas = (List<Map<String, Object>>) PropertyUtils.getProperty(assessment, "body.objectiveAssessment"); assertEquals(1, oas.size()); assertEquals("ParentOA", PropertyUtils.getProperty(assessment, "body.objectiveAssessment.[0].title")); assertEquals("Child1", PropertyUtils.getProperty(assessment, "body.objectiveAssessment.[0].objectiveAssessments.[0].title")); assertEquals("Child2", PropertyUtils.getProperty(assessment, "body.objectiveAssessment.[0].objectiveAssessments.[1].title")); assertEquals("GrandChild", PropertyUtils.getProperty(assessment, "body.objectiveAssessment.[0].objectiveAssessments.[0].objectiveAssessments.[0].title")); }
@Test public void testAssessmentsWithAIsInOAsToAPI() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Entity oldAssessment = createHierarchicalUpConvertEntity(); Entity assessment = assessmentConverter.subdocToBodyField(oldAssessment); assertEquals("somevalue1", PropertyUtils.getProperty(assessment, "body.objectiveAssessment.[0].objectiveAssessments.[0].assessmentItem.[0].abc")); assertEquals("somevalue2", PropertyUtils.getProperty(assessment, "body.objectiveAssessment.[0].objectiveAssessments.[1].assessmentItem.[0].abc")); assertEquals("somevalue3", PropertyUtils.getProperty(assessment, "body.objectiveAssessment.[0].objectiveAssessments.[0].assessmentItem.[1].abc")); assertEquals("somevalue4", PropertyUtils.getProperty(assessment, "body.assessmentItem.[0].abc")); assertNull(PropertyUtils.getProperty(assessment, "body.objectiveAssessment.[0].objectiveAssessments.[0].assessmentItem.[0]._id")); assertNull(PropertyUtils.getProperty(assessment, "body.objectiveAssessment.[0].objectiveAssessments.[0].assessmentItem.[0].assessmentId")); }
|
AssessmentConverter extends GenericSuperdocConverter implements SuperdocConverter { @Override public void bodyFieldToSubdoc(Entity entity) { bodyFieldToSubdoc(entity, null); } @Override Entity subdocToBodyField(Entity entity); @Override void bodyFieldToSubdoc(Entity entity); @Override void bodyFieldToSubdoc(Entity entity, SuperdocConverter.Option option); List<Map<String, Object>> extractAssessmentItems(List<Entity> objectiveAssessments, String parentKey); @Override Iterable<Entity> subdocToBodyField(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities); @Override void bodyFieldToSubdoc(Iterable<Entity> entities, SuperdocConverter.Option option); }
|
@Test public void downconvertShouldDeleteAssessmentFamilyHierarchy() { Entity entity = createDownConvertEntity(); assessmentConverter.bodyFieldToSubdoc(entity); assertNull(entity.getBody().get(ASSESSMENT_FAMILY_HIERARCHY)); }
@Test public void downconvertShouldDeleteAssessmentFamilyHierarchyExistingAssessment() { Entity existingAssessment = createDownConvertEntity(); existingAssessment.getBody().put(ASSESSMENT_FAMILY_REFERENCE, assessmentFamilyA.getEntityId()); when(template.findById(existingAssessment.getEntityId(), Entity.class, EntityNames.ASSESSMENT)).thenReturn(existingAssessment); Entity updatedAssessment = createDownConvertEntity(); updatedAssessment.getBody().put("assessmentTitle", "A_new_title"); assessmentConverter.bodyFieldToSubdoc(updatedAssessment); assertNull(updatedAssessment.getBody().get(ASSESSMENT_FAMILY_HIERARCHY)); assertEquals(existingAssessment.getBody().get(ASSESSMENT_FAMILY_REFERENCE), updatedAssessment.getBody().get(ASSESSMENT_FAMILY_REFERENCE)); assertEquals("A_new_title", updatedAssessment.getBody().get("assessmentTitle")); }
@Test public void downconvertBodyHasNoSubdocShouldNotChange() throws NoNaturalKeysDefinedException { List<Entity> entity = Arrays.asList(createUpConvertEntity()); Entity clone = createUpConvertEntity(); assessmentConverter.bodyFieldToSubdoc(entity); assertEquals(clone.getBody(), entity.get(0).getBody()); }
@Test public void downconvertBodyToSubdoc() { Entity entity = createDownConvertEntity(); assessmentConverter.bodyFieldToSubdoc(entity); assertNull(entity.getBody().get("assessmentItem")); assertNotNull(entity.getEmbeddedData().get("assessmentItem")); assertNull(entity.getBody().get("assessmentPeriodDescriptor")); assertNotNull(entity.getBody().get("assessmentPeriodDescriptorId")); }
@Test public void bodyToSubdocGenerateId() { Entity entity = createDownConvertEntity(); assessmentConverter.bodyFieldToSubdoc(entity); assertNotNull("should move assessmentItem from in body to out body", entity.getEmbeddedData().get("assessmentItem")); assertEquals("should have one assessmentItem in subdoc field", 1, entity.getEmbeddedData() .get("assessmentItem").size()); String id = entity.getEmbeddedData().get("assessmentItem").get(0).getEntityId(); assertNotNull("should generate id for subdoc entity", id); }
@Test public void testHierachyInObjectiveAssessmentsToDAL() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Entity assessment = createHierarchicalDownConvertEntity(); assessmentConverter.bodyFieldToSubdoc(assessment); assertEquals("ParentOA", PropertyUtils.getProperty(assessment, "embeddedData.objectiveAssessment.[3].body.title")); assertEquals("Child1", PropertyUtils.getProperty(assessment, "embeddedData.objectiveAssessment.[3].body.subObjectiveAssessment.[0]")); assertEquals("Child2", PropertyUtils.getProperty(assessment, "embeddedData.objectiveAssessment.[3].body.subObjectiveAssessment.[1]")); assertEquals("Child1", PropertyUtils.getProperty(assessment, "embeddedData.objectiveAssessment.[1].body.title")); assertEquals("GrandChild", PropertyUtils.getProperty(assessment, "embeddedData.objectiveAssessment.[1].body.subObjectiveAssessment.[0]")); assertEquals("Child2", PropertyUtils.getProperty(assessment, "embeddedData.objectiveAssessment.[2].body.title")); assertEquals("GrandChild", PropertyUtils.getProperty(assessment, "embeddedData.objectiveAssessment.[0].body.title")); }
@Test public void testAssessmentsWithAIsInOAsToDAL() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Entity assessment = createHierarchicalDownConvertEntity(); assessmentConverter.bodyFieldToSubdoc(assessment); assertEquals("1", PropertyUtils.getProperty(assessment, "embeddedData.assessmentItem.[0].body.a")); assertEquals("somevalue1", PropertyUtils.getProperty(assessment, "embeddedData.assessmentItem.[1].body.abc")); assertEquals("somevalue2", PropertyUtils.getProperty(assessment, "embeddedData.assessmentItem.[2].body.abc")); assertEquals("somevalue3", PropertyUtils.getProperty(assessment, "embeddedData.assessmentItem.[3].body.abc")); assertNotNull(PropertyUtils.getProperty(assessment, "embeddedData.assessmentItem.[0].entityId")); assertNotNull(PropertyUtils.getProperty(assessment, "embeddedData.assessmentItem.[1].entityId")); assertNotNull(PropertyUtils.getProperty(assessment, "embeddedData.assessmentItem.[2].entityId")); assertNotNull(PropertyUtils.getProperty(assessment, "embeddedData.assessmentItem.[3].entityId")); }
|
FileEntryWorkNote extends WorkNote implements Serializable { public IngestionFileEntry getFileEntry() { return fileEntry; } FileEntryWorkNote(String batchJobId, IngestionFileEntry fileEntry, boolean hasErrors); IngestionFileEntry getFileEntry(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }
|
@Test public void testCreateSimpleWorkNote() { FileEntryWorkNote workNote = new FileEntryWorkNote("batchJobId", null, false); Assert.assertEquals("batchJobId", workNote.getBatchJobId()); Assert.assertEquals(null, workNote.getFileEntry()); }
|
EntityWriteConverter implements Converter<Entity, DBObject> { @Override public DBObject convert(Entity e) { MongoEntity me; if (e instanceof MongoEntity) { me = (MongoEntity) e; } else { me = new MongoEntity(e.getType(), e.getEntityId(), e.getBody(), e.getMetaData(), e.getCalculatedValues(), e.getAggregates()); } if (encrypt != null) { me.encrypt(encrypt); } return me.toDBObject(uuidGeneratorStrategy, naturalKeyExtractor); } @Override DBObject convert(Entity e); }
|
@Test public void testEntityConvert() throws NoNaturalKeysDefinedException { Entity e = Mockito.mock(Entity.class); HashMap<String, Object> body = new HashMap<String, Object>(); body.put("field1", "field1"); body.put("field2", "field2"); HashMap<String, Object> meta = new HashMap<String, Object>(); meta.put("meta1", "field1"); meta.put("meta2", "field2"); NaturalKeyDescriptor desc = new NaturalKeyDescriptor(); Mockito.when(e.getType()).thenReturn("collection"); Mockito.when(e.getBody()).thenReturn(body); Mockito.when(e.getMetaData()).thenReturn(meta); Mockito.when(naturalKeyExtractor.getNaturalKeyDescriptor(Mockito.any(Entity.class))).thenReturn(desc); Mockito.when(uuidGeneratorStrategy.generateId(desc)).thenReturn("uid"); DBObject d = converter.convert(e); Assert.assertNotNull("DBObject should not be null", d); assertSame(body, (Map<?, ?>) d.get("body")); assertSame(meta, (Map<?, ?>) d.get("metaData")); Assert.assertEquals(1, encryptCalls.size()); Assert.assertEquals(2, encryptCalls.get(0).length); Assert.assertEquals(e.getType(), encryptCalls.get(0)[0]); Assert.assertEquals(e.getBody(), encryptCalls.get(0)[1]); }
@Test public void testMockMongoEntityConvert() { MongoEntity e = Mockito.mock(MongoEntity.class); DBObject result = Mockito.mock(DBObject.class); Mockito.when(e.toDBObject(uuidGeneratorStrategy, naturalKeyExtractor)).thenReturn(result); DBObject d = converter.convert(e); Assert.assertNotNull(d); Assert.assertEquals(result, d); Mockito.verify(e, Mockito.times(1)).encrypt(encryptor); Mockito.verify(e, Mockito.times(1)).toDBObject(uuidGeneratorStrategy, naturalKeyExtractor); }
@Test public void testMongoEntityConvert() { HashMap<String, Object> body = new HashMap<String, Object>(); body.put("field1", "field1"); body.put("field2", "field2"); HashMap<String, Object> meta = new HashMap<String, Object>(); meta.put("meta1", "field1"); meta.put("meta2", "field2"); MongoEntity e = new MongoEntity("collection", UUID.randomUUID().toString(), body, meta); DBObject d = converter.convert(e); Assert.assertNotNull(d); assertSame(body, (Map<?, ?>) d.get("body")); assertSame(meta, (Map<?, ?>) d.get("metaData")); Assert.assertEquals(1, encryptCalls.size()); Assert.assertEquals(2, encryptCalls.get(0).length); Assert.assertEquals(e.getType(), encryptCalls.get(0)[0]); Assert.assertEquals(e.getBody(), encryptCalls.get(0)[1]); }
|
MongoEntityTemplate extends MongoTemplate { public <T> Iterator<T> findEach(final Query query, final Class<T> entityClass, String collectionName) { MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityClass); DBCollection collection = getDb().getCollection(collectionName); prepareCollection(collection); DBObject dbQuery = mapper.getMappedObject(query.getQueryObject(), entity); final DBCursor cursor; if (query.getFieldsObject() == null) { cursor = collection.find(dbQuery); } else { cursor = collection.find(dbQuery, query.getFieldsObject()); } return new Iterator<T>() { @Override public boolean hasNext() { return cursor.hasNext(); } @Override public T next() { return getConverter().read(entityClass, cursor.next()); } @Override public void remove() { cursor.remove(); } }; } MongoEntityTemplate(MongoDbFactory mongoDbFactory, MongoConverter mongoConverter); Iterator<T> findEach(final Query query, final Class<T> entityClass, String collectionName); }
|
@Test public void testReadPreference() { template.setReadPreference(ReadPreference.secondary()); Query query = new Query(); template.findEach(query, Entity.class, "student"); Assert.assertEquals(ReadPreference.secondary(), template.getCollection("student").getReadPreference()); }
|
AesCipher implements org.slc.sli.dal.encrypt.Cipher { @Override public String encrypt(Object data) { if (data instanceof String) { return "ESTRING:" + encryptFromBytes(StringUtils.getBytesUtf8((String) data)); } else { ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOutputStream); String type; try { if (data instanceof Boolean) { dos.writeBoolean((Boolean) data); type = "EBOOL:"; } else if (data instanceof Integer) { dos.writeInt((Integer) data); type = "EINT:"; } else if (data instanceof Long) { dos.writeLong((Long) data); type = "ELONG:"; } else if (data instanceof Double) { dos.writeDouble((Double) data); type = "EDOUBLE:"; } else { throw new RuntimeException("Unsupported type: " + data.getClass().getCanonicalName()); } dos.flush(); dos.close(); } catch (IOException e) { throw new RuntimeException(e); } byte[] bytes = byteOutputStream.toByteArray(); return type + encryptFromBytes(bytes); } } @Override String encrypt(Object data); @Override Object decrypt(String data); }
|
@Test(expected = RuntimeException.class) public void testUnhandled() { aes.encrypt(1.1F); }
|
AesCipher implements org.slc.sli.dal.encrypt.Cipher { @Override public Object decrypt(String data) { String[] splitData = org.apache.commons.lang3.StringUtils.split(data, ':'); if (splitData.length != 2) { return null; } else { if (splitData[0].equals("ESTRING")) { return StringUtils.newStringUtf8(decryptToBytes(splitData[1])); } else if (splitData[0].equals("EBOOL")) { return decryptBinary(splitData[1], Boolean.class); } else if (splitData[0].equals("EINT")) { return decryptBinary(splitData[1], Integer.class); } else if (splitData[0].equals("ELONG")) { return decryptBinary(splitData[1], Long.class); } else if (splitData[0].equals("EDOUBLE")) { return decryptBinary(splitData[1], Double.class); } else { return null; } } } @Override String encrypt(Object data); @Override Object decrypt(String data); }
|
@Test() public void testUnencryptedString() { Object decrypted = aes.decrypt("Some text"); assertEquals(null, decrypted); Object d2 = aes.decrypt("SOME DATA WITH : IN IT"); assertEquals(null, d2); }
|
TenantMongoDA implements TenantDA { @Override public String getTenantId(String lzPath) { return findTenantIdByLzPath(lzPath); } @Override List<String> getLzPaths(); @Override String getTenantId(String lzPath); @Override void insertTenant(TenantRecord tenant); @Override @SuppressWarnings("unchecked") String getTenantEdOrg(String lzPath); Repository<Entity> getEntityRepository(); void setEntityRepository(Repository<Entity> entityRepository); @SuppressWarnings("unchecked") @Override Map<String, List<String>> getPreloadFiles(String ingestionServer); @Override boolean tenantDbIsReady(String tenantId); @Override void setTenantReadyFlag(String tenantId); @Override void unsetTenantReadyFlag(String tenantId); @Override boolean updateAndAquireOnboardingLock(String tenantId); @Override void removeInvalidTenant(String lzPath); @Override Map<String, List<String>> getPreloadFiles(); @Override List<String> getAllTenantDbs(); static final String TENANT_ID; static final String DB_NAME; static final String INGESTION_SERVER; static final String PATH; static final String LANDING_ZONE; static final String PRELOAD_DATA; static final String PRELOAD_STATUS; static final String PRELOAD_FILES; static final String TENANT_COLLECTION; static final String TENANT_TYPE; static final String EDUCATION_ORGANIZATION; static final String DESC; static final String ALL_STATUS_FIELDS; static final String STATUS_FIELD; }
|
@Test public void shouldGetTenantIdFromLzPath() { Entity tenantRecord = createTenantEntity(); when(mockRepository.findOne(Mockito.eq("tenant"), Mockito.any(NeutralQuery.class))).thenReturn(tenantRecord); String tenantIdResult = tenantDA.getTenantId(lzPath1); assertNotNull("tenantIdResult was null", tenantIdResult); assertEquals("tenantIdResult did not match expected value", tenantId, tenantIdResult); Mockito.verify(mockRepository, Mockito.times(1)).findOne(Mockito.eq("tenant"), Mockito.any(NeutralQuery.class)); }
|
ConfigManagerImpl extends ApiClientManager implements ConfigManager { @Override public Map<String, Collection<Config>> getAllConfigByType(String token, EdOrgKey edOrgKey, Map<String, String> params) { Map<String, Collection<Config>> allConfigs = new HashMap<String, Collection<Config>>(); Set<String> configIdLookup = new HashSet<String>(); Map<String, String> attribute = new HashMap<String, String>(); String layoutName = params.get(LAYOUT_NAME); if (params.containsKey(TYPE)) { attribute.put(TYPE, params.get(TYPE)); } Collection<Config> driverConfigs = getConfigsByAttribute(token, edOrgKey, attribute, false); Iterator<Config> configIterator = driverConfigs.iterator(); while (configIterator.hasNext()) { Config driverConfig = configIterator.next(); if (doesBelongToLayout(driverConfig, layoutName)) { configIdLookup.add(driverConfig.getId()); } else { configIterator.remove(); } } allConfigs.put(DEFAULT, driverConfigs); APIClient apiClient = getApiClient(); EdOrgKey loopEdOrgKey = edOrgKey; while (loopEdOrgKey != null) { Collection<Config> customConfigByType = new LinkedList<Config>(); ConfigMap customConfigMap = getCustomConfig(token, loopEdOrgKey); if (customConfigMap != null) { Map<String, Config> configByMap = customConfigMap.getConfig(); if (configByMap != null) { Collection<Config> customConfigs = configByMap.values(); if (customConfigs != null) { for (Config customConfig : customConfigs) { String parentId = customConfig.getParentId(); if (parentId != null && configIdLookup.contains(parentId)) { if (doesBelongToLayout(customConfig, layoutName)) { customConfigByType.add(customConfig); } } } } } } GenericEntity edOrg = apiClient.getEducationalOrganization(token, loopEdOrgKey.getSliId()); List<String> organizationCategories = (List<String>) edOrg.get(Constants.ATTR_ORG_CATEGORIES); if (organizationCategories != null && !organizationCategories.isEmpty()) { for (String educationAgency : organizationCategories) { if (educationAgency != null) { allConfigs.put(educationAgency, customConfigByType); break; } } } loopEdOrgKey = null; edOrg = apiClient.getParentEducationalOrganization(token, edOrg); if (edOrg != null) { String id = edOrg.getId(); if (id != null && !id.isEmpty()) { loopEdOrgKey = new EdOrgKey(id); } } } return allConfigs; } ConfigManagerImpl(); void setDriverConfigLocation(String configLocation); void setUserConfigLocation(String configLocation); String getComponentConfigLocation(String path, String componentId); String getDriverConfigLocation(String componentId); @Override @CacheableConfig Config getComponentConfig(String token, EdOrgKey edOrgKey, String componentId); @Override @Cacheable(value = Constants.CACHE_USER_WIDGET_CONFIG) Collection<Config> getWidgetConfigs(String token, EdOrgKey edOrgKey); @Override Collection<Config> getConfigsByAttribute(String token, EdOrgKey edOrgKey, Map<String, String> attrs); @Override Collection<Config> getConfigsByAttribute(String token, EdOrgKey edOrgKey, Map<String, String> attrs,
boolean overwriteCustomConfig); @Override ConfigMap getCustomConfig(String token, EdOrgKey edOrgKey); @Override @CacheEvict(value = Constants.CACHE_USER_PANEL_CONFIG, allEntries = true) void putCustomConfig(String token, EdOrgKey edOrgKey, ConfigMap configMap); @Override @CacheEvict(value = Constants.CACHE_USER_PANEL_CONFIG, allEntries = true) void putCustomConfig(String token, EdOrgKey edOrgKey, Config config); @Override Map<String, Collection<Config>> getAllConfigByType(String token, EdOrgKey edOrgKey,
Map<String, String> params); }
|
@Test public void testGetAllConfigByType() { configManager = new ConfigManagerImpl(); configManager.setApiClient(apiClient); configManager.setDriverConfigLocation("config"); configManager.setUserConfigLocation("custom"); Map<String, String> params = new HashMap<String, String>(); params.put("type", "PANEL"); String edOrgId = "2012de-df94acd2-e7cd-11e1-a937-68a86d3c2f82"; Map<String, Collection<Config>> mapConfigs = configManager.getAllConfigByType("token", new EdOrgKey(edOrgId), params); Assert.assertEquals(3, mapConfigs.size()); Collection<Config> defaultConfig = mapConfigs.get("default"); Assert.assertNotNull(defaultConfig); Assert.assertEquals(10, defaultConfig.size()); Collection<Config> sea = mapConfigs.get("State Education Agency"); Assert.assertNotNull(sea); Assert.assertEquals(1, sea.size()); Collection<Config> lea = mapConfigs.get("Local Education Agency"); Assert.assertNotNull(lea); Assert.assertEquals(1, lea.size()); }
|
UserEdOrgManagerImpl extends ApiClientManager implements UserEdOrgManager { @Override @CacheableUserData public EdOrgKey getUserEdOrg(String token) { GenericEntity edOrg = null; if (!isEducator()) { String id = getApiClient().getId(token); GenericEntity staff = getApiClient().getStaffWithEducationOrganization(token, id, null); if (staff != null) { GenericEntity staffEdOrg = (GenericEntity) staff.get(Constants.ATTR_ED_ORG); if (staffEdOrg != null) { @SuppressWarnings("unchecked") List<String> edOrgCategories = (List<String>) staffEdOrg.get(Constants.ATTR_ORG_CATEGORIES); if (edOrgCategories != null && !edOrgCategories.isEmpty()) { for (String edOrgCategory : edOrgCategories) { if (edOrgCategory.equals(Constants.STATE_EDUCATION_AGENCY)) { edOrg = staffEdOrg; break; } else if (edOrgCategory.equals(Constants.LOCAL_EDUCATION_AGENCY)) { edOrg = staffEdOrg; break; } } } } } } if (edOrg == null) { List<GenericEntity> schools = getMySchools(token); if (schools != null && !schools.isEmpty()) { GenericEntity school = schools.get(0); edOrg = getParentEducationalOrganization(getToken(), school); if (edOrg == null) { throw new DashboardException( "No data is available for you to view. Please contact your IT administrator."); } } } if (edOrg != null) { return new EdOrgKey(edOrg.getId()); } return null; } @Override @CacheableUserData EdOrgKey getUserEdOrg(String token); @Override @CacheableUserData GenericEntity getUserInstHierarchy(String token, Object key, Data config); @Override GenericEntity getUserCoursesAndSections(String token, Object schoolIdObj, Data config); @Override @SuppressWarnings("unchecked") GenericEntity getUserSectionList(String token, Object schoolIdObj, Data config); @Override GenericEntity getStaffInfo(String token); @Override @SuppressWarnings("unchecked") GenericEntity getSchoolInfo(String token, Object schoolIdObj, Data config); }
|
@Test public void testGetUserEdOrg() { this.testInstitutionalHierarchyManagerImpl = new UserEdOrgManagerImpl() { @Override public String getToken() { return ""; } @Override protected boolean isEducator() { return false; } }; this.testInstitutionalHierarchyManagerImpl.setApiClient(apiClient); EdOrgKey edOrgKey1 = this.testInstitutionalHierarchyManagerImpl.getUserEdOrg(Constants.STATE_EDUCATION_AGENCY); Assert.assertEquals("2012ny-09327920-e000-11e1-9f3b-3c07546832b4", edOrgKey1.getSliId()); EdOrgKey edOrgKey2 = this.testInstitutionalHierarchyManagerImpl.getUserEdOrg(Constants.LOCAL_EDUCATION_AGENCY); Assert.assertEquals("2012zj-0b0711a4-e000-11e1-9f3b-3c07546832b4", edOrgKey2.getSliId()); this.testInstitutionalHierarchyManagerImpl = new UserEdOrgManagerImpl() { @Override public String getToken() { return ""; } @Override protected boolean isEducator() { return true; } }; this.testInstitutionalHierarchyManagerImpl.setApiClient(apiClient); EdOrgKey edOrgKey3 = this.testInstitutionalHierarchyManagerImpl.getUserEdOrg("Teacher"); Assert.assertEquals("2012zj-0b0711a4-e000-11e1-9f3b-3c07546832b4", edOrgKey3.getSliId()); }
|
JsonConverter { public static String toJson(Object o) { return GSON.toJson(o); } static String toJson(Object o); static T fromJson(String json, Class<T> clazz); static T fromJson(Reader reader, Class<T> clazz); }
|
@Test public void test() { GenericEntity entity = new GenericEntity(); GenericEntity element = new GenericEntity(); element.put("tire", "Yokohama"); entity.put("car", element); assertEquals("{\"car\":{\"tire\":\"Yokohama\"}}", JsonConverter.toJson(entity)); }
|
ParentsSorter { public static List<GenericEntity> sort(List<GenericEntity> genericEntities) { for (GenericEntity genericEntity : genericEntities) { List<Map<String, Object>> studentParentAssociations = (List<Map<String, Object>>) genericEntity .get(Constants.ATTR_STUDENT_PARENT_ASSOCIATIONS); if (studentParentAssociations != null && !studentParentAssociations.isEmpty()) { Map<String, Object> studentParentAssociation = studentParentAssociations.get(0); genericEntity.put(Constants.ATTR_RELATION, studentParentAssociation.get(Constants.ATTR_RELATION)); genericEntity.put(Constants.ATTR_CONTACT_PRIORITY, studentParentAssociation.get(Constants.ATTR_CONTACT_PRIORITY)); genericEntity.put(Constants.ATTR_PRIMARY_CONTACT_STATUS, studentParentAssociation.get(Constants.ATTR_PRIMARY_CONTACT_STATUS)); } } GenericEntityComparator comparator = new GenericEntityComparator(Constants.ATTR_RELATION, String.class); Collections.sort(genericEntities, comparator); comparator = new GenericEntityComparator(Constants.ATTR_RELATION, relationPriority); Collections.sort(genericEntities, comparator); comparator = new GenericEntityComparator(Constants.ATTR_CONTACT_PRIORITY, Double.class); Collections.sort(genericEntities, comparator); comparator = new GenericEntityComparator(Constants.ATTR_PRIMARY_CONTACT_STATUS, primaryContactStatusPriority); Collections.sort(genericEntities, comparator); for (GenericEntity genericEntity : genericEntities) { genericEntity.remove(Constants.ATTR_RELATION); genericEntity.remove(Constants.ATTR_CONTACT_PRIORITY); genericEntity.remove(Constants.ATTR_PRIMARY_CONTACT_STATUS); } return genericEntities; } private ParentsSorter(); static List<GenericEntity> sort(List<GenericEntity> genericEntities); }
|
@Test public void testSort() { List<GenericEntity> entities = new LinkedList<GenericEntity>(); List<LinkedHashMap<String, Object>> studentParentsAssocistion = new LinkedList<LinkedHashMap<String, Object>>(); LinkedHashMap<String, Object> obj = new LinkedHashMap<String, Object>(); obj.put(Constants.ATTR_RELATION, "Father"); studentParentsAssocistion.add(obj); GenericEntity entity = new GenericEntity(); entity.put(Constants.ATTR_STUDENT_PARENT_ASSOCIATIONS, studentParentsAssocistion); entities.add(entity); obj = new LinkedHashMap<String, Object>(); obj.put(Constants.ATTR_RELATION, "Mother"); studentParentsAssocistion = new LinkedList<LinkedHashMap<String, Object>>(); studentParentsAssocistion.add(obj); entity = new GenericEntity(); entity.put(Constants.ATTR_STUDENT_PARENT_ASSOCIATIONS, studentParentsAssocistion); entities.add(entity); ParentsSorter.sort(entities); List<LinkedHashMap<String, Object>> objTest = (List<LinkedHashMap<String, Object>>) entities.get(0).get( Constants.ATTR_STUDENT_PARENT_ASSOCIATIONS); Assert.assertEquals("Mother", objTest.get(0).get(Constants.ATTR_RELATION)); }
|
GenericEntityEnhancer { public static GenericEntity enhanceStudent(GenericEntity entity) { String gradeLevel = entity.getString("gradeLevel"); if (gradeLevel != null && gradeConversion.containsKey(gradeLevel)) { entity.put("gradeLevelCode", gradeConversion.get(gradeLevel)); } return entity; } static GenericEntity enhanceStudent(GenericEntity entity); @SuppressWarnings({ "rawtypes", "unchecked" }) static Map convertGradeLevel(Map entity, String elementName); static String convertGradeLevel(String gradeLevel); static GenericEntity enhanceStudentSchoolAssociation(GenericEntity entity); }
|
@Test public void testEnhanceStudent() { GenericEntity entity = new GenericEntity(); entity.put("gradeLevel", "Adult Education"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "AE"); entity = new GenericEntity(); entity.put("gradeLevel", "Early Education"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "EE"); entity = new GenericEntity(); entity.put("gradeLevel", "Eighth grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "8"); entity = new GenericEntity(); entity.put("gradeLevel", "Eleventh grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "11"); entity = new GenericEntity(); entity.put("gradeLevel", "Fifth grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "5"); entity = new GenericEntity(); entity.put("gradeLevel", "First grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "1"); entity = new GenericEntity(); entity.put("gradeLevel", "Fourth grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "4"); entity = new GenericEntity(); entity.put("gradeLevel", "Grade 13"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "13"); entity = new GenericEntity(); entity.put("gradeLevel", "Infant/toddler"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "IN"); entity = new GenericEntity(); entity.put("gradeLevel", "Kindergarten"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "K"); entity = new GenericEntity(); entity.put("gradeLevel", "Ninth grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "9"); entity = new GenericEntity(); entity.put("gradeLevel", "Other"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "O"); entity = new GenericEntity(); entity.put("gradeLevel", "Postsecondary"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "+S"); entity = new GenericEntity(); entity.put("gradeLevel", "Preschool/Prekindergarten"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "PK"); entity = new GenericEntity(); entity.put("gradeLevel", "Second grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "2"); entity = new GenericEntity(); entity.put("gradeLevel", "Seventh grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "7"); entity = new GenericEntity(); entity.put("gradeLevel", "Sixth grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "6"); entity = new GenericEntity(); entity.put("gradeLevel", "Tenth grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "10"); entity = new GenericEntity(); entity.put("gradeLevel", "Third grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "3"); entity = new GenericEntity(); entity.put("gradeLevel", "Transitional Kindergarten"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "TK"); entity = new GenericEntity(); entity.put("gradeLevel", "Twelfth grade"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "12"); entity = new GenericEntity(); entity.put("gradeLevel", "Ungraded"); entity = GenericEntityEnhancer.enhanceStudent(entity); Assert.assertEquals(entity.get("gradeLevelCode"), "UG"); entity = new GenericEntity(); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertNull(entity.get("gradeLevelCode")); }
|
GenericEntityEnhancer { public static GenericEntity enhanceStudentSchoolAssociation(GenericEntity entity) { String gradeLevel = entity.getString("entryGradeLevel"); if (gradeLevel != null && gradeConversion.containsKey(gradeLevel)) { entity.put("entryGradeLevelCode", gradeConversion.get(gradeLevel)); } return entity; } static GenericEntity enhanceStudent(GenericEntity entity); @SuppressWarnings({ "rawtypes", "unchecked" }) static Map convertGradeLevel(Map entity, String elementName); static String convertGradeLevel(String gradeLevel); static GenericEntity enhanceStudentSchoolAssociation(GenericEntity entity); }
|
@Test public void testEnhanceStudentSchoolAssociation() { GenericEntity entity = new GenericEntity(); entity.put("entryGradeLevel", "Adult Education"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "AE"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Early Education"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "EE"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Eighth grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "8"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Eleventh grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "11"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Fifth grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "5"); entity = new GenericEntity(); entity.put("entryGradeLevel", "First grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "1"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Fourth grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "4"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Grade 13"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "13"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Infant/toddler"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "IN"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Kindergarten"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "K"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Ninth grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "9"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Other"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "O"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Postsecondary"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "+S"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Preschool/Prekindergarten"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "PK"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Second grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "2"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Seventh grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "7"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Sixth grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "6"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Tenth grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "10"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Third grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "3"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Transitional Kindergarten"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "TK"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Twelfth grade"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "12"); entity = new GenericEntity(); entity.put("entryGradeLevel", "Ungraded"); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertEquals(entity.get("entryGradeLevelCode"), "UG"); entity = new GenericEntity(); entity = GenericEntityEnhancer.enhanceStudentSchoolAssociation(entity); Assert.assertNull(entity.get("entryGradeLevelCode")); }
|
SLIAuthenticationEntryPoint implements AuthenticationEntryPoint { static boolean isSecureRequest(HttpServletRequest request) { String serverName = request.getServerName(); boolean isSecureEnvironment = (!serverName.substring(0, serverName.indexOf(".")).equals( NONSECURE_ENVIRONMENT_NAME)); return (request.isSecure() && isSecureEnvironment); } void setCallbackUrl(String callbackUrl); String getCallbackUrl(); void setApiUrl(String apiUrl); String getApiUrl(); RESTClient getRestClient(); void setRestClient(RESTClient restClient); APIClient getApiClient(); void setApiClient(APIClient apiClient); PropertiesDecryptor getPropDecryptor(); void setPropDecryptor(PropertiesDecryptor propDecryptor); @Override void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException); static final String OAUTH_TOKEN; static final String DASHBOARD_COOKIE; }
|
@Test public void testIsSecuredRequest() throws Exception { LOG.debug("[SLCAuthenticationEntryPointTest]Secure Protocol with local environment, return FALSE"); when(request.getServerName()).thenReturn("local.slidev.org"); when(request.isSecure()).thenReturn(true); assertFalse(SLIAuthenticationEntryPoint.isSecureRequest(request)); LOG.debug("[SLCAuthenticationEntryPointTest]Non-Secure Protocol with local environment, return FALSE"); when(request.getServerName()).thenReturn("local.slidev.org"); when(request.isSecure()).thenReturn(false); assertFalse(SLIAuthenticationEntryPoint.isSecureRequest(request)); LOG.debug("[SLCAuthenticationEntryPointTest]Non-Secure Protocol with non-local environment, return FALSE"); when(request.getServerName()).thenReturn("rcdashboard.slidev.org"); when(request.isSecure()).thenReturn(false); assertFalse(SLIAuthenticationEntryPoint.isSecureRequest(request)); LOG.debug("[SLCAuthenticationEntryPointTest]Non-Secure Protocol with local environment, return FALSE"); when(request.getServerName()).thenReturn("local.slidev.org"); when(request.isSecure()).thenReturn(false); assertFalse(SLIAuthenticationEntryPoint.isSecureRequest(request)); LOG.debug("[SLCAuthenticationEntryPointTest]Non-Secure Protocol with non-local environment, return FALSE"); when(request.getServerName()).thenReturn("rcdashboard.slidev.org"); when(request.isSecure()).thenReturn(false); assertFalse(SLIAuthenticationEntryPoint.isSecureRequest(request)); LOG.debug("[SLCAuthenticationEntryPointTest]Secure Protocol with non-local environment, return TRUE"); when(request.getServerName()).thenReturn("rcdashboard.slidev.org"); when(request.isSecure()).thenReturn(true); assertTrue(SLIAuthenticationEntryPoint.isSecureRequest(request)); }
|
SLIAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { HttpSession session = request.getSession(); try { SliApi.setBaseUrl(apiUrl); OAuthService service = new ServiceBuilder().provider(SliApi.class) .apiKey(propDecryptor.getDecryptedClientId()).apiSecret(propDecryptor.getDecryptedClientSecret()) .callback(callbackUrl).build(); boolean cookieFound = checkCookiesForToken(request, session); Object token = session.getAttribute(OAUTH_TOKEN); if (token == null && request.getParameter(OAUTH_CODE) == null) { initiatingAuthentication(request, response, session, service); } else if (token == null && request.getParameter(OAUTH_CODE) != null) { verifyingAuthentication(request, response, session, service); } else { completeAuthentication(request, response, session, token, cookieFound); } } catch (OAuthException ex) { session.invalidate(); LOG.error(LOG_MESSAGE_AUTH_EXCEPTION, new Object[] { ex.getMessage() }); response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage()); return; } } void setCallbackUrl(String callbackUrl); String getCallbackUrl(); void setApiUrl(String apiUrl); String getApiUrl(); RESTClient getRestClient(); void setRestClient(RESTClient restClient); APIClient getApiClient(); void setApiClient(APIClient apiClient); PropertiesDecryptor getPropDecryptor(); void setPropDecryptor(PropertiesDecryptor propDecryptor); @Override void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException); static final String OAUTH_TOKEN; static final String DASHBOARD_COOKIE; }
|
@Test public void testCommence() throws Exception { HttpSession mockSession = mock(HttpSession.class); AuthenticationException mockAuthenticationException = mock(AuthenticationException.class); PropertiesDecryptor mockPropertiesDecryptor = mock(PropertiesDecryptor.class); APIClient mockAPIClient = mock(APIClient.class); RESTClient mockRESTClient = mock(RESTClient.class); JsonParser parser = new JsonParser(); JsonObject jsonObject = (JsonObject)parser.parse("{\"authenticated\":true,\"edOrg\":null,\"edOrgId\":null,\"email\":\"dummy@fake.com\",\"external_id\":\"cgray\",\"full_name\":\"Mr Charles Gray\",\"granted_authorities\":[\"Destroyme\"],\"isAdminUser\":false,\"realm\":\"2013uz-d5ae70c9-55ef-11e2-b6be-68a86d3c2fde\",\"rights\":[\"READ_PUBLIC\",\"READ_GENERAL\",\"AGGREGATE_READ\"],\"sliRoles\":[\"Destroyme\"],\"tenantId\":\"wolverineil.wgen@gmail.com\",\"userType\":\"teacher\",\"user_id\":\"cgray@wolverineil.wgen@gmail.com\"}"); when(request.getSession()).thenReturn(mockSession); when(request.getRemoteAddr()).thenReturn("http: when(request.getServerName()).thenReturn("mock.slidev.org"); when(request.isSecure()).thenReturn(true); when(mockPropertiesDecryptor.getDecryptedClientId()).thenReturn("mock-client-id"); when(mockPropertiesDecryptor.getDecryptedClientSecret()).thenReturn("mock-client-secret"); when(mockPropertiesDecryptor.encrypt(anyString())).thenReturn("MOCK-ENCRYPTED-TOKEN"); when(mockSession.getAttribute(anyString())).thenReturn("Mock-OAUTH-TOKEN"); when(mockRESTClient.sessionCheck(anyString())).thenReturn(jsonObject); SLIAuthenticationEntryPoint sliAuthenticationEntryPoint = new SLIAuthenticationEntryPoint(); sliAuthenticationEntryPoint.setPropDecryptor(mockPropertiesDecryptor); sliAuthenticationEntryPoint.setApiClient(mockAPIClient); sliAuthenticationEntryPoint.setRestClient(mockRESTClient); sliAuthenticationEntryPoint.setApiUrl("/api/mock/uri"); sliAuthenticationEntryPoint.setCallbackUrl("http: sliAuthenticationEntryPoint.commence(request,response,mockAuthenticationException); }
|
SDKAPIClient implements APIClient { @Override public List<GenericEntity> getCourseSectionMappings(List<GenericEntity> sections, String schoolId, String token) { Map<String, GenericEntity> courseMap = new HashMap<String, GenericEntity>(); Map<String, String> sectionIDToCourseIDMap = new HashMap<String, String>(); Map<String, Set<GenericEntity>> sectionLookup = new HashMap<String, Set<GenericEntity>>(); if (sections != null) { Map<String, String> courseOfferingToCourseIDMap = new HashMap<String, String>(); String url = ""; if (schoolId != null) { url = SDKConstants.SCHOOLS_ENTITY + schoolId; } List<GenericEntity> courseOfferings = readEntityList(token, url + SDKConstants.COURSE_OFFERINGS + "?" + this.buildQueryString(null)); if (courseOfferings != null) { for (GenericEntity courseOffering : courseOfferings) { String courseOfferingId = (String) courseOffering.get(Constants.ATTR_ID); String courseId = (String) courseOffering.get(Constants.ATTR_COURSE_ID); courseOfferingToCourseIDMap.put(courseOfferingId, courseId); } } for (GenericEntity section : sections) { String courseOfferingId = (String) section.get(Constants.ATTR_COURSE_OFFERING_ID); String courseId = courseOfferingToCourseIDMap.get(courseOfferingId); if (!sectionLookup.containsKey(courseId)) { sectionLookup.put(courseId, new TreeSet<GenericEntity>(new GenericEntityComparator( Constants.ATTR_SECTION_NAME, String.class))); } sectionLookup.get(courseId).add(section); } List<String> edOrgIds = getEdorgHierarchy(schoolId, token); List<GenericEntity> courses = getCoursesForEdorgs(edOrgIds, token); for (GenericEntity course : courses) { Set<GenericEntity> matchedSections = sectionLookup.get(course.getId()); if (matchedSections != null) { courseMap.put(course.getId(), course); Iterator<GenericEntity> sectionEntities = matchedSections.iterator(); while (sectionEntities.hasNext()) { GenericEntity sectionEntity = sectionEntities.next(); course.appendToList(Constants.ATTR_SECTIONS, sectionEntity); sectionIDToCourseIDMap.put(sectionEntity.getId(), course.getId()); } } } } List<GenericEntity> courses = new ArrayList<GenericEntity>(courseMap.values()); Collections.sort(courses, new GenericEntityComparator(Constants.ATTR_COURSE_TITLE, String.class)); return courses; } SLIClientFactory getClientFactory(); void setClientFactory(SLIClientFactory clientFactory); void setGracePeriod(String gracePeriod); String getGracePeriod(); @Override GenericEntity getEntity(String token, String type, String id, Map<String, String> params); @Override List<GenericEntity> getEntities(String token, String type, String ids, Map<String, String> params); @Override GenericEntity getHome(String token); @Override String getId(String token); @Override ConfigMap getEdOrgCustomData(String token, String id); @Override void putEdOrgCustomData(String token, String id, ConfigMap configMap); @Override List<GenericEntity> getEducationalOrganizations(String token, List<String> ids, Map<String, String> params); @Override List<GenericEntity> getEducationOrganizationsForStaff(String token, String staffId); @Override GenericEntity getEducationalOrganization(String token, String id); @Override GenericEntity getEducationOrganizationForStaff(String token, String staffId, String organizationCategory); @Override List<GenericEntity> getParentEducationalOrganizations(String token,
List<GenericEntity> educationalOrganizations); @Override GenericEntity getParentEducationalOrganization(String token, GenericEntity educationalOrganization); @Override List<GenericEntity> getSchools(String token, List<String> ids); @Override List<GenericEntity> getMySchools(String token); @Override List<GenericEntity> getSchools(String token, List<String> ids, Map<String, String> params); @Override GenericEntity getSchool(String token, String id); @Override List<GenericEntity> getSessions(String token, String schoolId, Map<String, String> params); @Override List<GenericEntity> getSessions(String token, List<String> ids, Map<String, String> params); @Override List<GenericEntity> getSessionsForYear(String token, String schoolYear); @Override GenericEntity getSession(String token, String id); @Override List<GenericEntity> getSections(String token, Map<String, String> params); @Override List<GenericEntity> getSections(String token, List<String> ids, Map<String, String> params); @Override List<GenericEntity> getSectionsForNonEducator(String token, Map<String, String> params); @Override List<GenericEntity> getSectionsForTeacher(String teacherId, String token, Map<String, String> params); @Override List<GenericEntity> getSectionsForStudent(final String token, final String studentId,
Map<String, String> params); @Override @CacheableUserData GenericEntity getSection(String token, String id); @Override GenericEntity getSectionHomeForStudent(String token, String studentId); @Override List<GenericEntity> getCourses(String token, List<String> ids, Map<String, String> params); List<GenericEntity> getCourses(String token, List<String> ids); @Override List<GenericEntity> getCoursesForStudent(String token, String studentId, Map<String, String> params); @Override List<GenericEntity> getCoursesSectionsForSchool(String token, String schoolId); @Override List<GenericEntity> getTranscriptsForStudent(String token, String studentId, Map<String, String> params); @Override GenericEntity getCourse(String token, String id); @Override List<GenericEntity> getStaff(String token, List<String> ids, Map<String, String> params); @Override GenericEntity getStaff(String token, String id); @Override GenericEntity getStaffWithEducationOrganization(String token, String id, String organizationCategory); @Override List<GenericEntity> getTeachers(String token, List<String> ids, Map<String, String> params); @Override @CacheableUserData GenericEntity getTeacher(String token, String id); @Override GenericEntity getTeacherWithSections(String token, String id); @Override GenericEntity getTeacherForSection(String token, String sectionId); @Override String getTeacherIdForSection(String token, String sectionId); @Override void getTeacherIdForSections(String token, List<String> sectionIds, Map<String, String> teacherIdCache); @Override List<GenericEntity> getTeachersForSchool(String token, String schoolId); @Override List<GenericEntity> getParentsForStudent(String token, String studentId, Map<String, String> params); @Override List<GenericEntity> getStudentsForSchool(String token, String schoolId, Map<String, String> params); @Override List<GenericEntity> getStudents(String token, Map<String, String> params); @Override List<GenericEntity> getStudents(String token, List<String> ids, Map<String, String> params); @Override List<GenericEntity> getStudentsForSection(String token, String sectionId); @Override List<GenericEntity> getStudentsWithSearch(String token, String firstName, String lastName, String schoolId); @Override List<GenericEntity> searchStudents(String token, String query, Map<String, String> params); @Override List<GenericEntity> getStudentsForSectionWithGradebookEntries(String token, String sectionId); @Override @CacheableUserData GenericEntity getStudent(String token, String id); @Override GenericEntity getStudentWithOptionalFields(String token, String id, List<String> optionalFields); @Override List<GenericEntity> getEnrollmentForStudent(String token, String studentId); @Override List<GenericEntity> getAttendanceForStudent(String token, String studentId, Map<String, String> params); @Override List<GenericEntity> getAcademicRecordsForStudent(String token, String studentId, Map<String, String> params); @Override List<GenericEntity> getAssessments(String token, List<String> ids, Map<String, String> params); @Override List<GenericEntity> getAssessmentsForStudent(String token, String studentId); @Override GenericEntity getAssessment(String token, String id); @Override @ExecutionTimeLogger.LogExecutionTime GenericEntity readEntity(String token, String url); @ExecutionTimeLogger.LogExecutionTime @Override @CacheableUserData List<GenericEntity> readEntityList(String token, String url); @Override List<GenericEntity> readEntityList(String token, List<String> ids, Map<String, String> params, String type); @Override List<GenericEntity> getCourseSectionMappings(List<GenericEntity> sections, String schoolId, String token); SLIClient getClient(String sessionToken); }
|
@Test public void shouldGetCourseSectionMappings() throws SLIClientException, IOException, URISyntaxException { List<GenericEntity> sections = new ArrayList<GenericEntity>(); sections.add(createSection("S1", "CO1", "Section 1")); sections.add(createSection("S2", "CO2", "Section 2")); List<Entity> courseOfferings = new ArrayList<Entity>(); courseOfferings.add(createCourseOffering("CO1", "C1")); courseOfferings.add(createCourseOffering("CO2", "C2")); when(mockSliClient.read("/schools/SCHOOL_ID/courseOfferings/?limit=0")).thenReturn(courseOfferings); when(mockSliClient.read("/educationOrganizations/SCHOOL_ID")) .thenReturn(asList(createEdOrg(SCHOOL_ID, LEA_ID))); when(mockSliClient.read("/educationOrganizations/LEA_ID")).thenReturn(asList(createEdOrg(LEA_ID, SEA_ID))); when(mockSliClient.read("/educationOrganizations/SEA_ID")).thenReturn(asList(createEdOrg(SEA_ID, null))); when(mockSliClient.read("/educationOrganizations/SCHOOL_ID/courses?limit=0")).thenReturn( asList(createCourse("C1", "C1"))); when(mockSliClient.read("/educationOrganizations/LEA_ID/courses?limit=0")).thenReturn( asList(createCourse("C2", "C1"))); List<GenericEntity> result = sdkapiClient.getCourseSectionMappings(sections, SCHOOL_ID, TOKEN); Assert.assertEquals(2, result.size()); }
|
Response extends WadlElement { public List<String> getStatusCodes() { return statusCodes; } Response(final List<String> statusCodes, final List<Documentation> doc, final List<Param> params,
final List<Representation> representations); List<String> getStatusCodes(); List<Param> getParams(); List<Representation> getRepresentations(); @Override String toString(); }
|
@Test public void testGetStatusCodes() { assertEquals(STATUS_CODES, response.getStatusCodes()); }
|
TenantMongoDA implements TenantDA { @Override public void insertTenant(TenantRecord tenant) { if (entityRepository.findOne(TENANT_COLLECTION, new NeutralQuery(new NeutralCriteria(TENANT_ID, "=", tenant.getTenantId()))) == null) { entityRepository.create(TENANT_COLLECTION, getTenantBody(tenant)); } } @Override List<String> getLzPaths(); @Override String getTenantId(String lzPath); @Override void insertTenant(TenantRecord tenant); @Override @SuppressWarnings("unchecked") String getTenantEdOrg(String lzPath); Repository<Entity> getEntityRepository(); void setEntityRepository(Repository<Entity> entityRepository); @SuppressWarnings("unchecked") @Override Map<String, List<String>> getPreloadFiles(String ingestionServer); @Override boolean tenantDbIsReady(String tenantId); @Override void setTenantReadyFlag(String tenantId); @Override void unsetTenantReadyFlag(String tenantId); @Override boolean updateAndAquireOnboardingLock(String tenantId); @Override void removeInvalidTenant(String lzPath); @Override Map<String, List<String>> getPreloadFiles(); @Override List<String> getAllTenantDbs(); static final String TENANT_ID; static final String DB_NAME; static final String INGESTION_SERVER; static final String PATH; static final String LANDING_ZONE; static final String PRELOAD_DATA; static final String PRELOAD_STATUS; static final String PRELOAD_FILES; static final String TENANT_COLLECTION; static final String TENANT_TYPE; static final String EDUCATION_ORGANIZATION; static final String DESC; static final String ALL_STATUS_FIELDS; static final String STATUS_FIELD; }
|
@Test public void shouldInsertTenant() { TenantRecord tenantRecord = createTestTenantRecord(); tenantDA.insertTenant(tenantRecord); Mockito.verify(mockRepository).create(Mockito.eq("tenant"), Mockito.argThat(new IsCorrectBody(tenantRecord))); }
|
Response extends WadlElement { public List<Param> getParams() { return params; } Response(final List<String> statusCodes, final List<Documentation> doc, final List<Param> params,
final List<Representation> representations); List<String> getStatusCodes(); List<Param> getParams(); List<Representation> getRepresentations(); @Override String toString(); }
|
@Test public void testGetParams() { assertEquals(PARAMS, response.getParams()); }
|
Response extends WadlElement { public List<Representation> getRepresentations() { return representations; } Response(final List<String> statusCodes, final List<Documentation> doc, final List<Param> params,
final List<Representation> representations); List<String> getStatusCodes(); List<Param> getParams(); List<Representation> getRepresentations(); @Override String toString(); }
|
@Test public void testGetRepresentations() { assertEquals(REPRESENTATIONS, response.getRepresentations()); }
|
Response extends WadlElement { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("statusCodes").append(" : ").append(statusCodes); sb.append(", "); sb.append("params").append(" : ").append(params); sb.append(", "); sb.append("representations").append(" : ").append(representations); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } Response(final List<String> statusCodes, final List<Documentation> doc, final List<Param> params,
final List<Representation> representations); List<String> getStatusCodes(); List<Param> getParams(); List<Representation> getRepresentations(); @Override String toString(); }
|
@Test public void testToString() { assertTrue(!"".equals(response.toString())); }
|
Request extends WadlElement { public List<Param> getParams() { return params; } Request(final List<Documentation> doc, final List<Param> params, final List<Representation> representations); List<Param> getParams(); List<Representation> getRepresentations(); @Override String toString(); }
|
@Test public void testGetParams() { assertEquals(PARAMS, request.getParams()); }
|
Request extends WadlElement { public List<Representation> getRepresentations() { return representations; } Request(final List<Documentation> doc, final List<Param> params, final List<Representation> representations); List<Param> getParams(); List<Representation> getRepresentations(); @Override String toString(); }
|
@Test public void testGetRepresentations() { assertEquals(REPRESENTATIONS, request.getRepresentations()); }
|
Request extends WadlElement { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("params").append(" : ").append(params); sb.append(", "); sb.append("representations").append(" : ").append(representations); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } Request(final List<Documentation> doc, final List<Param> params, final List<Representation> representations); List<Param> getParams(); List<Representation> getRepresentations(); @Override String toString(); }
|
@Test public void testToString() { assertTrue(!"".equals(request.toString())); }
|
Representation extends WadlElement { public String getId() { return id; } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); String getId(); QName getElementName(); String getMediaType(); List<String> getProfiles(); List<Param> getParams(); @Override String toString(); }
|
@Test public void testGetId() { assertEquals(ID, representation.getId()); }
|
Representation extends WadlElement { public String getMediaType() { return mediaType; } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); String getId(); QName getElementName(); String getMediaType(); List<String> getProfiles(); List<Param> getParams(); @Override String toString(); }
|
@Test public void testGetMediaType() { assertEquals(MEDIA_TYPE, representation.getMediaType()); }
|
Representation extends WadlElement { public List<Param> getParams() { return params; } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); String getId(); QName getElementName(); String getMediaType(); List<String> getProfiles(); List<Param> getParams(); @Override String toString(); }
|
@Test public void testGetParams() { assertEquals(PARAMS, representation.getParams()); }
|
Representation extends WadlElement { public List<String> getProfiles() { return profiles; } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); String getId(); QName getElementName(); String getMediaType(); List<String> getProfiles(); List<Param> getParams(); @Override String toString(); }
|
@Test public void testGetProfiles() { assertEquals(PROFILES, representation.getProfiles()); }
|
TenantMongoDA implements TenantDA { @SuppressWarnings("unchecked") @Override public Map<String, List<String>> getPreloadFiles(String ingestionServer) { Iterable<Entity> tenants = entityRepository.findAll( TENANT_COLLECTION, new NeutralQuery(byServerQuery(ingestionServer)).addCriteria(PRELOAD_READY_CRITERIA).setIncludeFields( Arrays.asList(LANDING_ZONE + "." + PRELOAD_DATA, LANDING_ZONE_PATH, LANDING_ZONE_INGESTION_SERVER))); Map<String, List<String>> fileMap = new HashMap<String, List<String>>(); for (Entity tenant : tenants) { if (markPreloadStarted(tenant)) { List<Map<String, Object>> landingZones = (List<Map<String, Object>>) tenant.getBody().get(LANDING_ZONE); for (Map<String, Object> landingZone : landingZones) { if (landingZone.get(INGESTION_SERVER).equals(ingestionServer)) { List<String> files = new ArrayList<String>(); Map<String, Object> preloadData = (Map<String, Object>) landingZone.get(PRELOAD_DATA); if (preloadData != null) { if ("ready".equals(preloadData.get(PRELOAD_STATUS))) { files.addAll((Collection<? extends String>) preloadData.get(PRELOAD_FILES)); } fileMap.put((String) landingZone.get(PATH), files); } } } } } return fileMap; } @Override List<String> getLzPaths(); @Override String getTenantId(String lzPath); @Override void insertTenant(TenantRecord tenant); @Override @SuppressWarnings("unchecked") String getTenantEdOrg(String lzPath); Repository<Entity> getEntityRepository(); void setEntityRepository(Repository<Entity> entityRepository); @SuppressWarnings("unchecked") @Override Map<String, List<String>> getPreloadFiles(String ingestionServer); @Override boolean tenantDbIsReady(String tenantId); @Override void setTenantReadyFlag(String tenantId); @Override void unsetTenantReadyFlag(String tenantId); @Override boolean updateAndAquireOnboardingLock(String tenantId); @Override void removeInvalidTenant(String lzPath); @Override Map<String, List<String>> getPreloadFiles(); @Override List<String> getAllTenantDbs(); static final String TENANT_ID; static final String DB_NAME; static final String INGESTION_SERVER; static final String PATH; static final String LANDING_ZONE; static final String PRELOAD_DATA; static final String PRELOAD_STATUS; static final String PRELOAD_FILES; static final String TENANT_COLLECTION; static final String TENANT_TYPE; static final String EDUCATION_ORGANIZATION; static final String DESC; static final String ALL_STATUS_FIELDS; static final String STATUS_FIELD; }
|
@SuppressWarnings("unchecked") @Test public void testGetAutoLoadFiles() throws UnknownHostException { Map<String, Object> tenantsForPreloading = new HashMap<String, Object>(); tenantsForPreloading.put(lzPath1, Arrays.asList("smallDataSet.xml", "mediumDataSet.xml")); Entity tenant = createTenantEntity(); List<Map<String, Object>> landingZone = (List<Map<String, Object>>) tenant.getBody().get( TenantMongoDA.LANDING_ZONE); Map<String, Object> preloadDef = new HashMap<String, Object>(); preloadDef.put(TenantMongoDA.PRELOAD_STATUS, "ready"); preloadDef.put(TenantMongoDA.PRELOAD_FILES, Arrays.asList("smallDataSet.xml", "mediumDataSet.xml")); landingZone.get(0).put(TenantMongoDA.PRELOAD_DATA, preloadDef); when(mockRepository.findAll(eq("tenant"), any(NeutralQuery.class))).thenReturn(Arrays.asList(tenant)); when(mockRepository.doUpdate(eq("tenant"), any(NeutralQuery.class), any(Update.class))).thenReturn(true); assertEquals(tenantsForPreloading, tenantDA.getPreloadFiles("ingestion_server_host")); verify(mockRepository).doUpdate(eq("tenant"), any(NeutralQuery.class), argThat(new ArgumentMatcher<Update>() { @Override public boolean matches(Object argument) { Update expectedUpdate = Update.update("body." + TenantMongoDA.LANDING_ZONE + ".$." + TenantMongoDA.PRELOAD_DATA + "." + TenantMongoDA.PRELOAD_STATUS, "started"); return ((Update) argument).getUpdateObject().equals(expectedUpdate.getUpdateObject()); } })); }
|
Representation extends WadlElement { public QName getElementName() { return elementName; } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); String getId(); QName getElementName(); String getMediaType(); List<String> getProfiles(); List<Param> getParams(); @Override String toString(); }
|
@Test public void testGetElementName() { assertEquals(ELEMENT_NAME, representation.getElementName()); }
|
Representation extends WadlElement { @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("id").append(" : ").append(id); sb.append(", "); sb.append("elementName").append(" : ").append(elementName); sb.append(", "); sb.append("mediaType").append(" : ").append(mediaType); sb.append(", "); sb.append("profiles").append(" : ").append(profiles); sb.append(", "); sb.append("params").append(" : ").append(params); sb.append(", "); sb.append("doc").append(" : ").append(getDocumentation()); sb.append("}"); return sb.toString(); } Representation(final String id, final QName elementName, final String mediaType,
final List<String> profiles, final List<Documentation> doc, final List<Param> params); String getId(); QName getElementName(); String getMediaType(); List<String> getProfiles(); List<Param> getParams(); @Override String toString(); }
|
@Test public void testToString() { assertTrue(!"".equals(representation.toString())); }
|
Grammars extends WadlElement { public List<Include> getIncludes() { return includes; } Grammars(final List<Documentation> doc, final List<Include> includes); List<Include> getIncludes(); @Override String toString(); }
|
@Test public void testGetIncludes() { assertEquals(INCLUDES, grammars.getIncludes()); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.