method2testcases stringlengths 118 6.63k |
|---|
### Question:
ClassLoaderPolicy { public boolean canLoad(String className) { if (deniedPaths.contains("")) { return false; } String[] split = className.split("\\."); String current = ""; for (String part : split) { current += (current.equals("")) ? part : ("." + part); if (deniedPaths.contains(current)) { return false;... |
### Question:
LibraryVersion { public boolean equals(LibraryVersion v) { return v.toString().equals(this.toString()); } LibraryVersion(String version); LibraryVersion(int major, int minor, int sub, int build); LibraryVersion(int major, int minor, int sub); LibraryVersion(int major, int minor); LibraryVersion(int ma... |
### Question:
RESTService extends Service { public final String getSwagger() throws JsonProcessingException { Swagger swagger = new Reader(new Swagger()).read(this.application.getClasses()); return Json.mapper().writeValueAsString(swagger); } RESTService(); final RESTResponse handle(URI baseUri, URI requestUri, String ... |
### Question:
LibraryVersion { @Override public String toString() { String result = "" + major; if (minor != null) { result += "." + minor; if (sub != null) result += "." + sub; } if (build != null) result += "-" + build; return result; } LibraryVersion(String version); LibraryVersion(int major, int minor, int sub, in... |
### Question:
LibraryIdentifier { public boolean equals(LibraryIdentifier i) { return this.toString().equals(i.toString()); } LibraryIdentifier(String name); LibraryIdentifier(String name, String version); LibraryIdentifier(String name, LibraryVersion version); static LibraryIdentifier fromFilename(String filename); ... |
### Question:
LibraryIdentifier { public static LibraryIdentifier fromFilename(String filename) { String fileNameWithOutExt = new File(filename).getName().replaceFirst("[.][^.]+$", ""); Pattern versionPattern = Pattern.compile("-[0-9]+(?:.[0-9]+(?:.[0-9]+)?)?(?:-[0-9]+)?$"); Matcher m = versionPattern.matcher(fileNameW... |
### Question:
LoadedJarLibrary extends LoadedLibrary { public static LoadedJarLibrary createFromJar(String filename) throws IllegalArgumentException, IOException { JarFile jfFile = new JarFile(filename); String sName = jfFile.getManifest().getMainAttributes() .getValue(LibraryIdentifier.MANIFEST_LIBRARY_NAME_ATTRIBUTE)... |
### Question:
LoadedLibrary { public static String resourceToClassName(String entryName) { if (!entryName.endsWith(".class")) { throw new IllegalArgumentException("This is not a class file!"); } return entryName.replace('/', '.').substring(0, entryName.length() - 6); } LoadedLibrary(String libraryIdentifier); LoadedL... |
### Question:
LoadedLibrary { public static String classToResourceName(String className) { return className.replace('.', '/') + ".class"; } LoadedLibrary(String libraryIdentifier); LoadedLibrary(LibraryIdentifier lib); LibraryIdentifier getLibraryIdentifier(); abstract URL getResourceAsUrl(String name); String getRes... |
### Question:
FileSystemRepository implements Repository { public static long getLastModified(File dir, boolean recursive) { File[] files = dir.listFiles(); if (files == null || files.length == 0) { return dir.lastModified(); } long lastModified = 0; for (File f : files) { if (f.isDirectory() && recursive) { long ll = ... |
### Question:
L2pLogger extends Logger implements NodeObserver { public static L2pLogger getInstance(Class<?> cls) throws ClassCastException { return getInstance(cls.getCanonicalName()); } protected L2pLogger(String name, String resourceBundleName); synchronized void printStackTrace(Throwable e); static void setGlobal... |
### Question:
UserAgentManager { public String getAgentIdByLogin(String name) throws AgentNotFoundException, AgentOperationFailedException { if (name.equalsIgnoreCase(AnonymousAgent.LOGIN_NAME)) { return AnonymousAgentImpl.getInstance().getIdentifier(); } try { EnvelopeVersion env = node.fetchEnvelope(PREFIX_USER_NAME ... |
### Question:
ServiceAgentGenerator { public static void main(String argv[]) { if (argv.length != 2) { System.err.println( "usage: java i5.las2peer.tools.ServiceAgentGenerator [service class]@[service version] [passphrase]"); return; } else if (argv[0].length() < PW_MIN_LENGTH) { System.err.println("the password needs ... |
### Question:
UserAgentManager { public String getAgentIdByEmail(String email) throws AgentNotFoundException, AgentOperationFailedException { try { EnvelopeVersion env = node.fetchEnvelope(PREFIX_USER_MAIL + email.toLowerCase()); return (String) env.getContent(); } catch (EnvelopeNotFoundException e) { throw new AgentN... |
### Question:
UserAgentImpl extends PassphraseAgentImpl implements UserAgent { public static UserAgentImpl createUserAgent(String passphrase) throws CryptoException, AgentOperationFailedException { byte[] salt = CryptoTools.generateSalt(); return new UserAgentImpl(CryptoTools.generateKeyPair(), passphrase, salt); } pro... |
### Question:
Mediator implements MessageReceiver { @Override public void receiveMessage(Message message, AgentContext c) throws MessageException { if (!message.getRecipientId().equalsIgnoreCase(myAgent.getIdentifier())) { throw new MessageException("I'm not responsible for the receiver (something went very wrong)!"); ... |
### Question:
ServiceAgentImpl extends PassphraseAgentImpl implements ServiceAgent { public static long serviceNameToTopicId(String service) { return SimpleTools.longHash(service); } protected ServiceAgentImpl(ServiceNameVersion service, KeyPair pair, String passphrase, byte[] salt); protected ServiceAgentImpl(Servic... |
### Question:
AgentContext implements AgentStorage { public Agent requestAgent(String agentId) throws AgentAccessDeniedException, AgentNotFoundException, AgentOperationFailedException { if (agentId.equalsIgnoreCase(getMainAgent().getIdentifier())) { return getMainAgent(); } else { try { return requestGroupAgent(agentId... |
### Question:
AgentContext implements AgentStorage { public boolean hasAccess(String agentId) throws AgentNotFoundException { if (agent.getIdentifier().equals(agentId)) { return true; } AgentImpl a; try { a = getAgent(agentId); } catch (AgentException e) { throw new AgentNotFoundException("Agent could not be found!", e... |
### Question:
AnonymousAgentImpl extends AgentImpl implements AnonymousAgent { @Override public boolean isLocked() { return false; } private AnonymousAgentImpl(); static AnonymousAgentImpl getInstance(); @Override String toXmlString(); @Override void receiveMessage(Message message, AgentContext c); @Override void unlo... |
### Question:
AnonymousAgentImpl extends AgentImpl implements AnonymousAgent { @Override public String getIdentifier() { return AnonymousAgent.IDENTIFIER; } private AnonymousAgentImpl(); static AnonymousAgentImpl getInstance(); @Override String toXmlString(); @Override void receiveMessage(Message message, AgentContext... |
### Question:
Message implements XmlAble, Cloneable { public void open(AgentStorage storage) throws InternalSecurityException, AgentException { open(null, storage); } Message(); Message(AgentImpl from, AgentImpl to, Serializable data); Message(AgentImpl from, AgentImpl to, Serializable data, long timeOutMs); Message... |
### Question:
Message implements XmlAble, Cloneable { @Override public String toXmlString() { String response = ""; if (responseToId != null) { response = " responseTo=\"" + responseToId + "\""; } String sending = ""; if (sendingNodeId != null) { if (sendingNodeId instanceof Long || sendingNodeId instanceof NodeHandle)... |
### Question:
ExecutionContext implements Context { @Override public void storeAgent(Agent agent) throws AgentAccessDeniedException, AgentAlreadyExistsException, AgentOperationFailedException, AgentLockedException { if (agent.isLocked()) { throw new AgentLockedException(); } else if (agent instanceof AnonymousAgent) { ... |
### Question:
ServiceHelper { public static Object execute(Service service, String method) throws ServiceMethodNotFoundException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { return execute(service, method, new Object[0]); } static Class<?> getWrapperClass(Class<?> c); static boolean i... |
### Question:
SimpleTools { public static String join(Object[] objects, String glue) { if (objects == null) { return ""; } return SimpleTools.join(Arrays.asList(objects), glue); } static long longHash(String s); static String createRandomString(int length); static String join(Object[] objects, String glue); static Str... |
### Question:
SimpleTools { public static String repeat(String string, int count) { if (string == null) { return null; } else if (string.isEmpty() || count <= 0) { return ""; } StringBuffer result = new StringBuffer(); for (int i = 0; i < count; i++) { result.append(string); } return result.toString(); } static long l... |
### Question:
Utils { public static void print(String title, String message, int type) { switch (type) { case Log.DEBUG: Log.d("EntireNews (" + title + ")", message); break; case Log.ERROR: Log.e("EntireNews (" + title + ")", message); break; case Log.INFO: Log.i("EntireNews (" + title + ")", message); break; case Log.... |
### Question:
Utils { public static String createSlug(final String slug) { return slug.replaceAll("[^\\w\\s]", "").trim().toLowerCase().replaceAll("\\W+", "-"); } static void print(String title, String message, int type); static void print(final String title, final int message); static void print(final String title, f... |
### Question:
PlaygroundApplication { public static void main(String[] args) { SpringApplication.run(PlaygroundApplication.class, args); } static void main(String[] args); }### Answer:
@Test public void main() throws Exception { PlaygroundApplication playgroundApplication = new PlaygroundApplication(); playgroundAppl... |
### Question:
ProductService { public TdBProduct getProductInfo(Long productId) { TdBProduct tdBProduct = tdBProductRepository.findOne(productId); if (tdBProduct == null) { throw new ResourceNotFoundException(String.format("不存在 productId=%s", productId)); } return tdBProduct; } TdBProduct getProductInfo(Long productId... |
### Question:
RootController { @RequestMapping(value = {"/"}, method = RequestMethod.GET) public String rootRedirect() { return "index"; } @RequestMapping(value = {"/"}, method = RequestMethod.GET) String rootRedirect(); }### Answer:
@Test public void rootRedirect() throws Exception { ResponseEntity<String> result = ... |
### Question:
ProductController { @Cacheable("getProductInfo") @HystrixCommand( fallbackMethod = "", ignoreExceptions = {Exception.class} ) @ApiOperation(value = "查询产品配置") @RequestMapping(value = "/{productId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public ProductDTO getProductIn... |
### Question:
SemanticVersion implements Comparable<SemanticVersion>, Serializable { @Override public String toString() { StringBuilder ret = new StringBuilder(); ret.append(major); ret.append('.'); ret.append(minor); ret.append('.'); ret.append(patch); if (qualifier != null) { ret.append('-'); ret.append(qualifier); }... |
### Question:
Newznab extends Indexer<Xml> { protected void computeCategory(SearchResultItem searchResultItem, List<Integer> newznabCategories) { if (!newznabCategories.isEmpty()) { Integer mostSpecific = newznabCategories.stream().max(Integer::compareTo).get(); IndexerCategoryConfig mapping = config.getCategoryMapping... |
### Question:
NzbGeek extends Newznab { @Override protected String cleanupQuery(String query) { String[] split = query.split(" "); if (query.split(" ").length > 6) { query = Joiner.on(" ").join(Arrays.copyOfRange(split, 0, 6)); } return query.replace("\"", ""); } }### Answer:
@Test public void shouldNotUseMoreThan6W... |
### Question:
IndexerStatusesCleanupTask { @HydraTask(configId = "cleanUpIndexerStatuses", name = "Clean up indexer statuses", interval = MINUTE) public void cleanup() { boolean anyChanges = false; for (IndexerConfig config : configProvider.getBaseConfig().getIndexers()) { if (config.getState() == IndexerConfig.State.D... |
### Question:
IndexerWebAccess { @SuppressWarnings("unchecked") public <T> T get(URI uri, IndexerConfig indexerConfig) throws IndexerAccessException { return get(uri, indexerConfig, null); } @SuppressWarnings("unchecked") T get(URI uri, IndexerConfig indexerConfig); @SuppressWarnings("unchecked") T get(URI uri, Indexe... |
### Question:
IndexerForSearchSelector { protected boolean checkIndexerHitLimit(Indexer indexer) { Stopwatch stopwatch = Stopwatch.createStarted(); IndexerConfig indexerConfig = indexer.getConfig(); if (!indexerConfig.getHitLimit().isPresent() && !indexerConfig.getDownloadLimit().isPresent()) { return true; } LocalDate... |
### Question:
InfoProvider { public boolean canConvert(MediaIdType from, MediaIdType to) { return canConvertMap.get(from).contains(to); } boolean canConvert(MediaIdType from, MediaIdType to); static Set<MediaIdType> getConvertibleFrom(MediaIdType from); boolean canConvertAny(Set<MediaIdType> from, Set<MediaIdType> to)... |
### Question:
InfoProvider { public boolean canConvertAny(Set<MediaIdType> from, Set<MediaIdType> to) { return from.stream().anyMatch(x -> canConvertMap.containsKey(x) && canConvertMap.get(x).stream().anyMatch(to::contains)); } boolean canConvert(MediaIdType from, MediaIdType to); static Set<MediaIdType> getConvertibl... |
### Question:
InfoProvider { public MediaInfo convert(Map<MediaIdType, String> identifiers) throws InfoProviderException { for (MediaIdType idType : REAL_ID_TYPES) { if (identifiers.containsKey(idType) && identifiers.get(idType) != null) { return convert(identifiers.get(idType), idType); } } throw new InfoProviderExcep... |
### Question:
InfoProvider { @Cacheable(cacheNames = "titles", sync = true) public List<MediaInfo> search(String title, MediaIdType titleType) throws InfoProviderException { try { List<MediaInfo> infos; switch (titleType) { case TVTITLE: { List<TvMazeSearchResult> results = tvMazeHandler.search(title); infos = results.... |
### Question:
InfoProvider { public TvInfo findTvInfoInDatabase(Map<MediaIdType, String> ids) { Collection<TvInfo> matchingInfos = tvInfoRepository.findByTvrageIdOrTvmazeIdOrTvdbIdOrImdbId(ids.getOrDefault(TVRAGE, "-1"), ids.getOrDefault(TVMAZE, "-1"), ids.getOrDefault(TVDB, "-1"), ids.getOrDefault(IMDB, "-1")); return... |
### Question:
TmdbHandler { public TmdbSearchResult getInfos(String value, MediaIdType idType) throws InfoProviderException { if (idType == MediaIdType.MOVIETITLE) { return fromTitle(value, null); } if (idType == MediaIdType.IMDB) { return fromImdb(value); } if (idType == MediaIdType.TMDB) { return fromTmdb(value); } t... |
### Question:
TmdbHandler { TmdbSearchResult fromTitle(String title, Integer year) throws InfoProviderException { Movie movie = getMovieByTitle(title, year); TmdbSearchResult result = getSearchResultFromMovie(movie); return result; } TmdbSearchResult getInfos(String value, MediaIdType idType); List<TmdbSearchResult> s... |
### Question:
HydraOkHttp3ClientHttpRequestFactory implements ClientHttpRequestFactory, AsyncClientHttpRequestFactory { protected boolean isUriToBeIgnoredByProxy(String host) { MainConfig mainConfig = configProvider.getBaseConfig().getMain(); if (mainConfig.isProxyIgnoreLocal()) { Boolean ipToLong = isHostInLocalNetwor... |
### Question:
HydraOkHttp3ClientHttpRequestFactory implements ClientHttpRequestFactory, AsyncClientHttpRequestFactory { public Builder getOkHttpClientBuilder(URI requestUri) { Builder builder = getBaseBuilder(); configureBuilderForSsl(requestUri, builder); MainConfig main = configProvider.getBaseConfig().getMain(); if ... |
### Question:
UpdateManager implements InitializingBean { public boolean isUpdateAvailable() { try { return getLatestVersion().isUpdateFor(currentVersion) && !latestVersionIgnored() && !latestVersionBlocked() && latestVersionFinalOrPreEnabled(); } catch (UpdateException e) { logger.error("Error while checking if new ve... |
### Question:
UpdateManager implements InitializingBean { public String getLatestVersionString() throws UpdateException { return getLatestVersion().toString(); } UpdateManager(); boolean isUpdateAvailable(); boolean latestVersionFinalOrPreEnabled(); boolean latestVersionIgnored(); boolean latestVersionBlocked(); String... |
### Question:
IndexerForSearchSelector { LocalDateTime calculateNextPossibleHit(IndexerConfig indexerConfig, Instant firstInWindowAccessTime) { LocalDateTime nextPossibleHit; if (indexerConfig.getHitLimitResetTime().isPresent()) { LocalDateTime now = LocalDateTime.now(clock); nextPossibleHit = now.with(ChronoField.HOUR... |
### Question:
IndexerForSearchSelector { protected boolean checkTorznabOnlyUsedForTorrentOrInternalSearches(Indexer indexer) { if (searchRequest.getDownloadType() == DownloadType.TORRENT && indexer.getConfig().getSearchModuleType() != SearchModuleType.TORZNAB) { String message = String.format("Not using %s because a to... |
### Question:
CategoryProvider implements InitializingBean { public Category fromSearchNewznabCategories(String cats) { if (StringUtils.isEmpty(cats)) { return getNotAvailable(); } try { return fromSearchNewznabCategories(Arrays.stream(cats.split(",")).map(Integer::valueOf).collect(Collectors.toList()), getNotAvailable... |
### Question:
CategoryProvider implements InitializingBean { public Category fromResultNewznabCategories(List<Integer> cats) { if (cats == null || cats.size() == 0) { return naCategory; } cats.sort((o1, o2) -> Integer.compare(o2, o1)); return getMatchingCategoryOrMatchingMainCategory(cats, naCategory); } CategoryProvid... |
### Question:
CategoryProvider implements InitializingBean { public static boolean checkCategoryMatchingMainCategory(int cat, int possibleMainCat) { return possibleMainCat % 1000 == 0 && cat / 1000 == possibleMainCat / 1000; } CategoryProvider(); @Override void afterPropertiesSet(); @org.springframework.context.event.E... |
### Question:
CategoryProvider implements InitializingBean { public Optional<Category> fromSubtype(Subtype subtype) { return categories.stream().filter(x -> x.getSubtype() == subtype).findFirst(); } CategoryProvider(); @Override void afterPropertiesSet(); @org.springframework.context.event.EventListener void handleNewC... |
### Question:
NewznabParameters { @Override public int hashCode() { return Objects.hashCode(apikey, t, q, cat, rid, tvdbid, tvmazeid, traktId, imdbid, tmdbid, season, ep, author, title, offset, limit, minage, maxage, minsize, maxsize, id, raw, o, cachetime, genre, attrs, extended, password); } @Override String toStrin... |
### Question:
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... |
### Question:
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"); ... |
### Question:
DownloadStatusUpdater { @EventListener public void onNzbDownloadEvent(FileDownloadEvent downloadEvent) { if (!configProvider.getBaseConfig().getMain().isKeepHistory()) { return; } lastDownload = Instant.now(); queueCheckEnabled = true; historyCheckEnabled = true; logger.debug(LoggingMarkers.DOWNLOAD_STATU... |
### Question:
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); RssItemB... |
### Question:
DownloaderStatus { public List<Long> getDownloadingRatesInKilobytes() { if (downloadingRatesInKilobytes.isEmpty() || downloadingRatesInKilobytes.size() < 5) { return downloadingRatesInKilobytes; } if (downloadingRatesInKilobytes.get(downloadingRatesInKilobytes.size() - 1) / (float) 10 > downloadingRatesIn... |
### Question:
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(fals... |
### Question:
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... |
### Question:
IndexerForSearchSelector { protected boolean checkIndexerSelectedByUser(Indexer indexer) { boolean indexerNotSelectedByUser = (searchRequest.getIndexers().isPresent() && !searchRequest.getIndexers().get().isEmpty()) && !searchRequest.getIndexers().get().contains(indexer.getName()); if (indexerNotSelectedB... |
### Question:
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 convertToDa... |
### Question:
CategoryConverter implements AttributeConverter<Category, String> { @Override public Category convertToEntityAttribute(String categoryName) { return categoryProvider.getByInternalName(categoryName); } @Autowired void setCategoryProvider(CategoryProvider categoryProvider); @Override String convertToDataba... |
### Question:
NewznabXmlTransformer { NewznabXmlItem buildRssItem(SearchResultItem searchResultItem, boolean isNzb) { NewznabXmlItem rssItem = new NewznabXmlItem(); String link = nzbHandler.getDownloadLinkForResults(searchResultItem.getSearchResultId(), false, isNzb ? DownloadType.NZB : DownloadType.TORRENT); rssItem.s... |
### Question:
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.instan... |
### Question:
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 " + foundConfigVer... |
### Question:
ConfigMigration { protected static List<ConfigMigrationStep> getMigrationSteps() { ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); provider.addIncludeFilter(new AssignableTypeFilter(ConfigMigrationStep.class)); Set<BeanDefinition> candidates =... |
### Question:
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")... |
### Question:
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(... |
### Question:
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(show... |
### Question:
IndexerForSearchSelector { protected boolean checkDisabledForCategory(Indexer indexer) { if (searchRequest.getCategory().getSubtype().equals(Subtype.ALL)) { return true; } boolean indexerDisabledForThisCategory = !indexer.getConfig().getEnabledCategories().isEmpty() && !indexer.getConfig().getEnabledCateg... |
### Question:
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.par... |
### Question:
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").s... |
### Question:
Binsearch extends Indexer<String> { @Override protected UriComponentsBuilder buildSearchUrl(SearchRequest searchRequest, Integer offset, Integer limit) throws IndexerSearchAbortedException { String query = super.generateQueryIfApplicable(searchRequest, ""); query = addRequiredWordsToQuery(searchRequest, q... |
### Question:
IndexerForSearchSelector { protected boolean checkLoadLimiting(Indexer indexer) { boolean preventedByLoadLimiting = indexer.getConfig().getLoadLimitOnRandom().isPresent() && random.nextInt(indexer.getConfig().getLoadLimitOnRandom().get()) + 1 != 1; if (preventedByLoadLimiting) { boolean loadLimitIgnored =... |
### Question:
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(() -> getAndStor... |
### Question:
Indexer { @Transactional protected List<SearchResultItem> persistSearchResults(List<SearchResultItem> searchResultItems, IndexerSearchResult indexerSearchResult) { Stopwatch stopwatch = Stopwatch.createStarted(); synchronized (dbLock) { ArrayList<SearchResultEntity> searchResultEntities = new ArrayList<>(... |
### Question:
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(... |
### Question:
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 t... |
### Question:
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 (removeT... |
### Question:
Torznab extends Newznab { @Override protected UriComponentsBuilder buildSearchUrl(SearchRequest searchRequest, Integer offset, Integer limit) throws IndexerSearchAbortedException { return super.buildSearchUrl(searchRequest, null, null); } }### Answer:
@Test public void shouldNotAddExcludedWordsToQuery(... |
### Question:
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.addA... |
### Question:
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... |
### Question:
Anizb extends Indexer<NewznabXmlRoot> { @Override protected UriComponentsBuilder buildSearchUrl(SearchRequest searchRequest, Integer offset, Integer limit) throws IndexerSearchAbortedException { String query = super.generateQueryIfApplicable(searchRequest, ""); query = addRequiredWordsToQuery(searchReques... |
### Question:
NzbsOrg extends Newznab { protected String addForbiddenWords(SearchRequest searchRequest, String query) { List<String> allForbiddenWords = new ArrayList<>(searchRequest.getInternalData().getForbiddenWords()); allForbiddenWords.addAll(configProvider.getBaseConfig().getSearching().getForbiddenWords()); allF... |
### Question:
NzbsOrg extends Newznab { protected String addRequiredWords(SearchRequest searchRequest, String query) { List<String> allRequiredWords = new ArrayList<>(searchRequest.getInternalData().getRequiredWords()); allRequiredWords.addAll(configProvider.getBaseConfig().getSearching().getRequiredWords()); allRequir... |
### Question:
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();... |
### Question:
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, new... |
### Question:
IndexerForSearchSelector { protected boolean checkSearchId(Indexer indexer) { boolean needToSearchById = !searchRequest.getIdentifiers().isEmpty() && !searchRequest.getQuery().isPresent(); if (needToSearchById) { boolean canUseAnyProvidedId = !Collections.disjoint(searchRequest.getIdentifiers().keySet(), ... |
### Question:
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) respo... |
### Question:
CurrentTenantHolder { public static String pop() { return getCurrentStack().pop(); } static void push(String tenantId); static String pop(); static String getCurrentTenant(); }### Answer:
@Test(expected = EmptyStackException.class) public void testEmptyHolderPop() { CurrentTenantHolder.pop(); } |
### Question:
CurrentTenantHolder { public static String getCurrentTenant() { return getCurrentStack().peek(); } static void push(String tenantId); static String pop(); static String getCurrentTenant(); }### Answer:
@Test(expected = EmptyStackException.class) public void testEmptyHolderPeek() { CurrentTenantHolder.ge... |
### Question:
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)) { jo... |
### Question:
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] ... |
### Question:
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))... |
### Question:
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("_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.