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 = HashMul... | @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... |
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 ha... | @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"... |
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 ... | @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.setSearchResul... |
DownloadStatusUpdater { protected void checkStatus(List<FileDownloadStatus> nzbDownloadStatuses, long maxAgeDownloadEntitiesInSeconds, StatusCheckType statusCheckType) { if ((!queueCheckEnabled && statusCheckType == StatusCheckType.QUEUE) || (!historyCheckEnabled && statusCheckType == StatusCheckType.HISTORY)) { logger... | @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 shouldNotRunWhenLastDownloa... |
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, "Rec... | @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(lo... | @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()... |
DownloaderStatus { public List<Long> getDownloadingRatesInKilobytes() { if (downloadingRatesInKilobytes.isEmpty() || downloadingRatesInKilobytes.size() < 5) { return downloadingRatesInKilobytes; } if (downloadingRatesInKilobytes.get(downloadingRatesInKilobytes.size() - 1) / (float) 10 > downloadingRatesInKilobytes.get(... | @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, 10... |
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()).f... | @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(logContentProvi... |
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 = configProvi... | @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... |
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<api... | @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: ... |
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 in... | @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.... |
IndexerForSearchSelector { protected boolean checkIndexerSelectedByUser(Indexer indexer) { boolean indexerNotSelectedByUser = (searchRequest.getIndexers().isPresent() && !searchRequest.getIndexers().get().isEmpty()) && !searchRequest.getIndexers().get().contains(indexer.getName()); if (indexerNotSelectedByUser) { logge... | @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.checkIndexerS... |
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(C... | @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(Categ... | @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); ... | @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.setDo... |
CapsGenerator { CapsXmlCategories getCapsXmlCategories() { if (configProvider.getBaseConfig().getSearching().isTransformNewznabCategories()) { Map<Integer, CapsXmlCategory> mainXmlCategoriesMap = new HashMap<>(); Set<String> alreadyAdded = new HashSet<>(); for (Category category : configProvider.getBaseConfig().getCate... | @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()... |
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... | @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("apik... |
BaseConfig extends ValidatingConfig<BaseConfig> { @Override public ConfigValidationResult validateConfig(BaseConfig oldConfig, BaseConfig newConfig, BaseConfig newBaseConfig) { ConfigValidationResult configValidationResult = new ConfigValidationResult(); ConfigValidationResult authValidation = newConfig.getAuth().valid... | @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(indexerCo... |
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... | @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.DIS... |
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 t... | @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()).thenRe... |
ConfigMigration { protected static List<ConfigMigrationStep> getMigrationSteps() { ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); provider.addIncludeFilter(new AssignableTypeFilter(ConfigMigrationStep.class)); Set<BeanDefinition> candidates = provider.find... | @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... |
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<Str... | @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.mi... |
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()); lastChecke... | @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).g... | @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.getNewsForCur... |
IndexerForSearchSelector { protected boolean checkDisabledForCategory(Indexer indexer) { if (searchRequest.getCategory().getSubtype().equals(Subtype.ALL)) { return true; } boolean indexerDisabledForThisCategory = !indexer.getConfig().getEnabledCategories().isEmpty() && !indexer.getConfig().getEnabledCategories().contai... | @Test public void shouldCheckForCategory() { when(searchRequest.getCategory()).thenReturn(category); indexerConfigMock.setEnabledCategories(Collections.emptyList()); assertTrue(testee.checkDisabledForCategory(indexer)); indexerConfigMock.setEnabledCategories(Arrays.asList("anotherCategory")); assertFalse(testee.checkDi... |
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(... | @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(); }... | @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.Unive... |
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(searchReque... | @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(searchRes... |
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) { E... | @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); Ind... |
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 (Str... | @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.toUriStrin... |
IndexerForSearchSelector { protected boolean checkLoadLimiting(Indexer indexer) { boolean preventedByLoadLimiting = indexer.getConfig().getLoadLimitOnRandom().isPresent() && random.nextInt(indexer.getConfig().getLoadLimitOnRandom().get()) + 1 != 1; if (preventedByLoadLimiting) { boolean loadLimitIgnored = configProvide... | @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 countNot... |
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(() -> getAndStoreResultToDatab... | @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> a... | @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 IndexerS... |
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... | @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(Inde... |
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", inde... | @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_TEMPORAR... |
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.isEmpt... | @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... |
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.getRs... | @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().a... |
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 bui... |
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.getNew... | @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),... |
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 %... | @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(sear... |
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 ... | @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.toUriStrin... |
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.... | @Test public void shouldLimitQueryLengthWhenAddingForbiddenWords() throws Exception { SearchRequest request = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); request.getInternalData().setForbiddenWords(Arrays.asList("characters50sssssssssssssssssssssssssssssssssssss1", "characters50ssssssssssssssss... |
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... | @Test public void shouldLimitQueryLengthWhenAddingRequiredWords() throws Exception { SearchRequest request = new SearchRequest(SearchSource.INTERNAL, SearchType.SEARCH, 0, 100); request.getInternalData().setRequiredWords(Arrays.asList("characters50sssssssssssssssssssssssssssssssssssss1", "characters50ssssssssssssssssss... |
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... | @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); ... | @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 indexerSea... |
Newznab extends Indexer<Xml> { protected UriComponentsBuilder extendQueryUrlWithSearchIds(SearchRequest searchRequest, UriComponentsBuilder componentsBuilder) { if (!searchRequest.getIdentifiers().isEmpty()) { Map<MediaIdType, String> params = new HashMap<>(); boolean idConversionNeeded = isIdConversionNeeded(searchReq... | @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");... |
IndexerForSearchSelector { protected boolean checkSearchId(Indexer indexer) { boolean needToSearchById = !searchRequest.getIdentifiers().isEmpty() && !searchRequest.getQuery().isPresent(); if (needToSearchById) { boolean canUseAnyProvidedId = !Collections.disjoint(searchRequest.getIdentifiers().keySet(), indexer.getCon... | @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(tru... |
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.toStr... | @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(... |
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 = i... | @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(n... |
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(F... | @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... |
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 en... | @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 ... |
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)) { journalCollapsed... | @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"); } jo... | @Test public void testJournalCollapsedSubDocs() throws DecoderException { String assessment1id = "1234567890123456789012345678901234567890"; String assessment2id = "1234567890123456789012345678901234567892"; deltaJournal.journal( Arrays.asList(assessment1id + "_id1234567890123456789012345678901234567891_id", assessment... |
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, DELT... | @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).get... |
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(!idP... | @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))); ... |
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")... | @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.... |
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 paren... | @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(Objec... |
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 { EdfiRecordUnmarshall... | @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/InterchangeStudentPa... |
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 docTy... | @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.star... |
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 = retr... | @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()... |
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(Ent... | @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 ... |
ContainerDocumentAccessor { public boolean isContainerDocument(final String entity) { return containerDocumentHolder.isContainerDocument(entity); } ContainerDocumentAccessor(final UUIDGeneratorStrategy strategy, final INaturalKeyExtractor extractor,
final MongoTemplate mongoTemplate... | @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; } ContainerDocumentA... | @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.isC... |
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,
... | @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(createCo... |
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(... | @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... |
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); subdocsTo... | @Test public void upconvertShouldRemoveAPD_references() { Entity oldEntity = createUpConvertEntity(); Entity entity = assessmentConverter.subdocToBodyField(oldEntity); assertNull(entity.getBody().get("assessmentPeriodDescriptorId")); }
@Test public void upconvertNoEmbeddedSubdocShouldRemainUnchanged() { List<Entity> ol... |
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 ent... | @Test public void downconvertShouldDeleteAssessmentFamilyHierarchy() { Entity entity = createDownConvertEntity(); assessmentConverter.bodyFieldToSubdoc(entity); assertNull(entity.getBody().get(ASSESSMENT_FAMILY_HIERARCHY)); }
@Test public void downconvertShouldDeleteAssessmentFamilyHierarchyExistingAssessment() { Entit... |
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 ... | @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 (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", "f... |
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(collec... | @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 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(splitD... | @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 getTenantEd... | @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); ass... |
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 = ne... | @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 edO... |
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... | @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.t... |
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 (studentParentAssociati... | @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, "Fathe... |
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 enha... | @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"); ent... |
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; }... | @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(); enti... |
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() &&... | @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... |
SLIAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { HttpSession session = request.getSession(); try { SliApi.setBaseUrl(apiUrl); OAuthServi... | @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)... |
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<St... | @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 ... |
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<Representati... | @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<Str... | @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> getRepr... | @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(); L... | @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(" : ").app... | @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(g... | @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(); Lis... | @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 getMe... | @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 getMed... | @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 g... | @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).setIncludeF... | @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... |
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 ge... | @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(medi... | @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.