method2testcases
stringlengths
118
6.63k
### Question: PersistNotificationHandler { @EventListener @Transactional(propagation = REQUIRES_NEW) public void handle(final RequestFundedNotificationDto notification) { notificationRepository.save(requestFundedNotificationMapper.map(notification)); } PersistNotificationHandler(final NotificationRepository notificatio...
### Question: PublicEnvironmentEndpoint extends AbstractEndpoint<Map<String, Object>> { @Override public Map<String, Object> invoke() { return filterOutNonPublicProperties(environmentEndpoint.invoke()); } PublicEnvironmentEndpoint(final EnvironmentEndpoint environmentEndpoint, @Valu...
### Question: MessagesController extends AbstractController { @PostMapping("/messages/{type}/add") public ModelAndView add(WebRequest request, @PathVariable String type, RedirectAttributes redirectAttributes) { MessageDto messageDto = MessageDto.builder() .name(request.getParameter("name")) .type(MessageType.valueOf(ty...
### Question: ThymeleafSvgConfig implements ApplicationContextAware { @Bean public ITemplateResolver svgTemplateResolver() { final SpringResourceTemplateResolver svgTemplateResolver = new SpringResourceTemplateResolver(); svgTemplateResolver.setApplicationContext(applicationContext); svgTemplateResolver.setPrefix("clas...
### Question: ThymeleafSvgConfig implements ApplicationContextAware { @Bean public ThymeleafViewResolver svgViewResolver(final SpringTemplateEngine templateEngine) { final ThymeleafViewResolver thymeleafViewResolver = new ThymeleafViewResolver(); thymeleafViewResolver.setTemplateEngine(templateEngine); thymeleafViewRes...
### Question: ProfileController { @GetMapping("/profile") public ModelAndView showProfile(Principal principal) throws Exception { final ModelAndView mav = new ModelAndView("pages/profile/index"); mav.addObject("isVerifiedGithub", isVerifiedGithub(principal)); mav.addObject("isVerifiedStackOverflow", isVerifiedStackOver...
### Question: ProfileController { @GetMapping("/profile/managewallets") public ModelAndView manageWallets(Principal principal, HttpServletRequest request) throws UnsupportedEncodingException { String bearerToken = URLEncoder.encode(profileService.getArkaneAccessToken((KeycloakAuthenticationToken) principal), "UTF-8"); ...
### Question: ProfileController { @PostMapping("/profile/headline") public ModelAndView updateHeadline(Principal principal, @RequestParam("headline") String headline) { profileService.updateHeadline(principal, headline); return redirectToProfile(); } ProfileController(final ApplicationEventPublisher eventPublisher, ...
### Question: FundrequestExpressionObjectFactory implements IExpressionObjectFactory { @Override public Set<String> getAllExpressionObjectNames() { return expressionObjectsMap.keySet(); } FundrequestExpressionObjectFactory(final Map<String, Object> expressionObjectsMap); @Override Set<String> getAllExpressionObjectName...
### Question: FundrequestDialect extends AbstractDialect implements IExpressionObjectDialect { @Override public IExpressionObjectFactory getExpressionObjectFactory() { return fundrequestExpressionObjectFactory; } FundrequestDialect(final IExpressionObjectFactory fundrequestExpressionObjectFactory); @Override IExpressio...
### Question: ProfilesExpressionObject { public Optional<UserProfile> findByUserId(final String userId) { try { return StringUtils.isBlank(userId) ? Optional.empty() : Optional.ofNullable(profileService.getNonLoggedInUserProfile(userId)); } catch (Exception e) { LOGGER.error("Error getting profile for: \"" + userId + "...
### Question: MessagesController extends AbstractController { @PostMapping("/messages/{type}/{name}/edit") public ModelAndView update(WebRequest request, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes) { MessageDto messageDto = MessageDto.builder() .name(name) .type(MessageT...
### Question: ProfilesExpressionObject { public Function<UserProfile, String> getName() { return UserProfile::getName; } ProfilesExpressionObject(final ProfileService profileService); Optional<UserProfile> findByUserId(final String userId); Function<UserProfile, String> getName(); }### Answer: @Test public void getNam...
### Question: HomeController extends AbstractController { @RequestMapping("/") public ModelAndView home(@RequestParam(value = "ref", required = false) String ref, RedirectAttributes redirectAttributes, Principal principal) { final List<RequestView> requests = mappers.mapList(RequestDto.class, RequestView.class, request...
### Question: HomeController extends AbstractController { @RequestMapping("/user/login") public ModelAndView login(RedirectAttributes redirectAttributes, HttpServletRequest request) { return redirectView(redirectAttributes) .url(request.getHeader("referer")) .build(); } HomeController(ProfileService profileService, ...
### Question: HomeController extends AbstractController { @GetMapping(path = "/logout") public String logout(Principal principal, HttpServletRequest request) throws ServletException { if (principal != null) { profileService.logout(principal); } request.logout(); return "redirect:/"; } HomeController(ProfileService prof...
### Question: RequestDetailsViewMapperDecorator implements RequestDetailsViewMapper { @Override public RequestDetailsView map(RequestDto r) { RequestDetailsView view = delegate.map(r); if (view != null) { IssueInformationDto issueInfo = r.getIssueInformation(); view.setIcon("https: view.setPlatform(issueInfo.getPlatfor...
### Question: RequestViewMapper implements BaseMapper<RequestDto, RequestView> { @Override public RequestView map(final RequestDto r) { if (r == null) { return null; } return RequestView.builder() .id(r.getId()) .icon("https: .owner(r.getIssueInformation().getOwner()) .repo(r.getIssueInformation().getRepo()) .issueNumb...
### Question: MessagesController extends AbstractController { @PostMapping("/messages/{type}/{name}/delete") public ModelAndView delete(final Model model, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes) { messageService.delete(MessageType.valueOf(type.toUpperCase()), name); ...
### Question: UserResourceTemplate implements UserResource { @Override public Me me() { return restTemplate.getForObject("https: } UserResourceTemplate(final RestTemplate restTemplate); @Override Me me(); }### Answer: @Test void me() { mockServer.expect(requestTo("https: .andExpect(method(GET)) .andRespond(withSuccess...
### Question: RequestController extends AbstractController { @GetMapping("/requests/{id}/actions") public ModelAndView detailActions(final Principal principal, @PathVariable final Long id) { final RequestDto request = requestService.findRequest(id); if (request != null) { final IssueInformationDto issueInformation = re...
### Question: RequestController extends AbstractController { @PostMapping("/requests/{id}/claim") public ModelAndView claimRequest(Principal principal, @PathVariable Long id, @Valid UserClaimRequest userClaimRequest, RedirectAttributes redirectAttributes) { if (!profileService.getUserProfile(principal).userOwnsAddress(...
### Question: RequestController extends AbstractController { @PostMapping(value = {"/requests/{id}/watch"}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public String toggleWatchRequest(Principal principal, @PathVariable Long id) { RequestDto request = requestService.findRequest(id); if (request.isLo...
### Question: RequestRestController { @GetMapping(value = "/github/{owner}/{repo}/{number}") public RequestView requestDetails(@PathVariable("owner") final String repoOwner, @PathVariable("repo") final String repo, @PathVariable("number") final String issueNumber) { final RequestDto request = requestService.findRequest...
### Question: RequestRestController { @GetMapping(value = "/github/{owner}/{repo}/{number}/claimable") public ClaimView claimDetails(@PathVariable("owner") final String repoOwner, @PathVariable("repo") final String repo, @PathVariable("number") final String issueNumber) { final RequestDto request = requestService.findR...
### Question: RequestVacuumer { @Scheduled(fixedDelay = 300_000L) public void cleanClaims() { final List<RequestClaim> claims = requestClaimRepository.findByStatus(ClaimRequestStatus.APPROVED); claims.stream() .filter(x -> x.getTransactionHash() != null) .filter(x -> azraelClient.getTransactionStatus(x.getTransactionHa...
### Question: FundController extends AbstractController { @PostMapping(value = "/requests/{requestId}/refunds") public ModelAndView requestRefund(final Principal principal, @PathVariable("requestId") final Long requestId, @RequestParam("funder_address") final String funderAddress, final RedirectAttributes redirectAttri...
### Question: GithubScraper { @Cacheable("github_issues") public GithubIssue fetchGithubIssue(final String owner, final String repo, final String number) { Document document; try { document = jsoup.connect("https: } catch (IOException e) { throw new RuntimeException(e); } return GithubIssue.builder() .owner(owner) .rep...
### Question: GithubStatusResolver { public String resolve(final Document document) { return document.select("#partial-discussion-header .State").first().text(); } String resolve(final Document document); }### Answer: @Test public void parseOpen() { final Document document = mock(Document.class, RETURNS_DEEP_STUBS); ...
### Question: GithubId { public static Optional<GithubId> fromString(final String githubIdAsString) { final Pattern pattern = Pattern.compile("^.*/(?<owner>.+)/(?<repo>.+)/.+/(?<number>\\d+)$"); final Matcher matcher = pattern.matcher(githubIdAsString); if (matcher.matches()) { return Optional.of(GithubId.builder() .ow...
### Question: RequestVacuumer { @Scheduled(fixedDelay = 300_000L) public void cleanRefunds() { final List<RefundRequest> refundRequests = refundRequestRepository.findAllByStatus(RefundRequestStatus.APPROVED); refundRequests.stream() .filter(refundRequest -> refundRequest.getTransactionHash() != null) .filter(refundRequ...
### Question: GithubId { public static Optional<GithubId> fromPlatformId(final String platformId) { final Pattern pattern = Pattern.compile("^(?<owner>.+)\\|FR\\|(?<repo>.+)\\|FR\\|(?<number>\\d+)$"); final Matcher matcher = pattern.matcher(platformId); if (matcher.matches()) { return Optional.of(GithubId.builder() .ow...
### Question: GithubSolverResolver { public Optional<String> resolve(final Document document, final GithubId issueGithubId) { return document.select(".TimelineItem") .stream() .filter(this::isPullRequest) .filter(this::isMerged) .map(this::resolvePullRequestGithubId) .map(this::fetchPullrequest) .filter(pullRequest -> ...
### Question: GithubTemplateResource implements ITemplateResource { @Override public String getDescription() { return String.format("%s/%s/%s/%s", owner, repo, branch, location); } GithubTemplateResource(final String owner, final String repo, final String branch, final String location, final GithubRawClient githubRawCl...
### Question: GithubTemplateResource implements ITemplateResource { @Override public String getBaseName() { return location; } GithubTemplateResource(final String owner, final String repo, final String branch, final String location, final GithubRawClient githubRawClient); @Override String getDescription(); @Override St...
### Question: GithubTemplateResource implements ITemplateResource { @Override public boolean exists() { return StringUtils.isNotBlank(fetchTemplateContents()); } GithubTemplateResource(final String owner, final String repo, final String branch, final String location, final GithubRawClient githubRawClient); @Override St...
### Question: GithubTemplateResource implements ITemplateResource { @Override public Reader reader() { final String templateContents = fetchTemplateContents(); return StringUtils.isNotBlank(templateContents) ? new StringReader(templateContents) : null; } GithubTemplateResource(final String owner, final String repo, fin...
### Question: GithubTemplateResource implements ITemplateResource { @Override public GithubTemplateResource relative(String relativeLocation) { return new GithubTemplateResource(owner, repo, branch, relativeLocation, githubRawClient); } GithubTemplateResource(final String owner, final String repo, final String branch, ...
### Question: OpenRequestsNotificationsController extends AbstractController { @GetMapping("/notifications/open-requests") public ModelAndView showGenerateTemplateForm(final Model model) { return modelAndView(model).withView("notifications/open-requests") .withObject("projects", requestService.findAllProjects()) .withO...
### Question: GithubRateHealthCheck implements HealthIndicator { @Override public Health health() { final GithubRateLimit rateLimit = githubGateway.getRateLimit().getCore(); if (rateLimit.getRemaining() == 0) { return addDetails(Health.down(), rateLimit).build(); } if (rateLimit.getRemaining() > calculateThreshold(rate...
### Question: GithubCommentFactory { public String createFundedComment(final Long requestId, final String githubIssueNumber) { return String.format(FUNDED_COMMENT_TEMPLATE, platformBasePath, requestId, githubIssueNumber); } GithubCommentFactory(@Value("${io.fundrequest.platform.base-path}") final String platformBasePat...
### Question: GithubCommentFactory { public String createResolvedComment(final Long requestId, final String solver) { return String.format(RESOLVED_COMMENT_TEMPLATE, platformBasePath, requestId, solver); } GithubCommentFactory(@Value("${io.fundrequest.platform.base-path}") final String platformBasePath, ...
### Question: GithubCommentFactory { public String createClosedComment(final Long requestId, final String solver, final String transactionHash) { return String.format(CLOSED_COMMENT_TEMPLATE, platformBasePath, requestId, solver, etherscanBasePath, transactionHash); } GithubCommentFactory(@Value("${io.fundrequest.platfo...
### Question: GithubIssueService { public Optional<GithubIssue> findBy(final String platformId) { return GithubId.fromPlatformId(platformId) .map(githubId -> githubScraper.fetchGithubIssue(githubId.getOwner(), githubId.getRepo(), githubId.getNumber())); } GithubIssueService(final GithubScraper githubScraper); Optional<...
### Question: EmptyFAQServiceImpl implements FAQService { public FaqItemsDto getFAQsForPage(final String pageName) { return new FaqItemsDto(DUMMY_FAQS_SUBTITLE, DUMMY_FAQ_ITEMS); } EmptyFAQServiceImpl(); FaqItemsDto getFAQsForPage(final String pageName); }### Answer: @Test void getFAQsForPage() { assertThat(new EmptyF...
### Question: KeycloakRepositoryImpl implements KeycloakRepository { public Stream<UserIdentity> getUserIdentities(String userId) { return resource.users().get(userId).getFederatedIdentity() .stream() .map(fi -> UserIdentity.builder().provider(Provider.fromString(fi.getIdentityProvider())).username(fi.getUserName()).us...
### Question: ReferralServiceImpl implements ReferralService { @Override @Transactional public void createNewRef(CreateRefCommand command) { String referrer = command.getRef(); String referee = command.getPrincipal().getName(); validReferral(referrer, referee); if (!repository.existsByReferee(referee)) { Referral refer...
### Question: UserProfile { public boolean userOwnsAddress(String address) { return getEtherAddresses().stream().anyMatch(x -> x.equalsIgnoreCase(address)); } boolean userOwnsAddress(String address); boolean hasEtherAddress(); }### Answer: @Test void userOwnsAddress() { Wallet wallet = WalletMother.aWallet(); UserPro...
### Question: BountyServiceImpl implements BountyService { @Override @Transactional(readOnly = true) public List<PaidBountyDto> getPaidBounties(Principal principal) { return bountyRepository.findByUserId(principal.getName()) .stream() .filter(f -> StringUtils.isNotBlank(f.getTransactionHash())) .sorted(Comparator.compa...
### Question: GithubBountyServiceImpl implements GithubBountyService, ApplicationListener<AuthenticationSuccessEvent> { @Override @Transactional public void onApplicationEvent(AuthenticationSuccessEvent event) { Authentication principal = event.getAuthentication(); UserProfile userProfile = profileService.getUserProfil...
### Question: GithubBountyServiceImpl implements GithubBountyService, ApplicationListener<AuthenticationSuccessEvent> { @EventListener @Transactional public void onProviderLinked(UserLinkedProviderEvent event) { if (event.getProvider() == Provider.GITHUB && event.getPrincipal() != null) { UserProfile userProfile = prof...
### Question: EnumToCapitalizedStringMapper implements BaseMapper<Enum, String> { @Override public String map(final Enum anEnum) { if (anEnum == null) { return null; } return WordUtils.capitalizeFully(anEnum.name().replace('_', ' ')); } @Override String map(final Enum anEnum); }### Answer: @Test void map() { assertTh...
### Question: UserServiceImpl implements UserService { @Override @Transactional(readOnly = true) public UserDto getUser(String email) { return userDtoMapper.map( userRepository.findOne(email).orElse(null) ); } UserServiceImpl(UserRepository userRepository, UserDtoMapper userDtoMapper); @Override @Transactional(readOnly...
### Question: PlatformIssueServiceImpl implements PlatformIssueService { @Override public Optional<PlatformIssueDto> findBy(final Platform platform, final String platformId) { if (Platform.GITHUB == platform) { return githubIssueService.findBy(platformId) .map(githubIssue -> mappers.map(GithubIssue.class, PlatformIssue...
### Question: GithubIssueToPlatformIssueDtoMapper implements BaseMapper<GithubIssue, PlatformIssueDto> { @Override public PlatformIssueDto map(final GithubIssue githubIssue) { return PlatformIssueDto.builder() .platform(GITHUB) .platformId(buildPlatformId(githubIssue)) .status(isClosed(githubIssue) ? CLOSED : OPEN) .bu...
### Question: MessageServiceImpl implements MessageService { @Transactional(readOnly = true) @Override public List<MessageDto> getMessagesByType(MessageType type) { return repository.findByType(type, new Sort(Sort.Direction.DESC, "name")) .stream() .parallel() .map(m -> objectMapper.convertValue(m, MessageDto.class)) ....
### Question: MessageServiceImpl implements MessageService { @Override public MessageDto getMessageByKey(String key) { int indexSeperator = key.indexOf('.'); if (indexSeperator > 0) { String type = key.substring(0, indexSeperator); String name = key.substring(indexSeperator + 1); return getMessageByTypeAndName(MessageT...
### Question: MessageServiceImpl implements MessageService { @Override public MessageDto getMessageByTypeAndName(MessageType type, String name) { Message m = repository.findByTypeAndName(type, name).orElseThrow(() -> new RuntimeException("Message not found")); return objectMapper.convertValue(m, MessageDto.class); } Me...
### Question: MessageServiceImpl implements MessageService { @Transactional @Override public Message update(MessageDto messageDto) { Message m = repository.findByTypeAndName(messageDto.getType(), messageDto.getName()).orElseThrow(() -> new RuntimeException("Message not found")); messageDto.setId(m.getId()); Message new...
### Question: MessageServiceImpl implements MessageService { @Transactional @Override public Message add(MessageDto messageDto) { int minlength = 3; if (messageDto.getName().length() < 3) { throw new RuntimeException(String.format("Message name should be at least %s characters long", minlength)); } if (repository.findB...
### Question: MessageServiceImpl implements MessageService { @Transactional @Override public void delete(MessageType type, String name) { repository.deleteByTypeAndName(type, name); } MessageServiceImpl(MessageRepository repository, ObjectMapper objectMapper); @Transactional(readOnly = true) @Override List<MessageDto> ...
### Question: TokenValueMapper { public TokenValueDto map(final String tokenAddress, final BigDecimal rawBalance) { final TokenInfoDto tokenInfo = tokenInfoService.getTokenInfo(tokenAddress); return tokenInfo == null ? null : TokenValueDto.builder() .tokenAddress(tokenInfo.getAddress()) .tokenSymbol(tokenInfo.getSymbol...
### Question: KeycloakRepositoryImpl implements KeycloakRepository { @Override public boolean isEtherAddressVerified(final UserRepresentation userRepresentation) { return "true".equalsIgnoreCase(getAttribute(userRepresentation, ETHER_ADDRESS_VERIFIED_KEY)); } KeycloakRepositoryImpl(RealmResource resource, @Value("${key...
### Question: SecurityContextServiceImpl implements SecurityContextService { @Override public Optional<Authentication> getLoggedInUser() { return Optional.ofNullable(securityContextHolder.getContext().getAuthentication()); } SecurityContextServiceImpl(final SecurityContextHolderSpringDelegate securityContextHolder, fin...
### Question: SecurityContextServiceImpl implements SecurityContextService { @Override public boolean isUserFullyAuthenticated() { return isUserFullyAuthenticated(securityContextHolder.getContext().getAuthentication()); } SecurityContextServiceImpl(final SecurityContextHolderSpringDelegate securityContextHolder, final ...
### Question: SecurityContextServiceImpl implements SecurityContextService { @Override public Optional<UserProfile> getLoggedInUserProfile() { return getLoggedInUser().filter(this::isUserFullyAuthenticated) .map(authentication -> (Principal) authentication.getPrincipal()) .map(profileService::getUserProfile); } Securit...
### Question: GithubLinkValidator implements ConstraintValidator<GithubLink, String> { public boolean isValid(String link, ConstraintValidatorContext context) { return StringUtils.isEmpty(link) || link.matches(regex); } GithubLinkValidator(); void initialize(GithubLink constraint); boolean isValid(String link, Constrai...
### Question: RequestClaimDtoDecorator implements RequestClaimDtoMapper { @Override public RequestClaimDto map(RequestClaim r) { RequestClaimDto dto = delegate.map(r); if (dto != null) { RequestDto request = requestService.findRequest(r.getRequestId()); dto.setUrl(createLink(request.getIssueInformation())); dto.setTitl...
### Question: ClaimDtoMapperDecorator implements ClaimDtoMapper { @Override public ClaimDto map(Claim r) { final ClaimDto dto = delegate.map(r); if (dto != null) { dto.setTransactionHash(blockchainEventService.findOne(r.getBlockchainEventId()) .map(BlockchainEventDto::getTransactionHash) .orElse("")); } return dto; } ...
### Question: ClaimServiceImpl implements ClaimService { @Override @Transactional(readOnly = true) public Optional<ClaimDto> findOne(final Long id) { return claimRepository.findOne(id).map(claim -> mappers.map(Claim.class, ClaimDto.class, claim)); } ClaimServiceImpl(final RequestRepository requestRepository, ...
### Question: ClaimServiceImpl implements ClaimService { @Transactional @Override public void claim(Principal user, UserClaimRequest userClaimRequest) { Request request = requestRepository.findByPlatformAndPlatformId(userClaimRequest.getPlatform(), userClaimRequest.getPlatformId()) .orElseThrow(() -> new RuntimeExcepti...
### Question: ClaimServiceImpl implements ClaimService { @Override @Transactional(readOnly = true) public ClaimsByTransactionAggregate getAggregatedClaimsForRequest(final long requestId) { return claimDtoAggregator.aggregateClaims(mappers.mapList(Claim.class, ClaimDto.class, claimRepository.findByRequestId(requestId)))...
### Question: ClaimServiceImpl implements ClaimService { @EventListener public void onClaimed(final RequestClaimedEvent claimedEvent) { requestClaimRepository.findByRequestId(claimedEvent.getRequestDto().getId()) .forEach(requestClaim -> { requestClaim.setStatus(ClaimRequestStatus.PROCESSED); requestClaimRepository.sav...
### Question: ClaimDtoAggregator { ClaimsByTransactionAggregate aggregateClaims(final List<ClaimDto> claims) { TokenValueDto totalFndValue = null; TokenValueDto totalOtherValue = null; final Map<String, ClaimByTransactionAggregate.Builder> claimsPerTransaction = new HashMap<>(); for (final ClaimDto claim : claims) { fi...
### Question: CreateGithubCommentOnResolvedHandler { @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) public void createGithubCommentOnRequestClaimable(final RequestClaimableEvent event) { if (addComment) { final RequestDto request = event.getRequestDto(); final IssueInformationDto issueInformation = ...
### Question: GitterService { @Cacheable("gitter_fund_notification_rooms") public List<String> listFundedNotificationRooms() { try { final String roomsRaw = githubRawClient.getContentsAsRaw("FundRequest", "content-management", branch, filePath); final GitterRooms gitterRooms = objectMapper.readValue(roomsRaw, GitterRoo...
### Question: KafkaMetricsSet implements MetricSet { public Boolean connectionToKafkaTopicsIsSuccess() { if (nonNull(metricTopics) && nonNull(connectionTimeoutTopic)) { StopWatch executionTime = StopWatch.createStarted(); DescribeTopicsOptions describeTopicsOptions = new DescribeTopicsOptions().timeoutMs( connectionTim...
### Question: TenantConfigService implements RefreshableConfiguration { @IgnoreLogginAspect public Map<String, Object> getConfig() { return getTenantConfig(); } TenantConfigService(XmConfigProperties xmConfigProperties, TenantContextHolder tenantContextHolder); @IgnoreLogginAspect Map<Str...
### Question: AnnotatedFieldProcessor { static <X> void ensureNoConflictingAnnotationsPresentOn(final Class<X> type) throws ResolutionException { final Set<Field> fieldsHavingConflictingAnnotations = new HashSet<Field>(); for (final Field fieldToInspect : allFieldsAndSuperclassFieldsIn(type)) { if (isAnnotatedWithOneOf...
### Question: AnnotatedFieldProcessor { static <X> boolean hasCamelInjectAnnotatedFields(final Class<X> type) { return !camelInjectAnnotatedFieldsIn(type).isEmpty(); } }### Answer: @Test public final void assertThatHasCamelInjectAnnotatedFieldsRecognizesThatNoCamelInjectAnnotationIsPresentOnAnyField() { final boolea...
### Question: AnnotatedFieldProcessor { static <X> Set<Field> camelInjectAnnotatedFieldsIn(final Class<X> type) { final Set<Field> camelInjectAnnotatedFields = new HashSet<Field>(); for (final Field fieldToInspect : allFieldsAndSuperclassFieldsIn(type)) { if (isAnnotatedWithOneOf(fieldToInspect, CAMEL)) { camelInjectAn...
### Question: LazyModuleLoader { public synchronized SupportFragmentLike loadSupportFragmentModule( Fragment hostingFragment, String moduleName, String className) throws LazyLoadingException { try { Class lazyLoadedClass = mLoaderAlgorithm.loadModule(moduleName, className); Constructor c = lazyLoadedClass.getConstructo...
### Question: LazyModuleLoader { public synchronized FragmentLike loadFragmentModule( android.app.Fragment hostingFragment, String moduleName, String className) throws LazyLoadingException { try { Class lazyLoadedClass = mLoaderAlgorithm.loadModule(moduleName, className); Constructor c = lazyLoadedClass.getConstructor(...
### Question: LazyModuleLoader { public synchronized ServiceLike loadServiceModule(String moduleName, String className) throws LazyLoadingException { try { Class lazyLoadedClass = mLoaderAlgorithm.loadModule(moduleName, className); Constructor c = lazyLoadedClass.getConstructor(Context.class); ServiceLike serviceLike =...
### Question: LazyModuleLoader { public synchronized ActivityLike loadActivityModule( Activity activity, String moduleName, String className) throws LazyLoadingException { try { Class lazyLoadedClass = mLoaderAlgorithm.loadModule(moduleName, className); Constructor c = lazyLoadedClass.getConstructor(Activity.class); Ac...
### Question: FilteredGuacamoleWriter implements GuacamoleWriter { @Override public void write(char[] chunk, int offset, int length) throws GuacamoleException { while (length > 0) { int parsed; while ((parsed = parser.append(chunk, offset, length)) != 0) { offset += parsed; length -= parsed; } if (!parser.hasNext()) th...
### Question: QCParser { public static GuacamoleConfiguration getConfiguration(String uri) throws GuacamoleException { URI qcUri; try { qcUri = new URI(uri); if (!qcUri.isAbsolute()) throw new TranslatableGuacamoleClientException("URI must be absolute.", "QUICKCONNECT.ERROR_NOT_ABSOLUTE_URI"); } catch (URISyntaxExcepti...
### Question: EnumGuacamoleProperty implements GuacamoleProperty<T> { @Override public T parseValue(String value) throws GuacamoleException { if (value == null) return null; T parsedValue = valueMapping.get(value); if (parsedValue != null) return parsedValue; List<String> legalValues = new ArrayList<>(valueMapping.keyS...
### Question: TokenFilter { public String filter(String input) { StringBuilder output = new StringBuilder(); Matcher tokenMatcher = tokenPattern.matcher(input); int endOfLastMatch = 0; while (tokenMatcher.find()) { String literal = tokenMatcher.group(LEADING_TEXT_GROUP); String escape = tokenMatcher.group(ESCAPE_CHAR_G...
### Question: TokenFilter { public void filterValues(Map<?, String> map) { for (Map.Entry<?, String> entry : map.entrySet()) { String value = entry.getValue(); if (value != null) entry.setValue(filter(value)); } } TokenFilter(); TokenFilter(Map<String, String> tokenValues); void setToken(String name, String value); St...
### Question: TokenName { public static String canonicalize(final String name, final String prefix) { Matcher groupMatcher = STRING_NAME_GROUPING.matcher(name); if (!groupMatcher.find()) return prefix + name.toUpperCase(); StringBuilder builder = new StringBuilder(prefix); builder.append(groupMatcher.group(0).toUpperCa...
### Question: GuacamoleProtocolVersion { public static GuacamoleProtocolVersion parseVersion(String version) { Matcher versionMatcher = VERSION_PATTERN.matcher(version); if (!versionMatcher.matches()) return null; return new GuacamoleProtocolVersion( Integer.parseInt(versionMatcher.group(1)), Integer.parseInt(versionMa...
### Question: GuacamoleProtocolVersion { @Override public String toString() { return "VERSION_" + getMajor() + "_" + getMinor() + "_" + getPatch(); } GuacamoleProtocolVersion(int major, int minor, int patch); int getMajor(); int getMinor(); int getPatch(); boolean atLeast(GuacamoleProtocolVersion otherVersion); static ...
### Question: FilteredGuacamoleReader implements GuacamoleReader { @Override public GuacamoleInstruction readInstruction() throws GuacamoleException { GuacamoleInstruction filteredInstruction; do { GuacamoleInstruction unfilteredInstruction = reader.readInstruction(); if (unfilteredInstruction == null) return null; fil...
### Question: ReaderGuacamoleReader implements GuacamoleReader { @Override public GuacamoleInstruction readInstruction() throws GuacamoleException { char[] instructionBuffer = read(); if (instructionBuffer == null) return null; int elementStart = 0; Deque<String> elements = new LinkedList<String>(); while (elementStart...
### Question: QCParser { public static Map<String, String> parseQueryString(String queryStr) throws UnsupportedEncodingException { List<String> paramList = Arrays.asList(queryStr.split("&")); Map<String, String> parameters = new HashMap<String,String>(); for (String param : paramList) { String[] paramArray = param.spli...
### Question: QCParser { public static void parseUserInfo(String userInfo, GuacamoleConfiguration config) throws UnsupportedEncodingException { Matcher userinfoMatcher = userinfoPattern.matcher(userInfo); if (userinfoMatcher.matches()) { String username = userinfoMatcher.group(USERNAME_GROUP); String password = userinf...
### Question: RootResource { @GET @PermitAll public APIRootResponse get(@Context SecurityContext context) { final Map<String, APIRestLink> links = new HashMap<>(); links.put("v1", new APIRestLink(URI.create(Constants.HTTP_V1_ROOT))); return new APIRootResponse(links); } @GET @PermitAll APIRootResponse get(@Context Sec...
### Question: JsonWebTokenConfig implements AuthenticationConfig { @Override public AuthFilter<?, Principal> createAuthFilter(AuthenticationBootstrap bootstrap) { final byte[] decodedSecretKey = Base64.getDecoder().decode(secretKey); final Key secretKeyKey = new SecretKeySpec(decodedSecretKey, 0, decodedSecretKey.lengt...
### Question: JsonWebTokenAuthenticator implements Authenticator<String, Principal> { @Override public Optional<Principal> authenticate(String s) throws NullPointerException, AuthenticationException { Objects.requireNonNull(s); try { final Jws<Claims> claims = Jwts.parser().setSigningKey(this.secretKey).parseClaimsJws(...