src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
CompetitionPostSubmissionController { @PutMapping("/{id}/release-feedback") public RestResult<Void> releaseFeedback(@PathVariable("id") final long competitionId) { return competitionService.releaseFeedback(competitionId) .andOnSuccess(() -> applicationNotificationService.notifyApplicantsByCompetition(competitionId)) .toPutResponse(); } @PutMapping("/{id}/release-feedback") RestResult<Void> releaseFeedback(@PathVariable("id") final long competitionId); @PutMapping("/{id}/close-assessment") RestResult<Void> closeAssessment(@PathVariable("id") final Long id); @GetMapping("/{id}/queries/open") RestResult<List<CompetitionOpenQueryResource>> getOpenQueries(@PathVariable("id") Long competitionId); @GetMapping("/{id}/queries/open/count") RestResult<Long> countOpenQueries(@PathVariable("id") Long competitionId); @GetMapping("/{competitionId}/pending-spend-profiles") RestResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(@PathVariable(value = "competitionId") Long competitionId); @GetMapping("/{competitionId}/count-pending-spend-profiles") RestResult<Long> countPendingSpendProfiles(@PathVariable(value = "competitionId") Long competitionId); } | @Test public void releaseFeedback() throws Exception { final Long competitionId = 1L; when(competitionServiceMock.releaseFeedback(competitionId)).thenReturn(serviceSuccess()); when(applicationNotificationServiceMock.notifyApplicantsByCompetition(competitionId)).thenReturn(serviceSuccess()); mockMvc.perform(put("/competition/post-submission/{id}/release-feedback", competitionId)) .andExpect(status().isOk()); verify(competitionServiceMock, only()).releaseFeedback(competitionId); verify(applicationNotificationServiceMock).notifyApplicantsByCompetition(competitionId); } |
CompetitionPostSubmissionController { @PutMapping("/{id}/close-assessment") public RestResult<Void> closeAssessment(@PathVariable("id") final Long id) { return competitionService.closeAssessment(id).toPutResponse(); } @PutMapping("/{id}/release-feedback") RestResult<Void> releaseFeedback(@PathVariable("id") final long competitionId); @PutMapping("/{id}/close-assessment") RestResult<Void> closeAssessment(@PathVariable("id") final Long id); @GetMapping("/{id}/queries/open") RestResult<List<CompetitionOpenQueryResource>> getOpenQueries(@PathVariable("id") Long competitionId); @GetMapping("/{id}/queries/open/count") RestResult<Long> countOpenQueries(@PathVariable("id") Long competitionId); @GetMapping("/{competitionId}/pending-spend-profiles") RestResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(@PathVariable(value = "competitionId") Long competitionId); @GetMapping("/{competitionId}/count-pending-spend-profiles") RestResult<Long> countPendingSpendProfiles(@PathVariable(value = "competitionId") Long competitionId); } | @Test public void closeAssessment() throws Exception { final Long competitionId = 1L; when(competitionServiceMock.closeAssessment(competitionId)).thenReturn(serviceSuccess()); mockMvc.perform(put("/competition/post-submission/{id}/close-assessment", competitionId)) .andExpect(status().isOk()) .andExpect(content().string("")); verify(competitionServiceMock, only()).closeAssessment(competitionId); } |
CompetitionPostSubmissionController { @GetMapping("/{competitionId}/pending-spend-profiles") public RestResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(@PathVariable(value = "competitionId") Long competitionId) { return competitionService.getPendingSpendProfiles(competitionId).toGetResponse(); } @PutMapping("/{id}/release-feedback") RestResult<Void> releaseFeedback(@PathVariable("id") final long competitionId); @PutMapping("/{id}/close-assessment") RestResult<Void> closeAssessment(@PathVariable("id") final Long id); @GetMapping("/{id}/queries/open") RestResult<List<CompetitionOpenQueryResource>> getOpenQueries(@PathVariable("id") Long competitionId); @GetMapping("/{id}/queries/open/count") RestResult<Long> countOpenQueries(@PathVariable("id") Long competitionId); @GetMapping("/{competitionId}/pending-spend-profiles") RestResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(@PathVariable(value = "competitionId") Long competitionId); @GetMapping("/{competitionId}/count-pending-spend-profiles") RestResult<Long> countPendingSpendProfiles(@PathVariable(value = "competitionId") Long competitionId); } | @Test public void getPendingSpendProfiles() throws Exception { final Long competitionId = 1L; List<SpendProfileStatusResource> pendingSpendProfiles = new ArrayList<>(); when(competitionServiceMock.getPendingSpendProfiles(competitionId)).thenReturn(serviceSuccess(pendingSpendProfiles)); mockMvc.perform(get("/competition/post-submission/{competitionId}/pending-spend-profiles", competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(pendingSpendProfiles))); verify(competitionServiceMock, only()).getPendingSpendProfiles(competitionId); } |
CompetitionPostSubmissionController { @GetMapping("/{competitionId}/count-pending-spend-profiles") public RestResult<Long> countPendingSpendProfiles(@PathVariable(value = "competitionId") Long competitionId) { return competitionService.countPendingSpendProfiles(competitionId).toGetResponse(); } @PutMapping("/{id}/release-feedback") RestResult<Void> releaseFeedback(@PathVariable("id") final long competitionId); @PutMapping("/{id}/close-assessment") RestResult<Void> closeAssessment(@PathVariable("id") final Long id); @GetMapping("/{id}/queries/open") RestResult<List<CompetitionOpenQueryResource>> getOpenQueries(@PathVariable("id") Long competitionId); @GetMapping("/{id}/queries/open/count") RestResult<Long> countOpenQueries(@PathVariable("id") Long competitionId); @GetMapping("/{competitionId}/pending-spend-profiles") RestResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(@PathVariable(value = "competitionId") Long competitionId); @GetMapping("/{competitionId}/count-pending-spend-profiles") RestResult<Long> countPendingSpendProfiles(@PathVariable(value = "competitionId") Long competitionId); } | @Test public void countPendingSpendProfiles() throws Exception { final Long competitionId = 1L; final Long pendingSpendProfileCount = 3L; when(competitionServiceMock.countPendingSpendProfiles(competitionId)).thenReturn(serviceSuccess(pendingSpendProfileCount)); mockMvc.perform(get("/competition/post-submission/{competitionId}/count-pending-spend-profiles", competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(pendingSpendProfileCount))); verify(competitionServiceMock, only()).countPendingSpendProfiles(competitionId); } |
TermsAndConditionsController { @GetMapping("get-by-id/{id}") public RestResult<GrantTermsAndConditionsResource> getById(@PathVariable("id") final Long id) { return termsAndConditionsService.getById(id).toGetResponse(); } @GetMapping("/get-latest") RestResult<List<GrantTermsAndConditionsResource>> getLatestVersionsForAllTermsAndConditions(); @GetMapping("get-by-id/{id}") RestResult<GrantTermsAndConditionsResource> getById(@PathVariable("id") final Long id); @GetMapping("/site") RestResult<SiteTermsAndConditionsResource> getLatestSiteTermsAndConditions(); } | @Test public void getById() throws Exception { final Long competitionId = 1L; when(termsAndConditionsService.getById(competitionId)).thenReturn(serviceSuccess (newGrantTermsAndConditionsResource().build())); mockMvc.perform(get("/terms-and-conditions/get-by-id/{id}", competitionId)) .andExpect(status().isOk()); verify(termsAndConditionsService, only()).getById(competitionId); } |
TermsAndConditionsController { @GetMapping("/get-latest") public RestResult<List<GrantTermsAndConditionsResource>> getLatestVersionsForAllTermsAndConditions() { return termsAndConditionsService.getLatestVersionsForAllTermsAndConditions().toGetResponse(); } @GetMapping("/get-latest") RestResult<List<GrantTermsAndConditionsResource>> getLatestVersionsForAllTermsAndConditions(); @GetMapping("get-by-id/{id}") RestResult<GrantTermsAndConditionsResource> getById(@PathVariable("id") final Long id); @GetMapping("/site") RestResult<SiteTermsAndConditionsResource> getLatestSiteTermsAndConditions(); } | @Test public void getLatest() throws Exception { List<GrantTermsAndConditionsResource> termsAndConditionsResourceList = newGrantTermsAndConditionsResource() .build(2); when(termsAndConditionsService.getLatestVersionsForAllTermsAndConditions()).thenReturn(serviceSuccess (termsAndConditionsResourceList)); mockMvc.perform(get("/terms-and-conditions/get-latest")) .andExpect(status().isOk()) .andExpect(content().json(toJson(termsAndConditionsResourceList))); verify(termsAndConditionsService, only()).getLatestVersionsForAllTermsAndConditions(); } |
TermsAndConditionsController { @GetMapping("/site") public RestResult<SiteTermsAndConditionsResource> getLatestSiteTermsAndConditions() { return termsAndConditionsService.getLatestSiteTermsAndConditions().toGetResponse(); } @GetMapping("/get-latest") RestResult<List<GrantTermsAndConditionsResource>> getLatestVersionsForAllTermsAndConditions(); @GetMapping("get-by-id/{id}") RestResult<GrantTermsAndConditionsResource> getById(@PathVariable("id") final Long id); @GetMapping("/site") RestResult<SiteTermsAndConditionsResource> getLatestSiteTermsAndConditions(); } | @Test public void getLatestSiteTermsAndConditions() throws Exception { SiteTermsAndConditionsResource expected = newSiteTermsAndConditionsResource().build(); when(termsAndConditionsService.getLatestSiteTermsAndConditions()).thenReturn(serviceSuccess(expected)); mockMvc.perform(RestDocumentationRequestBuilders.get("/terms-and-conditions/site")) .andExpect(status().isOk()) .andExpect(content().json(toJson(expected))); verify(termsAndConditionsService, only()).getLatestSiteTermsAndConditions(); } |
MilestoneServiceImpl extends BaseTransactionalService implements MilestoneService { @Override @Transactional public ServiceResult<Void> updateMilestones(List<MilestoneResource> milestones) { ValidationMessages messages = validate(milestones); if (messages.hasErrors()) { return serviceFailure(messages.getErrors()); } milestoneRepository.saveAll(milestoneMapper.mapToDomain(milestones)); return serviceSuccess(); } @Override ServiceResult<List<MilestoneResource>> getAllPublicMilestonesByCompetitionId(Long id); @Override ServiceResult<Boolean> allPublicDatesComplete(Long competitionId); @Override ServiceResult<List<MilestoneResource>> getAllMilestonesByCompetitionId(Long id); @Override ServiceResult<MilestoneResource> getMilestoneByTypeAndCompetitionId(MilestoneType type, Long id); @Override @Transactional ServiceResult<Void> updateMilestones(List<MilestoneResource> milestones); @Override @Transactional ServiceResult<Void> updateMilestone(MilestoneResource milestoneResource); @Override @Transactional ServiceResult<MilestoneResource> create(MilestoneType type, Long id); @Override @Transactional ServiceResult<Void> updateCompletionStage(long competitionId, CompetitionCompletionStage completionStage); } | @Test public void testUpdateMilestones() { Competition competition = newCompetition().build(); when(competitionRepository.findById(1L)).thenReturn(Optional.of(competition)); List<MilestoneResource> milestones = newMilestoneResource() .withCompetitionId(1L, 1L) .withType(FUNDERS_PANEL, ASSESSMENT_PANEL) .withDate(ZonedDateTime.of(2050, 3, 11, 0, 0, 0, 0, ZoneId.systemDefault()), ZonedDateTime.of(2050, 3, 10, 0, 0, 0, 0, ZoneId.systemDefault())) .build(2); List<Milestone> milestonesToSave = newMilestone() .withCompetition(newCompetition().withId(1L).build(), newCompetition().withId(1L).build()) .withType(FUNDERS_PANEL, ASSESSMENT_PANEL) .withDate(ZonedDateTime.of(2050, 3, 11, 0, 0, 0, 0, ZoneId.systemDefault()), ZonedDateTime.of(2050, 3, 10, 0, 0, 0, 0, ZoneId.systemDefault())) .build(2); when(milestoneMapper.mapToDomain(milestones)).thenReturn(milestonesToSave); ServiceResult<Void> result = service.updateMilestones(milestones); assertTrue(result.isSuccess()); verify(milestoneRepository, times(1)).saveAll(milestonesToSave); }
@Test public void testUpdateNotSequential() { Competition competition = newCompetition().build(); when(competitionRepository.findById(1L)).thenReturn(Optional.of(competition)); List<MilestoneResource> milestones = newMilestoneResource() .withCompetitionId(1L, 1L) .withType(FUNDERS_PANEL, ASSESSMENT_PANEL) .withDate(ZonedDateTime.of(2050, 3, 10, 0, 0, 0, 0, ZoneId.systemDefault()), ZonedDateTime.of(2050, 3, 11, 0, 0, 0, 0, ZoneId.systemDefault())) .build(2); ServiceResult<Void> result = service.updateMilestones(milestones); assertFalse(result.isSuccess()); assertEquals(1, result.getFailure().getErrors().size()); assertEquals("error.milestone.nonsequential", result.getFailure().getErrors().get(0).getErrorKey()); assertEquals(0, competition.getMilestones().size()); }
@Test public void testUpdateMilestonesNullDate() { Competition competition = newCompetition().build(); when(competitionRepository.findById(1L)).thenReturn(Optional.of(competition)); List<MilestoneResource> milestones = newMilestoneResource() .withCompetitionId(1L, 1L) .withType(FUNDERS_PANEL, ASSESSMENT_PANEL) .withDate(ZonedDateTime.of(2050, 3, 11, 0, 0, 0, 0, ZoneId.systemDefault()), null) .build(2); ServiceResult<Void> result = service.updateMilestones(milestones); assertFalse(result.isSuccess()); assertEquals(1, result.getFailure().getErrors().size()); assertEquals("error.milestone.nulldate", result.getFailure().getErrors().get(0).getErrorKey()); assertEquals(0, competition.getMilestones().size()); }
@Test public void testUpdateMilestonesDateInPast() { Competition competition = newCompetition().build(); when(competitionRepository.findById(1L)).thenReturn(Optional.of(competition)); List<MilestoneResource> milestones = newMilestoneResource() .withCompetitionId(1L, 1L) .withType(FUNDERS_PANEL, ASSESSMENT_PANEL) .withDate(ZonedDateTime.of(2050, 3, 11, 0, 0, 0, 0, ZoneId.systemDefault()), ZonedDateTime.of(1985, 3, 10, 0, 0, 0, 0, ZoneId.systemDefault())) .build(2); ServiceResult<Void> result = service.updateMilestones(milestones); assertFalse(result.isSuccess()); assertEquals(1, result.getFailure().getErrors().size()); assertEquals("error.milestone.pastdate", result.getFailure().getErrors().get(0).getErrorKey()); assertEquals(0, competition.getMilestones().size()); }
@Test public void testUpdateMilestonesErrorsNotRepeated() { Competition competition = newCompetition().build(); when(competitionRepository.findById(1L)).thenReturn(Optional.of(competition)); List<MilestoneResource> milestones = newMilestoneResource() .withCompetitionId(1L, 1L) .withType(FUNDERS_PANEL, ASSESSMENT_PANEL, ALLOCATE_ASSESSORS, ASSESSOR_ACCEPTS) .build(4); ServiceResult<Void> result = service.updateMilestones(milestones); assertFalse(result.isSuccess()); assertEquals(1, result.getFailure().getErrors().size()); assertEquals("error.milestone.nulldate", result.getFailure().getErrors().get(0).getErrorKey()); assertEquals(0, competition.getMilestones().size()); }
@Test public void testUpdateMilestones_milestonesForNonIfsCompetitionDoNotHaveToBeInFuture() { Competition nonIfsCompetition = newCompetition().withNonIfs(true).build(); when(competitionRepository.findById(1L)).thenReturn(Optional.of(nonIfsCompetition)); ZonedDateTime lastYearSomewhere = ZonedDateTime.now() .minusYears(1); ZonedDateTime lastYearSomewhereButLater = ZonedDateTime.now() .minusYears(1) .plusDays(1); List<MilestoneResource> pastMilestones = newMilestoneResource() .withCompetitionId(1L, 1L) .withType(FUNDERS_PANEL, ASSESSMENT_PANEL) .withDate(lastYearSomewhereButLater, lastYearSomewhere) .build(2); ServiceResult<Void> result = service.updateMilestones(pastMilestones); assertTrue(result.isSuccess()); }
@Test public void testUpdateMilestones_milestonesForIfsCompetitionHaveToBeInFuture() { Competition ifsCompetition = newCompetition().withNonIfs(false).build(); when(competitionRepository.findById(1L)).thenReturn(Optional.of(ifsCompetition)); ZonedDateTime lastYearSomewhere = ZonedDateTime.now() .minusYears(1); ZonedDateTime lastYearSomewhereButLater = ZonedDateTime.now() .minusYears(1) .plusDays(1); List<MilestoneResource> pastMilestones = newMilestoneResource() .withCompetitionId(1L, 1L) .withType(FUNDERS_PANEL, ASSESSMENT_PANEL) .withDate(lastYearSomewhereButLater, lastYearSomewhere) .build(2); ServiceResult<Void> result = service.updateMilestones(pastMilestones); assertTrue(result.isFailure()); assertEquals(result.getErrors().get(0).getErrorKey(), "error.milestone.pastdate"); }
@Test public void testUpdateMilestones_whenMilestonesAreReferencingDifferentCompetitionsShouldReturnError() { Competition competition = newCompetition().build(); when(competitionRepository.findById(1L)).thenReturn(Optional.of(competition)); List<MilestoneResource> milestones = newMilestoneResource() .withCompetitionId(1L, 2L) .withType(FUNDERS_PANEL, ASSESSMENT_PANEL) .withDate(ZonedDateTime.of(2050, 3, 11, 0, 0, 0, 0, ZoneId.systemDefault()), ZonedDateTime.of(2050, 3, 10, 0, 0, 0, 0, ZoneId.systemDefault())) .build(2); ServiceResult<Void> result = service.updateMilestones(milestones); assertTrue(result.isFailure()); assertEquals(result.getErrors().get(0).getErrorKey(), "error.title.status.400"); } |
MilestoneServiceImpl extends BaseTransactionalService implements MilestoneService { @Override @Transactional public ServiceResult<Void> updateMilestone(MilestoneResource milestoneResource) { milestoneRepository.save(milestoneMapper.mapToDomain(milestoneResource)); return serviceSuccess(); } @Override ServiceResult<List<MilestoneResource>> getAllPublicMilestonesByCompetitionId(Long id); @Override ServiceResult<Boolean> allPublicDatesComplete(Long competitionId); @Override ServiceResult<List<MilestoneResource>> getAllMilestonesByCompetitionId(Long id); @Override ServiceResult<MilestoneResource> getMilestoneByTypeAndCompetitionId(MilestoneType type, Long id); @Override @Transactional ServiceResult<Void> updateMilestones(List<MilestoneResource> milestones); @Override @Transactional ServiceResult<Void> updateMilestone(MilestoneResource milestoneResource); @Override @Transactional ServiceResult<MilestoneResource> create(MilestoneType type, Long id); @Override @Transactional ServiceResult<Void> updateCompletionStage(long competitionId, CompetitionCompletionStage completionStage); } | @Test public void updateMilestone() { ZonedDateTime milestoneDate = ZonedDateTime.now(); ServiceResult<Void> result = service.updateMilestone(newMilestoneResource().withType(BRIEFING_EVENT).withDate(milestoneDate.plusMonths(1)).build()); assertTrue(result.isSuccess()); } |
MilestoneServiceImpl extends BaseTransactionalService implements MilestoneService { @Override public ServiceResult<List<MilestoneResource>> getAllMilestonesByCompetitionId(Long id) { return serviceSuccess((List<MilestoneResource>) milestoneMapper.mapToResource(milestoneRepository.findAllByCompetitionId(id))); } @Override ServiceResult<List<MilestoneResource>> getAllPublicMilestonesByCompetitionId(Long id); @Override ServiceResult<Boolean> allPublicDatesComplete(Long competitionId); @Override ServiceResult<List<MilestoneResource>> getAllMilestonesByCompetitionId(Long id); @Override ServiceResult<MilestoneResource> getMilestoneByTypeAndCompetitionId(MilestoneType type, Long id); @Override @Transactional ServiceResult<Void> updateMilestones(List<MilestoneResource> milestones); @Override @Transactional ServiceResult<Void> updateMilestone(MilestoneResource milestoneResource); @Override @Transactional ServiceResult<MilestoneResource> create(MilestoneType type, Long id); @Override @Transactional ServiceResult<Void> updateCompletionStage(long competitionId, CompetitionCompletionStage completionStage); } | @Test public void getAllMilestones() { List<Milestone> milestones = newMilestone().withType(BRIEFING_EVENT, LINE_DRAW, NOTIFICATIONS).build(3); when(milestoneRepository.findAllByCompetitionId(1L)).thenReturn(milestones); ServiceResult<List<MilestoneResource>> result = service.getAllMilestonesByCompetitionId(1L); assertTrue(result.isSuccess()); assertNotNull(result); assertEquals(3, milestones.size()); } |
MilestoneServiceImpl extends BaseTransactionalService implements MilestoneService { @Override public ServiceResult<List<MilestoneResource>> getAllPublicMilestonesByCompetitionId(Long id) { return find(competitionRepository.findById(id), notFoundError(Competition.class, id)).andOnSuccessReturn(competition -> (List<MilestoneResource>) milestoneMapper.mapToResource(milestoneRepository .findByCompetitionIdAndTypeIn(id, competition.isH2020() ? HORIZON_PUBLIC_MILESTONES : PUBLIC_MILESTONES)) ); } @Override ServiceResult<List<MilestoneResource>> getAllPublicMilestonesByCompetitionId(Long id); @Override ServiceResult<Boolean> allPublicDatesComplete(Long competitionId); @Override ServiceResult<List<MilestoneResource>> getAllMilestonesByCompetitionId(Long id); @Override ServiceResult<MilestoneResource> getMilestoneByTypeAndCompetitionId(MilestoneType type, Long id); @Override @Transactional ServiceResult<Void> updateMilestones(List<MilestoneResource> milestones); @Override @Transactional ServiceResult<Void> updateMilestone(MilestoneResource milestoneResource); @Override @Transactional ServiceResult<MilestoneResource> create(MilestoneType type, Long id); @Override @Transactional ServiceResult<Void> updateCompletionStage(long competitionId, CompetitionCompletionStage completionStage); } | @Test public void getAllPublicMilestones() { Competition competition = newCompetition().withCompetitionType(newCompetitionType().withName("Competition Type").build()).build(); List<Milestone> milestones = newMilestone().withType(OPEN_DATE, REGISTRATION_DATE, NOTIFICATIONS, SUBMISSION_DATE).build(4); when(milestoneRepository.findByCompetitionIdAndTypeIn(competition.getId(), asList(OPEN_DATE, REGISTRATION_DATE, SUBMISSION_DATE, NOTIFICATIONS))) .thenReturn(milestones); when(competitionRepository.findById(competition.getId())).thenReturn(Optional.of(competition)); ServiceResult<List<MilestoneResource>> result = service.getAllPublicMilestonesByCompetitionId(competition.getId()); assertTrue(result.isSuccess()); assertNotNull(result); assertEquals(4, milestones.size()); }
@Test public void getAllPublicMilestones_horizon2020() { Competition competition = newCompetition().withCompetitionType(newCompetitionType().withName("Horizon 2020").build()).build(); List<Milestone> milestones = newMilestone().withType(OPEN_DATE, REGISTRATION_DATE).build(3); when(milestoneRepository.findByCompetitionIdAndTypeIn(competition.getId(), asList(OPEN_DATE, REGISTRATION_DATE, SUBMISSION_DATE))) .thenReturn(milestones); when(competitionRepository.findById(competition.getId())).thenReturn(Optional.of(competition)); ServiceResult<List<MilestoneResource>> result = service.getAllPublicMilestonesByCompetitionId(competition.getId()); assertTrue(result.isSuccess()); assertNotNull(result); assertEquals(3, milestones.size()); } |
MilestoneServiceImpl extends BaseTransactionalService implements MilestoneService { @Override public ServiceResult<Boolean> allPublicDatesComplete(Long competitionId) { return find(competitionRepository.findById(competitionId), notFoundError(Competition.class, competitionId)).andOnSuccessReturn(competition -> { boolean isNonIfs = competition.isNonIfs(); List<MilestoneType> milestonesRequired; if (isNonIfs) { milestonesRequired= PUBLIC_MILESTONES.stream() .filter(milestoneType -> filterNonIfsOutOnIFSComp(milestoneType, isNonIfs)) .collect(toList()); } else { milestonesRequired = PUBLIC_MILESTONES.stream() .filter(milestoneType -> milestoneType.getPriority() <= competition.getCompletionStage().getLastMilestone().getPriority()) .filter(milestoneType -> filterNonIfsOutOnIFSComp(milestoneType, isNonIfs)) .collect(toList()); } List<Milestone> milestones = milestoneRepository .findByCompetitionIdAndTypeIn(competitionId, milestonesRequired); return hasRequiredMilestones(milestones, milestonesRequired); }); } @Override ServiceResult<List<MilestoneResource>> getAllPublicMilestonesByCompetitionId(Long id); @Override ServiceResult<Boolean> allPublicDatesComplete(Long competitionId); @Override ServiceResult<List<MilestoneResource>> getAllMilestonesByCompetitionId(Long id); @Override ServiceResult<MilestoneResource> getMilestoneByTypeAndCompetitionId(MilestoneType type, Long id); @Override @Transactional ServiceResult<Void> updateMilestones(List<MilestoneResource> milestones); @Override @Transactional ServiceResult<Void> updateMilestone(MilestoneResource milestoneResource); @Override @Transactional ServiceResult<MilestoneResource> create(MilestoneType type, Long id); @Override @Transactional ServiceResult<Void> updateCompletionStage(long competitionId, CompetitionCompletionStage completionStage); } | @Test public void allPublicDatesCompleteSuccess() { List<Milestone> milestones = newMilestone().withType(OPEN_DATE, SUBMISSION_DATE, NOTIFICATIONS).withDate(ZonedDateTime.now()).build(4); when(milestoneRepository.findByCompetitionIdAndTypeIn(1L, asList(OPEN_DATE, SUBMISSION_DATE, NOTIFICATIONS))) .thenReturn(milestones); ServiceResult<Boolean> result = service.allPublicDatesComplete(1L); assertTrue(result.isSuccess()); assertTrue(result.getSuccess()); }
@Test public void allPublicDatesCompleteSuccessForNonIfs() { when(competitionRepository.findById(1L)) .thenReturn(Optional.of(newCompetition() .withId(1L) .withCompletionStage(CompetitionCompletionStage.PROJECT_SETUP) .withNonIfs(true) .build())); List<Milestone> milestones = newMilestone().withType(OPEN_DATE, REGISTRATION_DATE, NOTIFICATIONS, SUBMISSION_DATE).withDate(ZonedDateTime.now()).build(4); when(milestoneRepository.findByCompetitionIdAndTypeIn(1L, asList(OPEN_DATE, REGISTRATION_DATE, SUBMISSION_DATE))) .thenReturn(milestones); ServiceResult<Boolean> result = service.allPublicDatesComplete(1L); assertTrue(result.isSuccess()); assertTrue(result.getSuccess()); }
@Test public void allPublicDatesCompleteFailure() { List<Milestone> milestones = newMilestone().withType(RELEASE_FEEDBACK, SUBMISSION_DATE).build(2); when(milestoneRepository.findByCompetitionIdAndTypeIn(1L, asList(OPEN_DATE, SUBMISSION_DATE, NOTIFICATIONS))) .thenReturn(milestones); ServiceResult<Boolean> result = service.allPublicDatesComplete(1L); assertTrue(result.isSuccess()); assertFalse(result.getSuccess()); } |
MilestoneServiceImpl extends BaseTransactionalService implements MilestoneService { @Override public ServiceResult<MilestoneResource> getMilestoneByTypeAndCompetitionId(MilestoneType type, Long id) { return find(milestoneRepository.findByTypeAndCompetitionId(type, id), notFoundError(MilestoneResource.class, type, id)) .andOnSuccess(milestone -> serviceSuccess(milestoneMapper.mapToResource(milestone))); } @Override ServiceResult<List<MilestoneResource>> getAllPublicMilestonesByCompetitionId(Long id); @Override ServiceResult<Boolean> allPublicDatesComplete(Long competitionId); @Override ServiceResult<List<MilestoneResource>> getAllMilestonesByCompetitionId(Long id); @Override ServiceResult<MilestoneResource> getMilestoneByTypeAndCompetitionId(MilestoneType type, Long id); @Override @Transactional ServiceResult<Void> updateMilestones(List<MilestoneResource> milestones); @Override @Transactional ServiceResult<Void> updateMilestone(MilestoneResource milestoneResource); @Override @Transactional ServiceResult<MilestoneResource> create(MilestoneType type, Long id); @Override @Transactional ServiceResult<Void> updateCompletionStage(long competitionId, CompetitionCompletionStage completionStage); } | @Test public void getMilestoneByTypeAndCompetition() { Milestone milestone = newMilestone().withType(NOTIFICATIONS).build(); when(milestoneRepository.findByTypeAndCompetitionId(NOTIFICATIONS, 1L)).thenReturn(Optional.ofNullable(milestone)); when(milestoneMapper.mapToResource(milestone)).thenReturn(newMilestoneResource().withType(NOTIFICATIONS).build()); ServiceResult<MilestoneResource> result = service.getMilestoneByTypeAndCompetitionId(NOTIFICATIONS, 1L); assertTrue(result.isSuccess()); assertEquals(NOTIFICATIONS, milestone.getType()); assertNull(milestone.getDate()); }
@Test public void getMilestoneByTypeAndCompetitionReturnsNotFoundErrorWhenNotPresent() { when(milestoneRepository.findByTypeAndCompetitionId(NOTIFICATIONS, 1L)).thenReturn(Optional.empty()); ServiceResult<MilestoneResource> result = service.getMilestoneByTypeAndCompetitionId(NOTIFICATIONS, 1L); assertTrue(result.isFailure()); assertEquals(result.getErrors().size(), 1); assertEquals(result.getErrors().get(0).getStatusCode(), HttpStatus.NOT_FOUND); } |
MilestoneServiceImpl extends BaseTransactionalService implements MilestoneService { @Override @Transactional public ServiceResult<Void> updateCompletionStage(long competitionId, CompetitionCompletionStage completionStage) { return getCompetition(competitionId).andOnSuccessReturnVoid(competition -> { if (competition.getCompletionStage() != completionStage) { competition.setCompletionStage(completionStage); List<Milestone> currentMilestones = milestoneRepository.findAllByCompetitionId(competitionId); List<Milestone> newMilestones = new ArrayList<>(); if (currentMilestones.size() > 1) { List<Milestone> milestonesToDelete = currentMilestones.stream() .filter(milestone -> milestone.getType().getPriority() > completionStage.getLastMilestone().getPriority()) .collect(Collectors.toList()); milestoneRepository.deleteAll(milestonesToDelete); List<MilestoneType> currentMilestoneTypes = currentMilestones.stream() .map(milestone -> milestone.getType()) .collect(toList()); Stream.of(MilestoneType.presetValues()).filter(milestoneType -> !milestoneType.isOnlyNonIfs()) .filter(milestoneType -> !currentMilestoneTypes.contains(milestoneType)).forEach(type -> newMilestones.add(new Milestone(type, competition)) ); milestoneRepository.saveAll(newMilestones); } else { Stream.of(MilestoneType.presetValues()).filter(milestoneType -> !milestoneType.isOnlyNonIfs()) .filter(milestoneType -> milestoneType.getPriority() <= completionStage.getLastMilestone().getPriority()) .filter(milestoneType -> !milestoneType.equals(MilestoneType.OPEN_DATE)).forEach(type -> newMilestones.add(new Milestone(type, competition)) ); milestoneRepository.saveAll(newMilestones); } } }); } @Override ServiceResult<List<MilestoneResource>> getAllPublicMilestonesByCompetitionId(Long id); @Override ServiceResult<Boolean> allPublicDatesComplete(Long competitionId); @Override ServiceResult<List<MilestoneResource>> getAllMilestonesByCompetitionId(Long id); @Override ServiceResult<MilestoneResource> getMilestoneByTypeAndCompetitionId(MilestoneType type, Long id); @Override @Transactional ServiceResult<Void> updateMilestones(List<MilestoneResource> milestones); @Override @Transactional ServiceResult<Void> updateMilestone(MilestoneResource milestoneResource); @Override @Transactional ServiceResult<MilestoneResource> create(MilestoneType type, Long id); @Override @Transactional ServiceResult<Void> updateCompletionStage(long competitionId, CompetitionCompletionStage completionStage); } | @Test public void updateCompletionStage_noChange() { Competition competition = newCompetition() .withCompletionStage(CompetitionCompletionStage.PROJECT_SETUP) .build(); when(competitionRepository.findById(1L)).thenReturn(Optional.of(competition)); ServiceResult<Void> result = service.updateCompletionStage(1L, CompetitionCompletionStage.PROJECT_SETUP); assertTrue(result.isSuccess()); verifyNoMoreInteractions(milestoneRepository); }
@Test @Rollback public void updateCompletionStage() { Competition competition = newCompetition() .withStartDate(ZonedDateTime.now()) .build(); when(competitionRepository.findById(1L)).thenReturn(Optional.of(competition)); ServiceResult<Void> result = service.updateCompletionStage(1L, CompetitionCompletionStage.PROJECT_SETUP); assertTrue(result.isSuccess()); } |
CompetitionSetupPostAwardServiceServiceImpl extends BaseTransactionalService implements CompetitionSetupPostAwardServiceService { @Override @Transactional public ServiceResult<Void> configurePostAwardService(long competitionId, PostAwardService postAwardService) { boolean sendByDefault = (postAwardService == PostAwardService.IFS_POST_AWARD); return findCompetitionById(competitionId) .andOnSuccessReturnVoid(competition -> { Optional<GrantProcessConfiguration> config = grantProcessConfigurationRepository.findByCompetitionId(competitionId); if (config.isPresent()) { GrantProcessConfiguration grantProcessConfiguration = config.get(); grantProcessConfiguration.setSendByDefault(sendByDefault); grantProcessConfigurationRepository.save(grantProcessConfiguration); } else { GrantProcessConfiguration grantProcessConfiguration = new GrantProcessConfiguration(); grantProcessConfiguration.setCompetition(competition); grantProcessConfiguration.setSendByDefault(sendByDefault); grantProcessConfigurationRepository.save(grantProcessConfiguration); } }); } @Override @Transactional ServiceResult<Void> configurePostAwardService(long competitionId, PostAwardService postAwardService); @Override ServiceResult<CompetitionPostAwardServiceResource> getPostAwardService(long competitionId); } | @Test public void configurePostAwardServiceWasSetToSendByDefault() { Long competitionId = 1L; Competition competition = newCompetition().withId(competitionId).build(); GrantProcessConfiguration grantProcessConfiguration = newGrantProcessConfiguration().withCompetition(competition).withSendByDefault(true).build(); when(competitionRepository.findById(competitionId)).thenReturn(Optional.of(competition)); when(grantProcessConfigurationRepository.findByCompetitionId(competitionId)).thenReturn(Optional.of(grantProcessConfiguration)); ServiceResult<Void> result = service.configurePostAwardService(competitionId, PostAwardService.CONNECT); assertTrue(result.isSuccess()); assertFalse(grantProcessConfiguration.isSendByDefault()); verify(grantProcessConfigurationRepository).save(grantProcessConfiguration); }
@Test public void configurePostAwardServiceWasSetToNotSendByDefault() { Long competitionId = 1L; Competition competition = newCompetition().withId(competitionId).build(); GrantProcessConfiguration grantProcessConfiguration = newGrantProcessConfiguration().withCompetition(competition).withSendByDefault(false).build(); when(competitionRepository.findById(competitionId)).thenReturn(Optional.of(competition)); when(grantProcessConfigurationRepository.findByCompetitionId(competitionId)).thenReturn(Optional.of(grantProcessConfiguration)); ServiceResult<Void> result = service.configurePostAwardService(competitionId, PostAwardService.IFS_POST_AWARD); assertTrue(result.isSuccess()); assertTrue(grantProcessConfiguration.isSendByDefault()); verify(grantProcessConfigurationRepository).save(grantProcessConfiguration); }
@Test public void configurePostAwardServiceWasNoConfigPresent() { Long competitionId = 1L; Competition competition = newCompetition().withId(competitionId).build(); when(competitionRepository.findById(competitionId)).thenReturn(Optional.of(competition)); when(grantProcessConfigurationRepository.findByCompetitionId(competitionId)).thenReturn(Optional.empty()); ServiceResult<Void> result = service.configurePostAwardService(competitionId, PostAwardService.IFS_POST_AWARD); assertTrue(result.isSuccess()); verify(grantProcessConfigurationRepository).save(argThat(config -> config.isSendByDefault() == true)); } |
CompetitionSetupPostAwardServiceServiceImpl extends BaseTransactionalService implements CompetitionSetupPostAwardServiceService { @Override public ServiceResult<CompetitionPostAwardServiceResource> getPostAwardService(long competitionId) { return findCompetitionById(competitionId) .andOnSuccessReturn(competition -> { Optional<GrantProcessConfiguration> config = grantProcessConfigurationRepository.findByCompetitionId(competitionId); PostAwardService postAwardService; if (!config.isPresent() || config.get().isSendByDefault()) { postAwardService = PostAwardService.IFS_POST_AWARD; } else { postAwardService = PostAwardService.CONNECT; } CompetitionPostAwardServiceResource resource = new CompetitionPostAwardServiceResource(); resource.setCompetitionId(competitionId); resource.setPostAwardService(postAwardService); return resource; }); } @Override @Transactional ServiceResult<Void> configurePostAwardService(long competitionId, PostAwardService postAwardService); @Override ServiceResult<CompetitionPostAwardServiceResource> getPostAwardService(long competitionId); } | @Test public void getPostAwardServiceWasSetToSendByDefault() { Long competitionId = 1L; Competition competition = newCompetition().withId(competitionId).build(); GrantProcessConfiguration grantProcessConfiguration = newGrantProcessConfiguration().withCompetition(competition).withSendByDefault(true).build(); when(competitionRepository.findById(competitionId)).thenReturn(Optional.of(competition)); when(grantProcessConfigurationRepository.findByCompetitionId(competitionId)).thenReturn(Optional.of(grantProcessConfiguration)); ServiceResult<CompetitionPostAwardServiceResource> result = service.getPostAwardService(competitionId); assertTrue(result.isSuccess()); assertEquals(competitionId, result.getSuccess().getCompetitionId()); assertEquals(PostAwardService.IFS_POST_AWARD, result.getSuccess().getPostAwardService()); }
@Test public void getPostAwardServiceWasSetToNotSendByDefault() { Long competitionId = 1L; Competition competition = newCompetition().withId(competitionId).build(); GrantProcessConfiguration grantProcessConfiguration = newGrantProcessConfiguration().withCompetition(competition).withSendByDefault(false).build(); when(competitionRepository.findById(competitionId)).thenReturn(Optional.of(competition)); when(grantProcessConfigurationRepository.findByCompetitionId(competitionId)).thenReturn(Optional.of(grantProcessConfiguration)); ServiceResult<CompetitionPostAwardServiceResource> result = service.getPostAwardService(competitionId); assertTrue(result.isSuccess()); assertEquals(competitionId, result.getSuccess().getCompetitionId()); assertEquals(PostAwardService.CONNECT, result.getSuccess().getPostAwardService()); }
@Test public void getPostAwardServiceWasNoConfigPresent() { Long competitionId = 1L; Competition competition = newCompetition().withId(competitionId).build(); when(competitionRepository.findById(competitionId)).thenReturn(Optional.of(competition)); when(grantProcessConfigurationRepository.findByCompetitionId(competitionId)).thenReturn(Optional.empty()); ServiceResult<CompetitionPostAwardServiceResource> result = service.getPostAwardService(competitionId); assertTrue(result.isSuccess()); assertEquals(competitionId, result.getSuccess().getCompetitionId()); assertEquals(PostAwardService.IFS_POST_AWARD, result.getSuccess().getPostAwardService()); } |
CompetitionSearchServiceImpl extends BaseTransactionalService implements CompetitionSearchService { @Override public ServiceResult<List<CompetitionSearchResultItem>> findLiveCompetitions() { List<Competition> competitions = competitionRepository.findLive(); return serviceSuccess(competitions.stream() .map(this::toLiveCompetitionResult) .collect(toList())); } @Override ServiceResult<List<CompetitionSearchResultItem>> findLiveCompetitions(); @Override ServiceResult<CompetitionSearchResult> findProjectSetupCompetitions(int page, int size); @Override ServiceResult<List<CompetitionSearchResultItem>> findUpcomingCompetitions(); @Override ServiceResult<CompetitionSearchResult> findNonIfsCompetitions(int page, int size); @Override ServiceResult<CompetitionSearchResult> findPreviousCompetitions(int page, int size); @Override ServiceResult<CompetitionSearchResult> searchCompetitions(String searchQuery, int page, int size); @Override ServiceResult<CompetitionCountResource> countCompetitions(); } | @Test public void findLiveCompetitions() { List<Competition> competitions = Lists.newArrayList(newCompetition().withId(competitionId).build()); when(competitionRepositoryMock.findLive()).thenReturn(competitions); List<CompetitionSearchResultItem> response = service.findLiveCompetitions().getSuccess(); assertCompetitionSearchResultsEqualToCompetitions(competitions, response); } |
CompetitionSearchServiceImpl extends BaseTransactionalService implements CompetitionSearchService { @Override public ServiceResult<CompetitionSearchResult> findProjectSetupCompetitions(int page, int size) { return getCurrentlyLoggedInUser().andOnSuccess(user -> { Page<Competition> competitions = user.hasRole(INNOVATION_LEAD) || user.hasRole(STAKEHOLDER) || user.hasRole(EXTERNAL_FINANCE) ? competitionRepository.findProjectSetupForInnovationLeadOrStakeholderOrCompetitionFinance(user.getId(), PageRequest.of(page, size)) : competitionRepository.findProjectSetup(PageRequest.of(page, size)); return handleCompetitionSearchResultPage(competitions, this::toProjectSetupCompetitionResult); }); } @Override ServiceResult<List<CompetitionSearchResultItem>> findLiveCompetitions(); @Override ServiceResult<CompetitionSearchResult> findProjectSetupCompetitions(int page, int size); @Override ServiceResult<List<CompetitionSearchResultItem>> findUpcomingCompetitions(); @Override ServiceResult<CompetitionSearchResult> findNonIfsCompetitions(int page, int size); @Override ServiceResult<CompetitionSearchResult> findPreviousCompetitions(int page, int size); @Override ServiceResult<CompetitionSearchResult> searchCompetitions(String searchQuery, int page, int size); @Override ServiceResult<CompetitionCountResource> countCompetitions(); } | @Test public void findProjectSetupCompetitions() { int page = 0; int size = 20; List<Competition> expectedCompetitions = newCompetition().build(2); when(competitionRepositoryMock.findProjectSetup(any())).thenReturn(new PageImpl<>(expectedCompetitions, PageRequest.of(page, size), 1L)); when(applicationRepository.findTopByCompetitionIdOrderByManageFundingEmailDateDesc(expectedCompetitions.get(0).getId())).thenReturn(Optional.of(newApplication().withManageFundingEmailDate(ZonedDateTime.now().minusDays(1)).build())); when(applicationRepository.findTopByCompetitionIdOrderByManageFundingEmailDateDesc(expectedCompetitions.get(1).getId())).thenReturn(Optional.of(newApplication().withManageFundingEmailDate(ZonedDateTime.now()).build())); CompetitionSearchResult response = service.findProjectSetupCompetitions(page, size).getSuccess(); assertCompetitionSearchResultsEqualToCompetitions(expectedCompetitions, response.getContent()); }
@Test public void findProjectSetupCompetitions_NoApplications() { int page = 0; int size = 20; List<Competition> expectedCompetitions = newCompetition().build(1); when(competitionRepositoryMock.findProjectSetup(any())).thenReturn(new PageImpl<>(expectedCompetitions, PageRequest.of(page, size), 1L)); when(applicationRepository.findTopByCompetitionIdOrderByManageFundingEmailDateDesc(expectedCompetitions.get(0).getId())).thenReturn(Optional.empty()); CompetitionSearchResult response = service.findProjectSetupCompetitions(page, size).getSuccess(); assertCompetitionSearchResultsEqualToCompetitions(expectedCompetitions, response.getContent()); }
@Test public void findProjectSetupCompetitionsWhenLoggedInAsStakeholder() { int page = 0; int size = 20; UserResource stakeholderUser = newUserResource().withId(1L).withRolesGlobal(singletonList(STAKEHOLDER)).build(); User user = newUser().withId(stakeholderUser.getId()).withRoles(singleton(STAKEHOLDER)).build(); setLoggedInUser(stakeholderUser); when(userRepositoryMock.findById(user.getId())).thenReturn(Optional.of(user)); List<Competition> expectedCompetitions = newCompetition().build(2); when(competitionRepositoryMock.findProjectSetupForInnovationLeadOrStakeholderOrCompetitionFinance(eq(stakeholderUser.getId()), any())).thenReturn(new PageImpl<>(expectedCompetitions, PageRequest.of(page, size), 1L)); when(applicationRepository.findTopByCompetitionIdOrderByManageFundingEmailDateDesc(expectedCompetitions.get(0).getId())).thenReturn(Optional.of(newApplication().withManageFundingEmailDate(ZonedDateTime.now().minusDays(1)).build())); when(applicationRepository.findTopByCompetitionIdOrderByManageFundingEmailDateDesc(expectedCompetitions.get(1).getId())).thenReturn(Optional.of(newApplication().withManageFundingEmailDate(ZonedDateTime.now()).build())); CompetitionSearchResult response = service.findProjectSetupCompetitions(page, size).getSuccess(); assertCompetitionSearchResultsEqualToCompetitions(expectedCompetitions, response.getContent()); verify(competitionRepositoryMock).findProjectSetupForInnovationLeadOrStakeholderOrCompetitionFinance(eq(stakeholderUser.getId()), any()); verify(competitionRepositoryMock, never()).findProjectSetup(any()); }
@Test public void findProjectSetupCompetitionsWhenLoggedInAsCompetitionFinance() { int page = 0; int size = 20; UserResource competitionFinanceUser = newUserResource().withId(1L).withRolesGlobal(singletonList(EXTERNAL_FINANCE)).build(); User user = newUser().withId(competitionFinanceUser.getId()).withRoles(singleton(EXTERNAL_FINANCE)).build(); setLoggedInUser(competitionFinanceUser); when(userRepositoryMock.findById(user.getId())).thenReturn(Optional.of(user)); List<Competition> expectedCompetitions = newCompetition().build(2); when(competitionRepositoryMock.findProjectSetupForInnovationLeadOrStakeholderOrCompetitionFinance(eq(competitionFinanceUser.getId()), any())).thenReturn(new PageImpl<>(expectedCompetitions, PageRequest.of(page, size), 1L)); when(applicationRepository.findTopByCompetitionIdOrderByManageFundingEmailDateDesc(expectedCompetitions.get(0).getId())).thenReturn(Optional.of(newApplication().withManageFundingEmailDate(ZonedDateTime.now().minusDays(1)).build())); when(applicationRepository.findTopByCompetitionIdOrderByManageFundingEmailDateDesc(expectedCompetitions.get(1).getId())).thenReturn(Optional.of(newApplication().withManageFundingEmailDate(ZonedDateTime.now()).build())); CompetitionSearchResult response = service.findProjectSetupCompetitions(page, size).getSuccess(); assertCompetitionSearchResultsEqualToCompetitions(expectedCompetitions, response.getContent()); verify(competitionRepositoryMock).findProjectSetupForInnovationLeadOrStakeholderOrCompetitionFinance(eq(competitionFinanceUser.getId()), any()); verify(competitionRepositoryMock, never()).findProjectSetup(any()); } |
CompetitionSearchServiceImpl extends BaseTransactionalService implements CompetitionSearchService { @Override public ServiceResult<List<CompetitionSearchResultItem>> findUpcomingCompetitions() { List<Competition> competitions = competitionRepository.findUpcoming(); return serviceSuccess(competitions.stream() .map(this::toUpcomingCompetitionResult) .collect(toList())); } @Override ServiceResult<List<CompetitionSearchResultItem>> findLiveCompetitions(); @Override ServiceResult<CompetitionSearchResult> findProjectSetupCompetitions(int page, int size); @Override ServiceResult<List<CompetitionSearchResultItem>> findUpcomingCompetitions(); @Override ServiceResult<CompetitionSearchResult> findNonIfsCompetitions(int page, int size); @Override ServiceResult<CompetitionSearchResult> findPreviousCompetitions(int page, int size); @Override ServiceResult<CompetitionSearchResult> searchCompetitions(String searchQuery, int page, int size); @Override ServiceResult<CompetitionCountResource> countCompetitions(); } | @Test public void findUpcomingCompetitions() { List<Competition> competitions = Lists.newArrayList(newCompetition().withId(competitionId).build()); when(competitionRepositoryMock.findUpcoming()).thenReturn(competitions); List<CompetitionSearchResultItem> response = service.findUpcomingCompetitions().getSuccess(); assertCompetitionSearchResultsEqualToCompetitions(competitions, response); } |
CompetitionSearchServiceImpl extends BaseTransactionalService implements CompetitionSearchService { @Override public ServiceResult<CompetitionSearchResult> findNonIfsCompetitions(int page, int size) { PageRequest pageRequest = PageRequest.of(page, size); Page<Competition> competitions = competitionRepository.findNonIfs(pageRequest); return handleCompetitionSearchResultPage(competitions, this::toNonIfsCompetitionSearchResult); } @Override ServiceResult<List<CompetitionSearchResultItem>> findLiveCompetitions(); @Override ServiceResult<CompetitionSearchResult> findProjectSetupCompetitions(int page, int size); @Override ServiceResult<List<CompetitionSearchResultItem>> findUpcomingCompetitions(); @Override ServiceResult<CompetitionSearchResult> findNonIfsCompetitions(int page, int size); @Override ServiceResult<CompetitionSearchResult> findPreviousCompetitions(int page, int size); @Override ServiceResult<CompetitionSearchResult> searchCompetitions(String searchQuery, int page, int size); @Override ServiceResult<CompetitionCountResource> countCompetitions(); } | @Test public void findNonIfsCompetitions() { int page = 0; int size = 20; List<Competition> competitions = Lists.newArrayList(newCompetition().withId(competitionId).build()); when(publicContentRepository.findByCompetitionId(competitionId)).thenReturn(newPublicContent().build()); when(competitionRepositoryMock.findNonIfs(any())).thenReturn(new PageImpl<>(competitions, PageRequest.of(page, size), 1L)); CompetitionSearchResult response = service.findNonIfsCompetitions(page, size).getSuccess(); assertCompetitionSearchResultsEqualToCompetitions(competitions, response.getContent()); } |
CompetitionSearchServiceImpl extends BaseTransactionalService implements CompetitionSearchService { @Override public ServiceResult<CompetitionSearchResult> findPreviousCompetitions(int page, int size) { return getCurrentlyLoggedInUser().andOnSuccess(user -> { Page<Competition> competitions = user.hasRole(INNOVATION_LEAD) || user.hasRole(STAKEHOLDER) || user.hasRole(EXTERNAL_FINANCE) ? competitionRepository.findPreviousForInnovationLeadOrStakeholderOrCompetitionFinance(user.getId(), PageRequest.of(page, size)) : competitionRepository.findPrevious(PageRequest.of(page, size)); return handleCompetitionSearchResultPage(competitions, this::toPreviousCompetitionSearchResult); }); } @Override ServiceResult<List<CompetitionSearchResultItem>> findLiveCompetitions(); @Override ServiceResult<CompetitionSearchResult> findProjectSetupCompetitions(int page, int size); @Override ServiceResult<List<CompetitionSearchResultItem>> findUpcomingCompetitions(); @Override ServiceResult<CompetitionSearchResult> findNonIfsCompetitions(int page, int size); @Override ServiceResult<CompetitionSearchResult> findPreviousCompetitions(int page, int size); @Override ServiceResult<CompetitionSearchResult> searchCompetitions(String searchQuery, int page, int size); @Override ServiceResult<CompetitionCountResource> countCompetitions(); } | @Test public void findPreviousCompetitions() { int page = 0; int size = 20; List<Competition> competitions = Lists.newArrayList(newCompetition().withId(competitionId).build(1)); when(competitionRepositoryMock.findPrevious(any())).thenReturn(new PageImpl<>(competitions, PageRequest.of(page, size), 30)); when(applicationRepository.countPrevious(competitionId)).thenReturn(1); when(projectRepositoryMock.countByApplicationCompetitionId(competitionId)).thenReturn(2); when(projectRepositoryMock.countByApplicationCompetitionIdAndProjectProcessActivityStateIn(competitionId, ProjectState.COMPLETED_STATES)).thenReturn(3); CompetitionSearchResult response = service.findPreviousCompetitions(page, size).getSuccess(); assertEquals((long) competitionId, response.getContent().get(0).getId()); assertEquals(1, ((PreviousCompetitionSearchResultItem) response.getContent().get(0)).getApplications()); assertEquals(2, ((PreviousCompetitionSearchResultItem) response.getContent().get(0)).getProjects()); assertEquals(3, ((PreviousCompetitionSearchResultItem) response.getContent().get(0)).getCompleteProjects()); }
@Test public void findPreviousCompetitionsWhenLoggedInAsCompetitionFinanceUser() { int page = 0; int size = 20; UserResource competitionFinanceUser = newUserResource().withId(1L).withRolesGlobal(singletonList(EXTERNAL_FINANCE)).build(); User user = newUser().withId(competitionFinanceUser.getId()).withRoles(singleton(EXTERNAL_FINANCE)).build(); setLoggedInUser(competitionFinanceUser); when(userRepositoryMock.findById(user.getId())).thenReturn(Optional.of(user)); List<Competition> competitions = Lists.newArrayList(newCompetition().withId(competitionId).build(1)); when(competitionRepositoryMock.findPreviousForInnovationLeadOrStakeholderOrCompetitionFinance(user.getId(), PageRequest.of(page, size))).thenReturn(new PageImpl<>(competitions, PageRequest.of(page, size), 30)); when(applicationRepository.countPrevious(competitionId)).thenReturn(1); when(projectRepositoryMock.countByApplicationCompetitionId(competitionId)).thenReturn(2); when(projectRepositoryMock.countByApplicationCompetitionIdAndProjectProcessActivityStateIn(competitionId, ProjectState.COMPLETED_STATES)).thenReturn(3); CompetitionSearchResult response = service.findPreviousCompetitions(page, size).getSuccess(); assertEquals((long) competitionId, response.getContent().get(0).getId()); assertEquals(1, ((PreviousCompetitionSearchResultItem) response.getContent().get(0)).getApplications()); assertEquals(2, ((PreviousCompetitionSearchResultItem) response.getContent().get(0)).getProjects()); assertEquals(3, ((PreviousCompetitionSearchResultItem) response.getContent().get(0)).getCompleteProjects()); } |
CompetitionSearchServiceImpl extends BaseTransactionalService implements CompetitionSearchService { @Override public ServiceResult<CompetitionCountResource> countCompetitions() { return serviceSuccess( new CompetitionCountResource( getLiveCount(), getPSCount(), competitionRepository.countUpcoming(), getFeedbackReleasedCount(), competitionRepository.countNonIfs())); } @Override ServiceResult<List<CompetitionSearchResultItem>> findLiveCompetitions(); @Override ServiceResult<CompetitionSearchResult> findProjectSetupCompetitions(int page, int size); @Override ServiceResult<List<CompetitionSearchResultItem>> findUpcomingCompetitions(); @Override ServiceResult<CompetitionSearchResult> findNonIfsCompetitions(int page, int size); @Override ServiceResult<CompetitionSearchResult> findPreviousCompetitions(int page, int size); @Override ServiceResult<CompetitionSearchResult> searchCompetitions(String searchQuery, int page, int size); @Override ServiceResult<CompetitionCountResource> countCompetitions(); } | @Test public void countCompetitions() { Long countLive = 1L; Long countProjectSetup = 2L; Long countUpcoming = 3L; Long countFeedbackReleased = 4L; when(competitionRepositoryMock.countLive()).thenReturn(countLive); when(competitionRepositoryMock.countProjectSetup()).thenReturn(countProjectSetup); when(competitionRepositoryMock.countUpcoming()).thenReturn(countUpcoming); when(competitionRepositoryMock.countPrevious()).thenReturn(countFeedbackReleased); CompetitionCountResource response = service.countCompetitions().getSuccess(); assertEquals(countLive, response.getLiveCount()); assertEquals(countProjectSetup, response.getProjectSetupCount()); assertEquals(countUpcoming, response.getUpcomingCount()); assertEquals(countFeedbackReleased, response.getFeedbackReleasedCount()); UserResource innovationLeadUser = newUserResource().withRolesGlobal(singletonList(INNOVATION_LEAD)).build(); setLoggedInUser(innovationLeadUser); when(competitionRepositoryMock.countLiveForInnovationLeadOrStakeholder(innovationLeadUser.getId())).thenReturn(countLive); when(competitionRepositoryMock.countProjectSetupForInnovationLeadOrStakeholder(innovationLeadUser.getId())).thenReturn(countProjectSetup); when(competitionRepositoryMock.countPreviousForInnovationLeadOrStakeholder(innovationLeadUser.getId())).thenReturn(countFeedbackReleased); when(userRepositoryMock.findById(innovationLeadUser.getId())).thenReturn(Optional.of(newUser().withId(innovationLeadUser.getId()).withRoles(singleton(Role.INNOVATION_LEAD)).build())); response = service.countCompetitions().getSuccess(); assertEquals(countLive, response.getLiveCount()); assertEquals(countProjectSetup, response.getProjectSetupCount()); assertEquals(countUpcoming, response.getUpcomingCount()); assertEquals(countFeedbackReleased, response.getFeedbackReleasedCount()); UserResource stakeholderUser = newUserResource().withRolesGlobal(singletonList(Role.STAKEHOLDER)).build(); setLoggedInUser(stakeholderUser); when(competitionRepositoryMock.countLiveForInnovationLeadOrStakeholder(stakeholderUser.getId())).thenReturn(countLive); when(competitionRepositoryMock.countProjectSetupForInnovationLeadOrStakeholder(stakeholderUser.getId())).thenReturn(countProjectSetup); when(competitionRepositoryMock.countPreviousForInnovationLeadOrStakeholder(stakeholderUser.getId())).thenReturn(countFeedbackReleased); when(userRepositoryMock.findById(stakeholderUser.getId())).thenReturn(Optional.of(newUser().withId(stakeholderUser.getId()).withRoles(singleton(Role.STAKEHOLDER)).build())); response = service.countCompetitions().getSuccess(); assertEquals(countLive, response.getLiveCount()); assertEquals(countProjectSetup, response.getProjectSetupCount()); assertEquals(countUpcoming, response.getUpcomingCount()); assertEquals(countFeedbackReleased, response.getFeedbackReleasedCount()); } |
CompetitionSearchServiceImpl extends BaseTransactionalService implements CompetitionSearchService { @Override public ServiceResult<CompetitionSearchResult> searchCompetitions(String searchQuery, int page, int size) { String searchQueryLike = "%" + searchQuery + "%"; PageRequest pageRequest = PageRequest.of(page, size); return getCurrentlyLoggedInUser().andOnSuccess(user -> { if (user.hasRole(INNOVATION_LEAD) || user.hasRole(STAKEHOLDER)) { return handleCompetitionSearchResultPage(competitionRepository.searchForInnovationLeadOrStakeholder(searchQueryLike, user.getId(), pageRequest), this::searchResultFromCompetition); } else if (user.hasRole(SUPPORT)) { return handleCompetitionSearchResultPage(competitionRepository.searchForSupportUser(searchQueryLike, pageRequest), this::searchResultFromCompetition); } return handleCompetitionSearchResultPage(competitionRepository.search(searchQueryLike, pageRequest), this::searchResultFromCompetition); }); } @Override ServiceResult<List<CompetitionSearchResultItem>> findLiveCompetitions(); @Override ServiceResult<CompetitionSearchResult> findProjectSetupCompetitions(int page, int size); @Override ServiceResult<List<CompetitionSearchResultItem>> findUpcomingCompetitions(); @Override ServiceResult<CompetitionSearchResult> findNonIfsCompetitions(int page, int size); @Override ServiceResult<CompetitionSearchResult> findPreviousCompetitions(int page, int size); @Override ServiceResult<CompetitionSearchResult> searchCompetitions(String searchQuery, int page, int size); @Override ServiceResult<CompetitionCountResource> countCompetitions(); } | @Test public void searchCompetitions() { String searchQuery = "SearchQuery"; String searchLike = "%" + searchQuery + "%"; String competitionType = "Comp type"; int page = 1; int size = 20; PageRequest pageRequest = PageRequest.of(page, size); Page<Competition> queryResponse = mock(Page.class); long totalElements = 2L; int totalPages = 1; ZonedDateTime openDate = ZonedDateTime.now(); Milestone openDateMilestone = newMilestone().withType(MilestoneType.OPEN_DATE).withDate(openDate).build(); Competition competition = newCompetition().withId(competitionId).withCompetitionType(newCompetitionType().withName(competitionType).build()).withMilestones(asList(openDateMilestone)).build(); when(queryResponse.getTotalElements()).thenReturn(totalElements); when(queryResponse.getTotalPages()).thenReturn(totalPages); when(queryResponse.getNumber()).thenReturn(page); when(queryResponse.getNumberOfElements()).thenReturn(size); when(queryResponse.getContent()).thenReturn(singletonList(competition)); when(queryResponse.getPageable()).thenReturn(pageRequest); when(competitionRepositoryMock.search(searchLike, pageRequest)).thenReturn(queryResponse); CompetitionSearchResult response = service.searchCompetitions(searchQuery, page, size).getSuccess(); assertEquals(totalElements, response.getTotalElements()); assertEquals(totalPages, response.getTotalPages()); assertEquals(page, response.getNumber()); assertEquals(size, response.getSize()); CompetitionSearchResultItem expectedSearchResult = new UpcomingCompetitionSearchResultItem(competition.getId(), competition.getName(), CompetitionStatus.COMPETITION_SETUP, competitionType, EMPTY_SET, openDate.format(DateTimeFormatter.ofPattern("dd/MM/YYYY"))); assertEquals(expectedSearchResult.getId(), (long) competition.getId()); }
@Test public void searchCompetitionsAsLeadTechnologist() { long totalElements = 2L; int totalPages = 1; int page = 1; int size = 20; String searchQuery = "SearchQuery"; String competitionType = "Comp type"; Competition competition = newCompetition().withId(competitionId).withCompetitionType(newCompetitionType().withName(competitionType).build()).build(); UserResource userResource = newUserResource().withRolesGlobal(singletonList(Role.INNOVATION_LEAD)).build(); User user = newUser().withId(userResource.getId()).withRoles(singleton(Role.INNOVATION_LEAD)).build(); searchCompetitionsMocking(totalElements, totalPages, page, size, searchQuery, competition, userResource, user); CompetitionSearchResult response = service.searchCompetitions(searchQuery, page, size).getSuccess(); searchCompetitionsAssertions(totalElements, totalPages, page, size, competitionType, competition, response); verify(competitionRepositoryMock).searchForInnovationLeadOrStakeholder(any(), anyLong(), any()); verify(competitionRepositoryMock, never()).searchForSupportUser(any(), any()); verify(competitionRepositoryMock, never()).search(any(), any()); }
@Test public void searchCompetitionsAsStakeholder() { long totalElements = 2L; int totalPages = 1; int page = 1; int size = 20; String searchQuery = "SearchQuery"; String competitionType = "Comp type"; Competition competition = newCompetition().withId(competitionId).withCompetitionType(newCompetitionType().withName(competitionType).build()).build(); UserResource userResource = newUserResource().withRolesGlobal(singletonList(Role.STAKEHOLDER)).build(); User user = newUser().withId(userResource.getId()).withRoles(singleton(Role.STAKEHOLDER)).build(); searchCompetitionsMocking(totalElements, totalPages, page, size, searchQuery, competition, userResource, user); CompetitionSearchResult response = service.searchCompetitions(searchQuery, page, size).getSuccess(); searchCompetitionsAssertions(totalElements, totalPages, page, size, competitionType, competition, response); verify(competitionRepositoryMock).searchForInnovationLeadOrStakeholder(any(), anyLong(), any()); verify(competitionRepositoryMock, never()).searchForSupportUser(any(), any()); verify(competitionRepositoryMock, never()).search(any(), any()); }
@Test public void searchCompetitionsAsSupportUser() { long totalElements = 2L; int totalPages = 1; int page = 1; int size = 20; String searchQuery = "SearchQuery"; String competitionType = "Comp type"; Competition competition = newCompetition().withId(competitionId).withCompetitionType(newCompetitionType().withName(competitionType).build()).build(); UserResource userResource = newUserResource().withRolesGlobal(singletonList(Role.SUPPORT)).build(); User user = newUser().withId(userResource.getId()).withRoles(singleton(Role.SUPPORT)).build(); searchCompetitionsMocking(totalElements, totalPages, page, size, searchQuery, competition, userResource, user); CompetitionSearchResult response = service.searchCompetitions(searchQuery, page, size).getSuccess(); searchCompetitionsAssertions(totalElements, totalPages, page, size, competitionType, competition, response); verify(competitionRepositoryMock, never()).searchForInnovationLeadOrStakeholder(any(), anyLong(), any()); verify(competitionRepositoryMock).searchForSupportUser(any(), any()); verify(competitionRepositoryMock, never()).search(any(), any()); } |
CompetitionServiceImpl extends BaseTransactionalService implements CompetitionService { @Override public ServiceResult<CompetitionResource> getCompetitionById(long id) { return findCompetitionById(id).andOnSuccess(comp -> serviceSuccess(competitionMapper.mapToResource(comp))); } @Override ServiceResult<CompetitionResource> getCompetitionById(long id); @Override ServiceResult<CompetitionResource> getCompetitionByApplicationId(long applicationId); @Override ServiceResult<CompetitionResource> getCompetitionByProjectId(long projectId); @Override ServiceResult<List<OrganisationTypeResource>> getCompetitionOrganisationTypes(long id); @Override ServiceResult<List<CompetitionResource>> findAll(); @Override @Transactional ServiceResult<Void> closeAssessment(long competitionId); @Override @Transactional ServiceResult<Void> notifyAssessors(long competitionId); @Override @Transactional ServiceResult<Void> releaseFeedback(long competitionId); @Override @Transactional ServiceResult<Void> manageInformState(long competitionId); @Override ServiceResult<List<CompetitionOpenQueryResource>> findAllOpenQueries(long competitionId); @Override ServiceResult<Long> countAllOpenQueries(long competitionId); @Override ServiceResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(long competitionId); @Override ServiceResult<Long> countPendingSpendProfiles(long competitionId); @Override @Transactional ServiceResult<Void> updateTermsAndConditionsForCompetition(long competitionId, long termsAndConditionsId); @Override ServiceResult<FileAndContents> downloadTerms(long competitionId); } | @Test public void getCompetitionById() { Competition competition = new Competition(); CompetitionResource resource = new CompetitionResource(); when(competitionRepositoryMock.findById(competitionId)).thenReturn(Optional.of(competition)); when(competitionMapperMock.mapToResource(competition)).thenReturn(resource); CompetitionResource response = service.getCompetitionById(competitionId).getSuccess(); assertEquals(resource, response); } |
PublicContentItemServiceImpl extends BaseTransactionalService implements PublicContentItemService { @Override public ServiceResult<PublicContentItemResource> byCompetitionId(Long competitionId) { Optional<Competition> competition = competitionRepository.findById(competitionId); PublicContent publicContent = publicContentRepository.findByCompetitionId(competitionId); if(!competition.isPresent() || null == publicContent) { return ServiceResult.serviceFailure(new Error(GENERAL_NOT_FOUND)); } return ServiceResult.serviceSuccess(mapPublicContentToPublicContentItemResource(publicContent, competition.get())); } @Override ServiceResult<PublicContentItemPageResource> findFilteredItems(Optional<Long> innovationAreaId, Optional<String> searchString, Optional<Integer> pageNumber, Integer pageSize); @Override ServiceResult<PublicContentItemResource> byCompetitionId(Long competitionId); static final Integer MAX_ALLOWED_KEYWORDS; } | @Test public void testByCompetitionId() { Long competitionId = 4L; Competition competition = newCompetition().withNonIfs(false).withId(competitionId).withSetupComplete(true) .withMilestones(newMilestone() .withDate(LocalDateTime.of(2017,1,2,3,4).atZone(ZoneId.systemDefault()), LocalDateTime.of(2017,3,2,1,4).atZone(ZoneId.systemDefault())) .withType(MilestoneType.OPEN_DATE, MilestoneType.SUBMISSION_DATE) .build(2) ).build(); PublicContent publicContent = newPublicContent().withCompetitionId(competitionId).build(); PublicContentResource publicContentResource = newPublicContentResource().withCompetitionId(competitionId).build(); when(competitionRepository.findById(competitionId)).thenReturn(Optional.of(competition)); when(publicContentRepository.findByCompetitionId(competitionId)).thenReturn(publicContent); when(publicContentMapper.mapToResource(publicContent)).thenReturn(publicContentResource); ServiceResult<PublicContentItemResource> result = service.byCompetitionId(competitionId); assertTrue(result.isSuccess()); PublicContentItemResource resultObject = result.getSuccess(); assertEquals(competition.getEndDate(), resultObject.getCompetitionCloseDate()); assertEquals(competition.getStartDate(), resultObject.getCompetitionOpenDate()); assertEquals(competition.getName(), resultObject.getCompetitionTitle()); assertEquals(publicContentResource, resultObject.getPublicContentResource()); assertEquals(competition.getSetupComplete(), resultObject.getSetupComplete()); verify(publicContentRepository, only()).findByCompetitionId(competitionId); verify(competitionRepository, only()).findById(competitionId); }
@Test public void testByCompetitionIdNonIfs() { Long competitionId = 4L; Competition competition = newCompetition().withNonIfs(true).withId(competitionId).withSetupComplete(true).withMilestones( newMilestone() .withDate(ZonedDateTime.of(2017,1,2,3,4,0,0,ZoneId.systemDefault()), ZonedDateTime.of(2017,2,1,3,4,0,0,ZoneId.systemDefault()), ZonedDateTime.of(2017,3,2,1,4,0,0,ZoneId.systemDefault())) .withType(MilestoneType.OPEN_DATE, MilestoneType.REGISTRATION_DATE, MilestoneType.SUBMISSION_DATE) .build(2) ).build(); PublicContent publicContent = newPublicContent().withCompetitionId(competitionId).build(); PublicContentResource publicContentResource = newPublicContentResource().withCompetitionId(competitionId).build(); when(competitionRepository.findById(competitionId)).thenReturn(Optional.of(competition)); when(publicContentRepository.findByCompetitionId(competitionId)).thenReturn(publicContent); when(publicContentMapper.mapToResource(publicContent)).thenReturn(publicContentResource); ServiceResult<PublicContentItemResource> result = service.byCompetitionId(competitionId); assertTrue(result.isSuccess()); PublicContentItemResource resultObject = result.getSuccess(); assertEquals(competition.getEndDate(), resultObject.getCompetitionCloseDate()); assertEquals(competition.getStartDate(), resultObject.getCompetitionOpenDate()); assertEquals(competition.getRegistrationDate(), resultObject.getRegistrationCloseDate()); assertEquals(competition.getName(), resultObject.getCompetitionTitle()); assertEquals(publicContentResource, resultObject.getPublicContentResource()); assertEquals(true, resultObject.getSetupComplete()); verify(publicContentRepository, only()).findByCompetitionId(competitionId); verify(competitionRepository, only()).findById(competitionId); }
@Test public void testByCompetitionIdFailure() { Long competitionId = 4L; when(competitionRepository.findById(competitionId)).thenReturn(Optional.empty()); when(publicContentRepository.findByCompetitionId(competitionId)).thenReturn(null); ServiceResult<PublicContentItemResource> result = service.byCompetitionId(competitionId); assertTrue(result.isFailure()); verify(publicContentRepository, only()).findByCompetitionId(competitionId); verify(competitionRepository, only()).findById(competitionId); } |
CompetitionServiceImpl extends BaseTransactionalService implements CompetitionService { @Override public ServiceResult<CompetitionResource> getCompetitionByApplicationId(long applicationId) { return findCompetitionByApplicationId(applicationId).andOnSuccess(comp -> serviceSuccess(competitionMapper.mapToResource(comp))); } @Override ServiceResult<CompetitionResource> getCompetitionById(long id); @Override ServiceResult<CompetitionResource> getCompetitionByApplicationId(long applicationId); @Override ServiceResult<CompetitionResource> getCompetitionByProjectId(long projectId); @Override ServiceResult<List<OrganisationTypeResource>> getCompetitionOrganisationTypes(long id); @Override ServiceResult<List<CompetitionResource>> findAll(); @Override @Transactional ServiceResult<Void> closeAssessment(long competitionId); @Override @Transactional ServiceResult<Void> notifyAssessors(long competitionId); @Override @Transactional ServiceResult<Void> releaseFeedback(long competitionId); @Override @Transactional ServiceResult<Void> manageInformState(long competitionId); @Override ServiceResult<List<CompetitionOpenQueryResource>> findAllOpenQueries(long competitionId); @Override ServiceResult<Long> countAllOpenQueries(long competitionId); @Override ServiceResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(long competitionId); @Override ServiceResult<Long> countPendingSpendProfiles(long competitionId); @Override @Transactional ServiceResult<Void> updateTermsAndConditionsForCompetition(long competitionId, long termsAndConditionsId); @Override ServiceResult<FileAndContents> downloadTerms(long competitionId); } | @Test public void getCompetitionByApplicationId() { long applicationId = 456; Competition competition = new Competition(); Application application = newApplication().withCompetition(competition).build(); CompetitionResource resource = new CompetitionResource(); when(applicationRepositoryMock.findById(applicationId)).thenReturn(Optional.of(application)); when(competitionMapperMock.mapToResource(competition)).thenReturn(resource); CompetitionResource response = service.getCompetitionByApplicationId(applicationId).getSuccess(); assertEquals(resource, response); } |
CompetitionServiceImpl extends BaseTransactionalService implements CompetitionService { @Override public ServiceResult<CompetitionResource> getCompetitionByProjectId(long projectId) { return findCompetitionByProjectId(projectId).andOnSuccess(comp -> serviceSuccess(competitionMapper.mapToResource(comp))); } @Override ServiceResult<CompetitionResource> getCompetitionById(long id); @Override ServiceResult<CompetitionResource> getCompetitionByApplicationId(long applicationId); @Override ServiceResult<CompetitionResource> getCompetitionByProjectId(long projectId); @Override ServiceResult<List<OrganisationTypeResource>> getCompetitionOrganisationTypes(long id); @Override ServiceResult<List<CompetitionResource>> findAll(); @Override @Transactional ServiceResult<Void> closeAssessment(long competitionId); @Override @Transactional ServiceResult<Void> notifyAssessors(long competitionId); @Override @Transactional ServiceResult<Void> releaseFeedback(long competitionId); @Override @Transactional ServiceResult<Void> manageInformState(long competitionId); @Override ServiceResult<List<CompetitionOpenQueryResource>> findAllOpenQueries(long competitionId); @Override ServiceResult<Long> countAllOpenQueries(long competitionId); @Override ServiceResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(long competitionId); @Override ServiceResult<Long> countPendingSpendProfiles(long competitionId); @Override @Transactional ServiceResult<Void> updateTermsAndConditionsForCompetition(long competitionId, long termsAndConditionsId); @Override ServiceResult<FileAndContents> downloadTerms(long competitionId); } | @Test public void getCompetitionByProjectId() { long projectId = 456; Competition competition = new Competition(); Application application = newApplication().withCompetition(competition).build(); Project project = newProject().withApplication(application).build(); CompetitionResource resource = new CompetitionResource(); when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.of(project)); when(competitionMapperMock.mapToResource(competition)).thenReturn(resource); CompetitionResource response = service.getCompetitionByProjectId(projectId).getSuccess(); assertEquals(resource, response); } |
CompetitionServiceImpl extends BaseTransactionalService implements CompetitionService { @Override public ServiceResult<List<CompetitionResource>> findAll() { return serviceSuccess((List) competitionMapper.mapToResource( competitionRepository.findAll().stream().filter(comp -> !comp.isTemplate()).collect(toList()) )); } @Override ServiceResult<CompetitionResource> getCompetitionById(long id); @Override ServiceResult<CompetitionResource> getCompetitionByApplicationId(long applicationId); @Override ServiceResult<CompetitionResource> getCompetitionByProjectId(long projectId); @Override ServiceResult<List<OrganisationTypeResource>> getCompetitionOrganisationTypes(long id); @Override ServiceResult<List<CompetitionResource>> findAll(); @Override @Transactional ServiceResult<Void> closeAssessment(long competitionId); @Override @Transactional ServiceResult<Void> notifyAssessors(long competitionId); @Override @Transactional ServiceResult<Void> releaseFeedback(long competitionId); @Override @Transactional ServiceResult<Void> manageInformState(long competitionId); @Override ServiceResult<List<CompetitionOpenQueryResource>> findAllOpenQueries(long competitionId); @Override ServiceResult<Long> countAllOpenQueries(long competitionId); @Override ServiceResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(long competitionId); @Override ServiceResult<Long> countPendingSpendProfiles(long competitionId); @Override @Transactional ServiceResult<Void> updateTermsAndConditionsForCompetition(long competitionId, long termsAndConditionsId); @Override ServiceResult<FileAndContents> downloadTerms(long competitionId); } | @Test public void findAll() { List<Competition> competitions = Lists.newArrayList(new Competition()); List<CompetitionResource> resources = Lists.newArrayList(new CompetitionResource()); when(competitionRepositoryMock.findAll()).thenReturn(competitions); when(competitionMapperMock.mapToResource(competitions)).thenReturn(resources); List<CompetitionResource> response = service.findAll().getSuccess(); assertEquals(resources, response); } |
CompetitionServiceImpl extends BaseTransactionalService implements CompetitionService { @Override @Transactional public ServiceResult<Void> closeAssessment(long competitionId) { Competition competition = competitionRepository.findById(competitionId).get(); competition.closeAssessment(ZonedDateTime.now()); return serviceSuccess(); } @Override ServiceResult<CompetitionResource> getCompetitionById(long id); @Override ServiceResult<CompetitionResource> getCompetitionByApplicationId(long applicationId); @Override ServiceResult<CompetitionResource> getCompetitionByProjectId(long projectId); @Override ServiceResult<List<OrganisationTypeResource>> getCompetitionOrganisationTypes(long id); @Override ServiceResult<List<CompetitionResource>> findAll(); @Override @Transactional ServiceResult<Void> closeAssessment(long competitionId); @Override @Transactional ServiceResult<Void> notifyAssessors(long competitionId); @Override @Transactional ServiceResult<Void> releaseFeedback(long competitionId); @Override @Transactional ServiceResult<Void> manageInformState(long competitionId); @Override ServiceResult<List<CompetitionOpenQueryResource>> findAllOpenQueries(long competitionId); @Override ServiceResult<Long> countAllOpenQueries(long competitionId); @Override ServiceResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(long competitionId); @Override ServiceResult<Long> countPendingSpendProfiles(long competitionId); @Override @Transactional ServiceResult<Void> updateTermsAndConditionsForCompetition(long competitionId, long termsAndConditionsId); @Override ServiceResult<FileAndContents> downloadTerms(long competitionId); } | @Test public void closeAssessment() { List<Milestone> milestones = newMilestone() .withDate(ZonedDateTime.now().minusDays(1)) .withType(OPEN_DATE, SUBMISSION_DATE, ASSESSORS_NOTIFIED).build(3); milestones.addAll(newMilestone() .withDate(ZonedDateTime.now().plusDays(1)) .withType(NOTIFICATIONS, ASSESSOR_DEADLINE) .build(2)); Competition competition = newCompetition().withSetupComplete(true) .withMilestones(milestones) .build(); when(competitionRepositoryMock.findById(competitionId)).thenReturn(Optional.of(competition)); service.closeAssessment(competitionId); assertEquals(CompetitionStatus.FUNDERS_PANEL, competition.getCompetitionStatus()); } |
CompetitionServiceImpl extends BaseTransactionalService implements CompetitionService { @Override @Transactional public ServiceResult<Void> notifyAssessors(long competitionId) { Competition competition = competitionRepository.findById(competitionId).get(); competition.notifyAssessors(ZonedDateTime.now()); return serviceSuccess(); } @Override ServiceResult<CompetitionResource> getCompetitionById(long id); @Override ServiceResult<CompetitionResource> getCompetitionByApplicationId(long applicationId); @Override ServiceResult<CompetitionResource> getCompetitionByProjectId(long projectId); @Override ServiceResult<List<OrganisationTypeResource>> getCompetitionOrganisationTypes(long id); @Override ServiceResult<List<CompetitionResource>> findAll(); @Override @Transactional ServiceResult<Void> closeAssessment(long competitionId); @Override @Transactional ServiceResult<Void> notifyAssessors(long competitionId); @Override @Transactional ServiceResult<Void> releaseFeedback(long competitionId); @Override @Transactional ServiceResult<Void> manageInformState(long competitionId); @Override ServiceResult<List<CompetitionOpenQueryResource>> findAllOpenQueries(long competitionId); @Override ServiceResult<Long> countAllOpenQueries(long competitionId); @Override ServiceResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(long competitionId); @Override ServiceResult<Long> countPendingSpendProfiles(long competitionId); @Override @Transactional ServiceResult<Void> updateTermsAndConditionsForCompetition(long competitionId, long termsAndConditionsId); @Override ServiceResult<FileAndContents> downloadTerms(long competitionId); } | @Test public void notifyAssessors() { List<Milestone> milestones = newMilestone() .withDate(ZonedDateTime.now().minusDays(1)) .withType(OPEN_DATE, SUBMISSION_DATE, ALLOCATE_ASSESSORS).build(3); milestones.addAll(newMilestone() .withDate(ZonedDateTime.now().plusDays(1)) .withType(ASSESSMENT_CLOSED) .build(1)); Competition competition = newCompetition().withSetupComplete(true) .withMilestones(milestones) .build(); when(competitionRepositoryMock.findById(competitionId)).thenReturn(Optional.of(competition)); service.notifyAssessors(competitionId); assertEquals(CompetitionStatus.IN_ASSESSMENT, competition.getCompetitionStatus()); } |
CompetitionServiceImpl extends BaseTransactionalService implements CompetitionService { @Override @Transactional public ServiceResult<Void> releaseFeedback(long competitionId) { CompetitionFundedKeyApplicationStatisticsResource keyStatisticsResource = competitionKeyApplicationStatisticsService.getFundedKeyStatisticsByCompetition(competitionId) .getSuccess(); if (keyStatisticsResource.isCanReleaseFeedback()) { Competition competition = competitionRepository.findById(competitionId).get(); competition.releaseFeedback(ZonedDateTime.now()); return serviceSuccess(); } else { return serviceFailure(new Error(COMPETITION_CANNOT_RELEASE_FEEDBACK)); } } @Override ServiceResult<CompetitionResource> getCompetitionById(long id); @Override ServiceResult<CompetitionResource> getCompetitionByApplicationId(long applicationId); @Override ServiceResult<CompetitionResource> getCompetitionByProjectId(long projectId); @Override ServiceResult<List<OrganisationTypeResource>> getCompetitionOrganisationTypes(long id); @Override ServiceResult<List<CompetitionResource>> findAll(); @Override @Transactional ServiceResult<Void> closeAssessment(long competitionId); @Override @Transactional ServiceResult<Void> notifyAssessors(long competitionId); @Override @Transactional ServiceResult<Void> releaseFeedback(long competitionId); @Override @Transactional ServiceResult<Void> manageInformState(long competitionId); @Override ServiceResult<List<CompetitionOpenQueryResource>> findAllOpenQueries(long competitionId); @Override ServiceResult<Long> countAllOpenQueries(long competitionId); @Override ServiceResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(long competitionId); @Override ServiceResult<Long> countPendingSpendProfiles(long competitionId); @Override @Transactional ServiceResult<Void> updateTermsAndConditionsForCompetition(long competitionId, long termsAndConditionsId); @Override ServiceResult<FileAndContents> downloadTerms(long competitionId); } | @Test public void releaseFeedback() { List<Milestone> milestones = newMilestone() .withDate(ZonedDateTime.now().minusDays(1)) .withType(OPEN_DATE, SUBMISSION_DATE, ALLOCATE_ASSESSORS, ASSESSORS_NOTIFIED, ASSESSMENT_CLOSED, ASSESSMENT_PANEL, PANEL_DATE, FUNDERS_PANEL, NOTIFICATIONS) .build(9); milestones.addAll(newMilestone() .withDate(ZonedDateTime.now().plusDays(1)) .withType(RELEASE_FEEDBACK) .build(1)); CompetitionType competitionType = newCompetitionType() .withName("Sector") .build(); Competition competition = newCompetition() .withSetupComplete(true) .withCompetitionType(competitionType) .withMilestones(milestones) .build(); CompetitionFundedKeyApplicationStatisticsResource keyStatistics = new CompetitionFundedKeyApplicationStatisticsResource(); keyStatistics.setApplicationsAwaitingDecision(0); keyStatistics.setApplicationsSubmitted(5); keyStatistics.setApplicationsNotifiedOfDecision(5); when(competitionRepositoryMock.findById(competitionId)).thenReturn(Optional.of(competition)); when(competitionKeyApplicationStatisticsServiceMock.getFundedKeyStatisticsByCompetition(competitionId)) .thenReturn(serviceSuccess(keyStatistics)); ServiceResult<Void> response = service.releaseFeedback(competitionId); assertTrue(response.isSuccess()); assertEquals(CompetitionStatus.PROJECT_SETUP, competition.getCompetitionStatus()); }
@Test public void releaseFeedback_cantRelease() { List<Milestone> milestones = newMilestone() .withDate(ZonedDateTime.now().minusDays(1)) .withType(OPEN_DATE, SUBMISSION_DATE, ALLOCATE_ASSESSORS, ASSESSORS_NOTIFIED, ASSESSMENT_CLOSED, ASSESSMENT_PANEL, PANEL_DATE, FUNDERS_PANEL, NOTIFICATIONS) .build(9); milestones.addAll(newMilestone() .withDate(ZonedDateTime.now().plusDays(1)) .withType(RELEASE_FEEDBACK) .build(1)); Competition competition = newCompetition().withSetupComplete(true) .withMilestones(milestones) .build(); CompetitionFundedKeyApplicationStatisticsResource keyStatistics = new CompetitionFundedKeyApplicationStatisticsResource(); keyStatistics.setApplicationsAwaitingDecision(0); keyStatistics.setApplicationsSubmitted(5); keyStatistics.setApplicationsNotifiedOfDecision(4); when(competitionRepositoryMock.findById(competitionId)).thenReturn(Optional.of(competition)); when(competitionKeyApplicationStatisticsServiceMock.getFundedKeyStatisticsByCompetition(competitionId)) .thenReturn(serviceSuccess(keyStatistics)); ServiceResult<Void> response = service.releaseFeedback(competitionId); assertTrue(response.isFailure()); assertTrue(response.getFailure().is(new Error(COMPETITION_CANNOT_RELEASE_FEEDBACK))); assertEquals(CompetitionStatus.ASSESSOR_FEEDBACK, competition.getCompetitionStatus()); } |
CompetitionServiceImpl extends BaseTransactionalService implements CompetitionService { @Override @Transactional public ServiceResult<Void> manageInformState(long competitionId) { CompetitionFundedKeyApplicationStatisticsResource keyStatisticsResource = competitionKeyApplicationStatisticsService.getFundedKeyStatisticsByCompetition(competitionId) .getSuccess(); if (keyStatisticsResource.isCanReleaseFeedback()) { Competition competition = competitionRepository.findById(competitionId).get(); competition.setFundersPanelEndDate(ZonedDateTime.now()); } return serviceSuccess(); } @Override ServiceResult<CompetitionResource> getCompetitionById(long id); @Override ServiceResult<CompetitionResource> getCompetitionByApplicationId(long applicationId); @Override ServiceResult<CompetitionResource> getCompetitionByProjectId(long projectId); @Override ServiceResult<List<OrganisationTypeResource>> getCompetitionOrganisationTypes(long id); @Override ServiceResult<List<CompetitionResource>> findAll(); @Override @Transactional ServiceResult<Void> closeAssessment(long competitionId); @Override @Transactional ServiceResult<Void> notifyAssessors(long competitionId); @Override @Transactional ServiceResult<Void> releaseFeedback(long competitionId); @Override @Transactional ServiceResult<Void> manageInformState(long competitionId); @Override ServiceResult<List<CompetitionOpenQueryResource>> findAllOpenQueries(long competitionId); @Override ServiceResult<Long> countAllOpenQueries(long competitionId); @Override ServiceResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(long competitionId); @Override ServiceResult<Long> countPendingSpendProfiles(long competitionId); @Override @Transactional ServiceResult<Void> updateTermsAndConditionsForCompetition(long competitionId, long termsAndConditionsId); @Override ServiceResult<FileAndContents> downloadTerms(long competitionId); } | @Test public void manageInformState() { List<Milestone> milestones = newMilestone() .withDate(ZonedDateTime.now().minusDays(1)) .withType(OPEN_DATE, SUBMISSION_DATE, ALLOCATE_ASSESSORS, ASSESSORS_NOTIFIED, ASSESSMENT_CLOSED, ASSESSMENT_PANEL, PANEL_DATE, FUNDERS_PANEL) .build(9); milestones.addAll(newMilestone() .withDate(ZonedDateTime.now().plusDays(1)) .withType(RELEASE_FEEDBACK) .build(1)); Competition competition = newCompetition().withSetupComplete(true) .withMilestones(milestones) .build(); assertEquals(CompetitionStatus.FUNDERS_PANEL, competition.getCompetitionStatus()); CompetitionFundedKeyApplicationStatisticsResource keyStatistics = new CompetitionFundedKeyApplicationStatisticsResource(); keyStatistics.setApplicationsAwaitingDecision(0); keyStatistics.setApplicationsSubmitted(5); keyStatistics.setApplicationsNotifiedOfDecision(5); when(competitionRepositoryMock.findById(competitionId)).thenReturn(Optional.of(competition)); when(competitionKeyApplicationStatisticsServiceMock.getFundedKeyStatisticsByCompetition(competitionId)) .thenReturn(serviceSuccess(keyStatistics)); ServiceResult<Void> response = service.manageInformState(competitionId); assertTrue(response.isSuccess()); assertEquals(CompetitionStatus.ASSESSOR_FEEDBACK, competition.getCompetitionStatus()); }
@Test public void manageInformState_noStateChange() { List<Milestone> milestones = newMilestone() .withDate(ZonedDateTime.now().minusDays(1)) .withType(OPEN_DATE, SUBMISSION_DATE, ALLOCATE_ASSESSORS, ASSESSORS_NOTIFIED, ASSESSMENT_CLOSED, ASSESSMENT_PANEL, PANEL_DATE, FUNDERS_PANEL) .build(9); milestones.addAll(newMilestone() .withDate(ZonedDateTime.now().plusDays(1)) .withType(RELEASE_FEEDBACK) .build(1)); Competition competition = newCompetition().withSetupComplete(true) .withMilestones(milestones) .build(); assertEquals(CompetitionStatus.FUNDERS_PANEL, competition.getCompetitionStatus()); CompetitionFundedKeyApplicationStatisticsResource keyStatistics = new CompetitionFundedKeyApplicationStatisticsResource(); keyStatistics.setApplicationsAwaitingDecision(0); keyStatistics.setApplicationsSubmitted(5); keyStatistics.setApplicationsNotifiedOfDecision(4); when(competitionRepositoryMock.findById(competitionId)).thenReturn(Optional.of(competition)); when(competitionKeyApplicationStatisticsServiceMock.getFundedKeyStatisticsByCompetition(competitionId)) .thenReturn(serviceSuccess(keyStatistics)); ServiceResult<Void> response = service.manageInformState(competitionId); assertTrue(response.isSuccess()); assertEquals(CompetitionStatus.FUNDERS_PANEL, competition.getCompetitionStatus()); } |
CompetitionServiceImpl extends BaseTransactionalService implements CompetitionService { @Override public ServiceResult<List<OrganisationTypeResource>> getCompetitionOrganisationTypes(long id) { return find(competitionRepository.findById(id), notFoundError(OrganisationType.class, id)).andOnSuccess(comp -> serviceSuccess((List) organisationTypeMapper.mapToResource(comp.getLeadApplicantTypes()))); } @Override ServiceResult<CompetitionResource> getCompetitionById(long id); @Override ServiceResult<CompetitionResource> getCompetitionByApplicationId(long applicationId); @Override ServiceResult<CompetitionResource> getCompetitionByProjectId(long projectId); @Override ServiceResult<List<OrganisationTypeResource>> getCompetitionOrganisationTypes(long id); @Override ServiceResult<List<CompetitionResource>> findAll(); @Override @Transactional ServiceResult<Void> closeAssessment(long competitionId); @Override @Transactional ServiceResult<Void> notifyAssessors(long competitionId); @Override @Transactional ServiceResult<Void> releaseFeedback(long competitionId); @Override @Transactional ServiceResult<Void> manageInformState(long competitionId); @Override ServiceResult<List<CompetitionOpenQueryResource>> findAllOpenQueries(long competitionId); @Override ServiceResult<Long> countAllOpenQueries(long competitionId); @Override ServiceResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(long competitionId); @Override ServiceResult<Long> countPendingSpendProfiles(long competitionId); @Override @Transactional ServiceResult<Void> updateTermsAndConditionsForCompetition(long competitionId, long termsAndConditionsId); @Override ServiceResult<FileAndContents> downloadTerms(long competitionId); } | @Test public void getCompetitionOrganisationTypesById() { List<OrganisationType> organisationTypes = newOrganisationType().build(2); List<OrganisationTypeResource> organisationTypeResources = newOrganisationTypeResource().build(2); Competition competition = new Competition(); competition.setLeadApplicantTypes(organisationTypes); when(competitionRepositoryMock.findById(competitionId)).thenReturn(Optional.of(competition)); when(organisationTypeMapperMock.mapToResource(organisationTypes)).thenReturn(organisationTypeResources); List<OrganisationTypeResource> response = service.getCompetitionOrganisationTypes(competitionId).getSuccess(); assertEquals(organisationTypeResources, response); } |
CompetitionServiceImpl extends BaseTransactionalService implements CompetitionService { @Override public ServiceResult<List<CompetitionOpenQueryResource>> findAllOpenQueries(long competitionId) { return serviceSuccess(competitionRepository.getOpenQueryByCompetitionAndProjectStateNotIn(competitionId, asList(WITHDRAWN, HANDLED_OFFLINE, COMPLETED_OFFLINE))); } @Override ServiceResult<CompetitionResource> getCompetitionById(long id); @Override ServiceResult<CompetitionResource> getCompetitionByApplicationId(long applicationId); @Override ServiceResult<CompetitionResource> getCompetitionByProjectId(long projectId); @Override ServiceResult<List<OrganisationTypeResource>> getCompetitionOrganisationTypes(long id); @Override ServiceResult<List<CompetitionResource>> findAll(); @Override @Transactional ServiceResult<Void> closeAssessment(long competitionId); @Override @Transactional ServiceResult<Void> notifyAssessors(long competitionId); @Override @Transactional ServiceResult<Void> releaseFeedback(long competitionId); @Override @Transactional ServiceResult<Void> manageInformState(long competitionId); @Override ServiceResult<List<CompetitionOpenQueryResource>> findAllOpenQueries(long competitionId); @Override ServiceResult<Long> countAllOpenQueries(long competitionId); @Override ServiceResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(long competitionId); @Override ServiceResult<Long> countPendingSpendProfiles(long competitionId); @Override @Transactional ServiceResult<Void> updateTermsAndConditionsForCompetition(long competitionId, long termsAndConditionsId); @Override ServiceResult<FileAndContents> downloadTerms(long competitionId); } | @Test public void getCompetitionOpenQueries() { List<CompetitionOpenQueryResource> openQueries = singletonList(new CompetitionOpenQueryResource(1L, 1L, "org", 1L, "proj")); when(competitionRepositoryMock.getOpenQueryByCompetitionAndProjectStateNotIn(competitionId, asList(WITHDRAWN, HANDLED_OFFLINE, COMPLETED_OFFLINE))).thenReturn(openQueries); List<CompetitionOpenQueryResource> response = service.findAllOpenQueries(competitionId).getSuccess(); assertEquals(1, response.size()); } |
CompetitionServiceImpl extends BaseTransactionalService implements CompetitionService { @Override public ServiceResult<Long> countAllOpenQueries(long competitionId) { return serviceSuccess(competitionRepository.countOpenQueriesByCompetitionAndProjectStateNotIn(competitionId, asList(WITHDRAWN, HANDLED_OFFLINE, COMPLETED_OFFLINE))); } @Override ServiceResult<CompetitionResource> getCompetitionById(long id); @Override ServiceResult<CompetitionResource> getCompetitionByApplicationId(long applicationId); @Override ServiceResult<CompetitionResource> getCompetitionByProjectId(long projectId); @Override ServiceResult<List<OrganisationTypeResource>> getCompetitionOrganisationTypes(long id); @Override ServiceResult<List<CompetitionResource>> findAll(); @Override @Transactional ServiceResult<Void> closeAssessment(long competitionId); @Override @Transactional ServiceResult<Void> notifyAssessors(long competitionId); @Override @Transactional ServiceResult<Void> releaseFeedback(long competitionId); @Override @Transactional ServiceResult<Void> manageInformState(long competitionId); @Override ServiceResult<List<CompetitionOpenQueryResource>> findAllOpenQueries(long competitionId); @Override ServiceResult<Long> countAllOpenQueries(long competitionId); @Override ServiceResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(long competitionId); @Override ServiceResult<Long> countPendingSpendProfiles(long competitionId); @Override @Transactional ServiceResult<Void> updateTermsAndConditionsForCompetition(long competitionId, long termsAndConditionsId); @Override ServiceResult<FileAndContents> downloadTerms(long competitionId); } | @Test public void countCompetitionOpenQueries() { Long countOpenQueries = 4l; when(competitionRepositoryMock.countOpenQueriesByCompetitionAndProjectStateNotIn(competitionId, asList(WITHDRAWN, HANDLED_OFFLINE, COMPLETED_OFFLINE))).thenReturn(countOpenQueries); Long response = service.countAllOpenQueries(competitionId).getSuccess(); assertEquals(countOpenQueries, response); } |
CompetitionServiceImpl extends BaseTransactionalService implements CompetitionService { @Override public ServiceResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(long competitionId) { List<Object[]> pendingSpendProfiles = competitionRepository.getPendingSpendProfiles(competitionId); return serviceSuccess(simpleMap(pendingSpendProfiles, object -> new SpendProfileStatusResource(((BigInteger) object[0]).longValue(), ((BigInteger) object[1]).longValue(), (String) object[2]))); } @Override ServiceResult<CompetitionResource> getCompetitionById(long id); @Override ServiceResult<CompetitionResource> getCompetitionByApplicationId(long applicationId); @Override ServiceResult<CompetitionResource> getCompetitionByProjectId(long projectId); @Override ServiceResult<List<OrganisationTypeResource>> getCompetitionOrganisationTypes(long id); @Override ServiceResult<List<CompetitionResource>> findAll(); @Override @Transactional ServiceResult<Void> closeAssessment(long competitionId); @Override @Transactional ServiceResult<Void> notifyAssessors(long competitionId); @Override @Transactional ServiceResult<Void> releaseFeedback(long competitionId); @Override @Transactional ServiceResult<Void> manageInformState(long competitionId); @Override ServiceResult<List<CompetitionOpenQueryResource>> findAllOpenQueries(long competitionId); @Override ServiceResult<Long> countAllOpenQueries(long competitionId); @Override ServiceResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(long competitionId); @Override ServiceResult<Long> countPendingSpendProfiles(long competitionId); @Override @Transactional ServiceResult<Void> updateTermsAndConditionsForCompetition(long competitionId, long termsAndConditionsId); @Override ServiceResult<FileAndContents> downloadTerms(long competitionId); } | @Test public void getPendingSpendProfiles() { List<Object[]> pendingSpendProfiles = singletonList(new Object[]{BigInteger.valueOf(11L), BigInteger.valueOf(1L), new String("Project 1")}); when(competitionRepositoryMock.getPendingSpendProfiles(competitionId)).thenReturn(pendingSpendProfiles); ServiceResult<List<SpendProfileStatusResource>> result = service.getPendingSpendProfiles(competitionId); assertTrue(result.isSuccess()); List<SpendProfileStatusResource> expectedPendingSpendProfiles = singletonList(new SpendProfileStatusResource(11L, 1L, "Project 1")); assertEquals(expectedPendingSpendProfiles, result.getSuccess()); } |
CompetitionServiceImpl extends BaseTransactionalService implements CompetitionService { @Override public ServiceResult<Long> countPendingSpendProfiles(long competitionId) { return serviceSuccess(competitionRepository.countPendingSpendProfiles(competitionId).longValue()); } @Override ServiceResult<CompetitionResource> getCompetitionById(long id); @Override ServiceResult<CompetitionResource> getCompetitionByApplicationId(long applicationId); @Override ServiceResult<CompetitionResource> getCompetitionByProjectId(long projectId); @Override ServiceResult<List<OrganisationTypeResource>> getCompetitionOrganisationTypes(long id); @Override ServiceResult<List<CompetitionResource>> findAll(); @Override @Transactional ServiceResult<Void> closeAssessment(long competitionId); @Override @Transactional ServiceResult<Void> notifyAssessors(long competitionId); @Override @Transactional ServiceResult<Void> releaseFeedback(long competitionId); @Override @Transactional ServiceResult<Void> manageInformState(long competitionId); @Override ServiceResult<List<CompetitionOpenQueryResource>> findAllOpenQueries(long competitionId); @Override ServiceResult<Long> countAllOpenQueries(long competitionId); @Override ServiceResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(long competitionId); @Override ServiceResult<Long> countPendingSpendProfiles(long competitionId); @Override @Transactional ServiceResult<Void> updateTermsAndConditionsForCompetition(long competitionId, long termsAndConditionsId); @Override ServiceResult<FileAndContents> downloadTerms(long competitionId); } | @Test public void countPendingSpendProfiles() { final BigDecimal pendingSpendProfileCount = BigDecimal.TEN; when(competitionRepositoryMock.countPendingSpendProfiles(competitionId)).thenReturn(pendingSpendProfileCount); ServiceResult<Long> result = service.countPendingSpendProfiles(competitionId); assertTrue(result.isSuccess()); assertEquals(Long.valueOf(pendingSpendProfileCount.longValue()), result.getSuccess()); } |
CompetitionServiceImpl extends BaseTransactionalService implements CompetitionService { @Override @Transactional public ServiceResult<Void> updateTermsAndConditionsForCompetition(long competitionId, long termsAndConditionsId) { Optional<GrantTermsAndConditions> termsAndConditions = grantTermsAndConditionsRepository.findById(termsAndConditionsId); if (termsAndConditions.isPresent()) { return find(competitionRepository.findById(competitionId), notFoundError(Competition.class, competitionId)) .andOnSuccess(competition -> { competition.setTermsAndConditions(termsAndConditions.get()); competitionRepository.save(competition); return serviceSuccess(); }); } return serviceFailure(notFoundError(GrantTermsAndConditions.class, termsAndConditionsId)); } @Override ServiceResult<CompetitionResource> getCompetitionById(long id); @Override ServiceResult<CompetitionResource> getCompetitionByApplicationId(long applicationId); @Override ServiceResult<CompetitionResource> getCompetitionByProjectId(long projectId); @Override ServiceResult<List<OrganisationTypeResource>> getCompetitionOrganisationTypes(long id); @Override ServiceResult<List<CompetitionResource>> findAll(); @Override @Transactional ServiceResult<Void> closeAssessment(long competitionId); @Override @Transactional ServiceResult<Void> notifyAssessors(long competitionId); @Override @Transactional ServiceResult<Void> releaseFeedback(long competitionId); @Override @Transactional ServiceResult<Void> manageInformState(long competitionId); @Override ServiceResult<List<CompetitionOpenQueryResource>> findAllOpenQueries(long competitionId); @Override ServiceResult<Long> countAllOpenQueries(long competitionId); @Override ServiceResult<List<SpendProfileStatusResource>> getPendingSpendProfiles(long competitionId); @Override ServiceResult<Long> countPendingSpendProfiles(long competitionId); @Override @Transactional ServiceResult<Void> updateTermsAndConditionsForCompetition(long competitionId, long termsAndConditionsId); @Override ServiceResult<FileAndContents> downloadTerms(long competitionId); } | @Test public void updateTermsAndConditionsForCompetition() { GrantTermsAndConditions termsAndConditions = newGrantTermsAndConditions().build(); Competition competition = newCompetition().build(); when(grantTermsAndConditionsRepositoryMock.findById(termsAndConditions.getId())) .thenReturn(Optional.of(termsAndConditions)); when(competitionRepositoryMock.findById(competition.getId())).thenReturn(Optional.of(competition)); ServiceResult<Void> result = service.updateTermsAndConditionsForCompetition(competition.getId(), termsAndConditions.getId()); assertTrue(result.isSuccess()); assertEquals(competition.getTermsAndConditions().getId(), termsAndConditions.getId()); verify(competitionRepositoryMock).findById(competition.getId()); verify(competitionRepositoryMock).save(competition); verify(grantTermsAndConditionsRepositoryMock).findById(termsAndConditions.getId()); }
@Test public void updateInvalidTermsAndConditionsForCompetition() { Competition competition = newCompetition().build(); when(grantTermsAndConditionsRepositoryMock.findById(competition.getTermsAndConditions().getId())).thenReturn(Optional.empty()); when(competitionRepositoryMock.findById(competition.getId())).thenReturn(Optional.of(competition)); ServiceResult<Void> result = service.updateTermsAndConditionsForCompetition(competitionId, competition.getTermsAndConditions().getId()); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(GrantTermsAndConditions.class, competition.getTermsAndConditions().getId()))); } |
CompetitionOrganisationConfigServiceImpl implements CompetitionOrganisationConfigService { @Override public ServiceResult<CompetitionOrganisationConfigResource> findOneByCompetitionId(long competitionId) { Optional<CompetitionOrganisationConfig> config = competitionOrganisationConfigRepository.findOneByCompetitionId(competitionId); if (config.isPresent()) { return serviceSuccess(mapper.mapToResource(config.get())); } return serviceSuccess(new CompetitionOrganisationConfigResource(false, false)); } @Override ServiceResult<CompetitionOrganisationConfigResource> findOneByCompetitionId(long competitionId); @Override @Transactional ServiceResult<Void> update(long competitionId, CompetitionOrganisationConfigResource competitionOrganisationConfigResource); } | @Test public void findOneByCompetitionId() { CompetitionOrganisationConfigResource resource = new CompetitionOrganisationConfigResource(); when(competitionOrganisationConfigRepository.findOneByCompetitionId(competitionId)).thenReturn(Optional.of(config)); when(mapper.mapToResource(config)).thenReturn(resource); ServiceResult<CompetitionOrganisationConfigResource> result = service.findOneByCompetitionId(competitionId); assertTrue(result.isSuccess()); assertEquals(config.getId(), result.getSuccess().getId()); } |
TermsAndConditionsServiceImpl implements TermsAndConditionsService { @Override public ServiceResult<GrantTermsAndConditionsResource> getById(Long id) { return find(grantTermsAndConditionsRepository.findById(id), notFoundError(GrantTermsAndConditionsResource.class, id)) .andOnSuccessReturn(grantTermsAndConditionsMapper::mapToResource); } @Autowired TermsAndConditionsServiceImpl(
GrantTermsAndConditionsRepository grantTermsAndConditionsRepository,
SiteTermsAndConditionsRepository siteTermsAndConditionsRepository,
GrantTermsAndConditionsMapper grantTermsAndConditionsMapper,
SiteTermsAndConditionsMapper siteTermsAndConditionsMapper); @Override ServiceResult<List<GrantTermsAndConditionsResource>> getLatestVersionsForAllTermsAndConditions(); @Override ServiceResult<GrantTermsAndConditionsResource> getById(Long id); @Override @Cacheable(cacheNames="siteTerms", key = "#root.methodName", unless = "#result.isFailure()") ServiceResult<SiteTermsAndConditionsResource> getLatestSiteTermsAndConditions(); } | @Test public void test_getTemplateById() { String name = "Innovate UK"; GrantTermsAndConditions termsAndConditions = newGrantTermsAndConditions().withName(name).build(); GrantTermsAndConditionsResource termsAndConditionsResource = newGrantTermsAndConditionsResource().withName(name) .build(); when(grantTermsAndConditionsRepository.findById(termsAndConditions.getId())).thenReturn(Optional.of(termsAndConditions)); when(grantTermsAndConditionsMapper.mapToResource(termsAndConditions)).thenReturn(termsAndConditionsResource); ServiceResult<GrantTermsAndConditionsResource> result = service.getById(termsAndConditions.getId()); assertTrue(result.isSuccess()); assertNotNull(result); assertEquals(name, result.getSuccess().getName()); }
@Test public void test_getTemplateByNull() { ServiceResult<GrantTermsAndConditionsResource> result = service.getById(null); assertTrue(result.isFailure()); assertNotNull(result); } |
TermsAndConditionsServiceImpl implements TermsAndConditionsService { @Override public ServiceResult<List<GrantTermsAndConditionsResource>> getLatestVersionsForAllTermsAndConditions() { return serviceSuccess((List<GrantTermsAndConditionsResource>) grantTermsAndConditionsMapper.mapToResource(grantTermsAndConditionsRepository.findLatestVersions()) ); } @Autowired TermsAndConditionsServiceImpl(
GrantTermsAndConditionsRepository grantTermsAndConditionsRepository,
SiteTermsAndConditionsRepository siteTermsAndConditionsRepository,
GrantTermsAndConditionsMapper grantTermsAndConditionsMapper,
SiteTermsAndConditionsMapper siteTermsAndConditionsMapper); @Override ServiceResult<List<GrantTermsAndConditionsResource>> getLatestVersionsForAllTermsAndConditions(); @Override ServiceResult<GrantTermsAndConditionsResource> getById(Long id); @Override @Cacheable(cacheNames="siteTerms", key = "#root.methodName", unless = "#result.isFailure()") ServiceResult<SiteTermsAndConditionsResource> getLatestSiteTermsAndConditions(); } | @Test public void test_getLatestVersionsForAllTermsAndConditions() { List<GrantTermsAndConditions> termsAndConditionsList = newGrantTermsAndConditions().build(3); List<GrantTermsAndConditionsResource> termsAndConditionsResourceList = newGrantTermsAndConditionsResource() .build(3); when(grantTermsAndConditionsRepository.findLatestVersions()).thenReturn(termsAndConditionsList); when(grantTermsAndConditionsMapper.mapToResource(termsAndConditionsList)).thenReturn (termsAndConditionsResourceList); ServiceResult<List<GrantTermsAndConditionsResource>> result = service .getLatestVersionsForAllTermsAndConditions(); assertTrue(result.isSuccess()); assertNotNull(result); assertEquals(3, result.getSuccess().size()); } |
TermsAndConditionsServiceImpl implements TermsAndConditionsService { @Override @Cacheable(cacheNames="siteTerms", key = "#root.methodName", unless = "#result.isFailure()") public ServiceResult<SiteTermsAndConditionsResource> getLatestSiteTermsAndConditions() { return find(siteTermsAndConditionsRepository.findTopByOrderByVersionDesc(), notFoundError(SiteTermsAndConditions.class)).andOnSuccessReturn (siteTermsAndConditionsMapper::mapToResource); } @Autowired TermsAndConditionsServiceImpl(
GrantTermsAndConditionsRepository grantTermsAndConditionsRepository,
SiteTermsAndConditionsRepository siteTermsAndConditionsRepository,
GrantTermsAndConditionsMapper grantTermsAndConditionsMapper,
SiteTermsAndConditionsMapper siteTermsAndConditionsMapper); @Override ServiceResult<List<GrantTermsAndConditionsResource>> getLatestVersionsForAllTermsAndConditions(); @Override ServiceResult<GrantTermsAndConditionsResource> getById(Long id); @Override @Cacheable(cacheNames="siteTerms", key = "#root.methodName", unless = "#result.isFailure()") ServiceResult<SiteTermsAndConditionsResource> getLatestSiteTermsAndConditions(); } | @Test public void test_getLatestSiteTermsAndConditions() { SiteTermsAndConditions siteTermsAndConditions = newSiteTermsAndConditions().build(); SiteTermsAndConditionsResource siteTermsAndConditionsResource = newSiteTermsAndConditionsResource().build(); when(siteTermsAndConditionsRepository.findTopByOrderByVersionDesc()).thenReturn(siteTermsAndConditions); when(siteTermsAndConditionsMapper.mapToResource(siteTermsAndConditions)).thenReturn (siteTermsAndConditionsResource); assertEquals(siteTermsAndConditionsResource, service.getLatestSiteTermsAndConditions().getSuccess()); InOrder inOrder = inOrder(siteTermsAndConditionsRepository, siteTermsAndConditionsMapper); inOrder.verify(siteTermsAndConditionsRepository).findTopByOrderByVersionDesc(); inOrder.verify(siteTermsAndConditionsMapper).mapToResource(siteTermsAndConditions); } |
CompetitionSetupInnovationLeadServiceImpl extends BaseTransactionalService implements CompetitionSetupInnovationLeadService { @Override public ServiceResult<List<UserResource>> findInnovationLeads(long competitionId) { List<User> innovationLeads = innovationLeadRepository.findAvailableInnovationLeadsNotAssignedToCompetition(competitionId); List<UserResource> innovationLeadUsers = simpleMap(innovationLeads, user -> userMapper .mapToResource(user)); return serviceSuccess(innovationLeadUsers); } @Override ServiceResult<List<UserResource>> findInnovationLeads(long competitionId); @Override ServiceResult<List<UserResource>> findAddedInnovationLeads(long competitionId); @Override @Transactional ServiceResult<Void> addInnovationLead(long competitionId, long innovationLeadUserId); @Override @Transactional ServiceResult<Void> removeInnovationLead(long competitionId, long innovationLeadUserId); } | @Test public void findInnovationLeads() { User innovationLead1 = newUser().withRoles(singleton(INNOVATION_LEAD)).build(); User innovationLead2 = newUser().withRoles(singleton(INNOVATION_LEAD)).build(); List<User> innovationLeads = asList(innovationLead1, innovationLead2); UserResource userResource1 = UserResourceBuilder.newUserResource().build(); UserResource userResource2 = UserResourceBuilder.newUserResource().build(); when(innovationLeadRepository.findAvailableInnovationLeadsNotAssignedToCompetition(competitionId)).thenReturn(innovationLeads); when(userMapper.mapToResource(innovationLead1)).thenReturn(userResource1); when(userMapper.mapToResource(innovationLead2)).thenReturn(userResource2); List<UserResource> result = service.findInnovationLeads(competitionId).getSuccess(); assertEquals(2, result.size()); assertEquals(userResource1, result.get(0)); assertEquals(userResource2, result.get(1)); } |
CompetitionSetupInnovationLeadServiceImpl extends BaseTransactionalService implements CompetitionSetupInnovationLeadService { @Override @Transactional public ServiceResult<Void> addInnovationLead(long competitionId, long innovationLeadUserId) { return findCompetitionById(competitionId) .andOnSuccessReturnVoid(competition -> find(userRepository.findById(innovationLeadUserId), notFoundError(User.class, innovationLeadUserId)) .andOnSuccess(innovationLead -> { innovationLeadRepository.save(new InnovationLead(competition, innovationLead)); return serviceSuccess(); }) ); } @Override ServiceResult<List<UserResource>> findInnovationLeads(long competitionId); @Override ServiceResult<List<UserResource>> findAddedInnovationLeads(long competitionId); @Override @Transactional ServiceResult<Void> addInnovationLead(long competitionId, long innovationLeadUserId); @Override @Transactional ServiceResult<Void> removeInnovationLead(long competitionId, long innovationLeadUserId); } | @Test public void addInnovationLeadWhenCompetitionNotFound() { Long innovationLeadUserId = 2L; when(competitionRepository.findById(competitionId)).thenReturn(Optional.empty()); ServiceResult<Void> result = service.addInnovationLead(competitionId, innovationLeadUserId); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(Competition.class, competitionId))); }
@Test public void addInnovationLead() { long innovationLeadUserId = 2L; Competition competition = newCompetition().build(); User innovationLead = newUser().build(); when(competitionRepository.findById(competitionId)).thenReturn(Optional.of(competition)); when(userRepository.findById(innovationLeadUserId)).thenReturn(Optional.of(innovationLead)); ServiceResult<Void> result = service.addInnovationLead(competitionId, innovationLeadUserId); assertTrue(result.isSuccess()); InnovationLead savedCompetitionParticipant = new InnovationLead(competition, innovationLead); verify(innovationLeadRepository).save(savedCompetitionParticipant); } |
CompetitionSetupInnovationLeadServiceImpl extends BaseTransactionalService implements CompetitionSetupInnovationLeadService { @Override @Transactional public ServiceResult<Void> removeInnovationLead(long competitionId, long innovationLeadUserId) { return find(innovationLeadRepository.findInnovationLead(competitionId, innovationLeadUserId), notFoundError(InnovationLead.class, competitionId, innovationLeadUserId)) .andOnSuccessReturnVoid(innovationLead -> innovationLeadRepository.delete(innovationLead)); } @Override ServiceResult<List<UserResource>> findInnovationLeads(long competitionId); @Override ServiceResult<List<UserResource>> findAddedInnovationLeads(long competitionId); @Override @Transactional ServiceResult<Void> addInnovationLead(long competitionId, long innovationLeadUserId); @Override @Transactional ServiceResult<Void> removeInnovationLead(long competitionId, long innovationLeadUserId); } | @Test public void removeInnovationLeadWhenCompetitionParticipantNotFound() { long innovationLeadUserId = 2L; when(innovationLeadRepository.findInnovationLead(competitionId, innovationLeadUserId)).thenReturn(null); ServiceResult<Void> result = service.removeInnovationLead(competitionId, innovationLeadUserId); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(notFoundError(InnovationLead.class, competitionId, innovationLeadUserId))); }
@Test public void removeInnovationLead() { long innovationLeadUserId = 2L; InnovationLead innovationLead = newInnovationLead().build(); when(innovationLeadRepository.findInnovationLead(competitionId, innovationLeadUserId)).thenReturn (innovationLead); ServiceResult<Void> result = service.removeInnovationLead(competitionId, innovationLeadUserId); assertTrue(result.isSuccess()); verify(innovationLeadRepository).delete(innovationLead); } |
CompetitionKeyApplicationStatisticsServiceImpl extends BaseTransactionalService implements
CompetitionKeyApplicationStatisticsService { @Override public ServiceResult<CompetitionOpenKeyApplicationStatisticsResource> getOpenKeyStatisticsByCompetition( long competitionId) { BigDecimal limit = new BigDecimal(50L); CompetitionOpenKeyApplicationStatisticsResource competitionOpenKeyApplicationStatisticsResource = new CompetitionOpenKeyApplicationStatisticsResource(); competitionOpenKeyApplicationStatisticsResource.setApplicationsPerAssessor(competitionAssessmentConfigRepository.findOneByCompetitionId (competitionId).get().getAssessorCount()); competitionOpenKeyApplicationStatisticsResource.setApplicationsStarted(applicationRepository .countByCompetitionIdAndApplicationProcessActivityStateInAndCompletionLessThanEqual(competitionId, CREATED_AND_OPEN_STATUSES, limit)); competitionOpenKeyApplicationStatisticsResource.setApplicationsPastHalf(applicationRepository .countByCompetitionIdAndApplicationProcessActivityStateNotInAndCompletionGreaterThan(competitionId, SUBMITTED_AND_INELIGIBLE_STATES, limit)); competitionOpenKeyApplicationStatisticsResource.setApplicationsSubmitted(applicationRepository .countByCompetitionIdAndApplicationProcessActivityStateIn(competitionId, SUBMITTED_AND_INELIGIBLE_STATES)); return serviceSuccess(competitionOpenKeyApplicationStatisticsResource); } @Override ServiceResult<CompetitionOpenKeyApplicationStatisticsResource> getOpenKeyStatisticsByCompetition(
long competitionId); @Override ServiceResult<CompetitionClosedKeyApplicationStatisticsResource> getClosedKeyStatisticsByCompetition(
long competitionId); @Override ServiceResult<CompetitionFundedKeyApplicationStatisticsResource> getFundedKeyStatisticsByCompetition(
long competitionId); } | @Test public void getOpenKeyStatisticsByCompetition() throws Exception { Long competitionId = 1L; CompetitionOpenKeyApplicationStatisticsResource keyStatisticsResource = newCompetitionOpenKeyApplicationStatisticsResource() .withApplicationsPastHalf(1) .withApplicationsPerAssessor(2) .withApplicationsStarted(3) .withApplicationsSubmitted(4) .build(); CompetitionAssessmentConfig config = newCompetitionAssessmentConfig().withAssessorCount(2).build(); BigDecimal limit = new BigDecimal(50L); when(competitionAssessmentConfigRepository.findOneByCompetitionId(competitionId)).thenReturn(Optional.of(config)); when(applicationRepositoryMock .countByCompetitionIdAndApplicationProcessActivityStateInAndCompletionLessThanEqual(competitionId, CREATED_AND_OPEN_STATUSES, limit)).thenReturn(keyStatisticsResource.getApplicationsStarted()); when(applicationRepositoryMock .countByCompetitionIdAndApplicationProcessActivityStateNotInAndCompletionGreaterThan(competitionId, SUBMITTED_AND_INELIGIBLE_STATES, limit)).thenReturn(keyStatisticsResource .getApplicationsPastHalf()); when(applicationRepositoryMock.countByCompetitionIdAndApplicationProcessActivityStateIn(competitionId, SUBMITTED_AND_INELIGIBLE_STATES)).thenReturn(keyStatisticsResource.getApplicationsSubmitted()); CompetitionOpenKeyApplicationStatisticsResource response = service.getOpenKeyStatisticsByCompetition (competitionId).getSuccess(); assertEquals(keyStatisticsResource, response); } |
CompetitionKeyApplicationStatisticsServiceImpl extends BaseTransactionalService implements
CompetitionKeyApplicationStatisticsService { @Override public ServiceResult<CompetitionClosedKeyApplicationStatisticsResource> getClosedKeyStatisticsByCompetition( long competitionId) { CompetitionClosedKeyApplicationStatisticsResource competitionClosedKeyApplicationStatisticsResource = new CompetitionClosedKeyApplicationStatisticsResource(); competitionClosedKeyApplicationStatisticsResource.setApplicationsPerAssessor(competitionAssessmentConfigRepository.findOneByCompetitionId (competitionId).get().getAssessorCount()); competitionClosedKeyApplicationStatisticsResource.setApplicationsRequiringAssessors (applicationStatisticsRepository.findByCompetitionAndApplicationProcessActivityStateIn(competitionId, SUBMITTED_STATES) .stream() .filter(as -> as.getAssessors() < competitionClosedKeyApplicationStatisticsResource .getApplicationsPerAssessor()) .mapToInt(e -> 1) .sum()); competitionClosedKeyApplicationStatisticsResource.setAssignmentCount(applicationStatisticsRepository .findByCompetitionAndApplicationProcessActivityStateIn(competitionId, SUBMITTED_STATES).stream() .mapToInt(ApplicationStatistics::getAssessors).sum()); return serviceSuccess(competitionClosedKeyApplicationStatisticsResource); } @Override ServiceResult<CompetitionOpenKeyApplicationStatisticsResource> getOpenKeyStatisticsByCompetition(
long competitionId); @Override ServiceResult<CompetitionClosedKeyApplicationStatisticsResource> getClosedKeyStatisticsByCompetition(
long competitionId); @Override ServiceResult<CompetitionFundedKeyApplicationStatisticsResource> getFundedKeyStatisticsByCompetition(
long competitionId); } | @Test public void getClosedKeyStatisticsByCompetition() throws Exception { long competitionId = 1L; CompetitionClosedKeyApplicationStatisticsResource keyStatisticsResource = newCompetitionClosedKeyApplicationStatisticsResource() .withApplicationsPerAssessor(2) .withApplicationsRequiringAssessors(2) .withAssignmentCount(3) .build(); CompetitionAssessmentConfig config = newCompetitionAssessmentConfig().withAssessorCount(2).build(); List<Assessment> assessments = newAssessment() .withProcessState(AssessmentState.PENDING, REJECTED, AssessmentState.OPEN) .build(3); List<Assessment> assessmentList = newAssessment() .withProcessState(AssessmentState.SUBMITTED) .build(1); List<ApplicationStatistics> applicationStatistics = newApplicationStatistics() .withAssessments(assessments, assessmentList, emptyList()) .build(3); when(competitionAssessmentConfigRepository.findOneByCompetitionId(competitionId)).thenReturn(Optional.of(config)); when(applicationStatisticsRepositoryMock.findByCompetitionAndApplicationProcessActivityStateIn(competitionId, SUBMITTED_STATES)).thenReturn(applicationStatistics); CompetitionClosedKeyApplicationStatisticsResource response = service.getClosedKeyStatisticsByCompetition (competitionId).getSuccess(); assertEquals(keyStatisticsResource, response); } |
CompetitionKeyApplicationStatisticsServiceImpl extends BaseTransactionalService implements
CompetitionKeyApplicationStatisticsService { @Override public ServiceResult<CompetitionFundedKeyApplicationStatisticsResource> getFundedKeyStatisticsByCompetition( long competitionId) { CompetitionFundedKeyApplicationStatisticsResource competitionFundedKeyApplicationStatisticsResource = new CompetitionFundedKeyApplicationStatisticsResource(); competitionFundedKeyApplicationStatisticsResource .setApplicationsSubmitted(applicationRepository.countByCompetitionIdAndApplicationProcessActivityStateIn(competitionId, SUBMITTED_STATES)); competitionFundedKeyApplicationStatisticsResource.setApplicationsFunded(applicationRepository.countByCompetitionIdAndFundingDecision(competitionId, FundingDecisionStatus.FUNDED)); competitionFundedKeyApplicationStatisticsResource.setApplicationsNotFunded(applicationRepository.countByCompetitionIdAndFundingDecision(competitionId, FundingDecisionStatus.UNFUNDED)); competitionFundedKeyApplicationStatisticsResource.setApplicationsOnHold(applicationRepository.countByCompetitionIdAndFundingDecision(competitionId, FundingDecisionStatus.ON_HOLD)); competitionFundedKeyApplicationStatisticsResource.setApplicationsNotifiedOfDecision(applicationRepository .countByCompetitionIdAndFundingDecisionIsNotNullAndManageFundingEmailDateIsNotNull(competitionId)); competitionFundedKeyApplicationStatisticsResource.setApplicationsAwaitingDecision(applicationRepository .countByCompetitionIdAndFundingDecisionIsNotNullAndManageFundingEmailDateIsNull(competitionId)); return serviceSuccess(competitionFundedKeyApplicationStatisticsResource); } @Override ServiceResult<CompetitionOpenKeyApplicationStatisticsResource> getOpenKeyStatisticsByCompetition(
long competitionId); @Override ServiceResult<CompetitionClosedKeyApplicationStatisticsResource> getClosedKeyStatisticsByCompetition(
long competitionId); @Override ServiceResult<CompetitionFundedKeyApplicationStatisticsResource> getFundedKeyStatisticsByCompetition(
long competitionId); } | @Test public void getFundedKeyStatisticsByCompetition() { long competitionId = 1L; int applicationsNotifiedOfDecision = 1; int applicationsAwaitingDecision = 2; when(applicationRepositoryMock.countByCompetitionIdAndApplicationProcessActivityStateIn(competitionId, SUBMITTED_STATES)).thenReturn(3); when(applicationRepositoryMock.countByCompetitionIdAndFundingDecision(competitionId, FundingDecisionStatus.FUNDED)).thenReturn(1); when(applicationRepositoryMock.countByCompetitionIdAndFundingDecision(competitionId, FundingDecisionStatus.UNFUNDED)).thenReturn(1); when(applicationRepositoryMock.countByCompetitionIdAndFundingDecision(competitionId, FundingDecisionStatus.ON_HOLD)).thenReturn(1); when(applicationRepositoryMock .countByCompetitionIdAndFundingDecisionIsNotNullAndManageFundingEmailDateIsNotNull(competitionId)) .thenReturn(applicationsNotifiedOfDecision); when(applicationRepositoryMock.countByCompetitionIdAndFundingDecisionIsNotNullAndManageFundingEmailDateIsNull (competitionId)).thenReturn(applicationsAwaitingDecision); CompetitionFundedKeyApplicationStatisticsResource response = service.getFundedKeyStatisticsByCompetition (competitionId).getSuccess(); assertEquals(3, response.getApplicationsSubmitted()); assertEquals(1, response.getApplicationsFunded()); assertEquals(1, response.getApplicationsNotFunded()); assertEquals(1, response.getApplicationsOnHold()); assertEquals(applicationsNotifiedOfDecision, response.getApplicationsNotifiedOfDecision()); assertEquals(applicationsAwaitingDecision, response.getApplicationsAwaitingDecision()); } |
Competition extends AuditableEntity implements ProcessActivity, ApplicationConfiguration, ProjectConfiguration { public CompetitionStatus getCompetitionStatus() { if (setupComplete != null && setupComplete) { if (!isMilestoneReached(OPEN_DATE)) { return READY_TO_OPEN; } else if (!isMilestoneReached(SUBMISSION_DATE)) { return OPEN; } else if (CompetitionCompletionStage.COMPETITION_CLOSE.equals(getCompletionStage())) { return PREVIOUS; } else if (!isMilestoneReached(ASSESSORS_NOTIFIED)) { return CLOSED; } else if (!isMilestoneReached(MilestoneType.ASSESSMENT_CLOSED)) { return IN_ASSESSMENT; } else if (!isMilestoneReached(MilestoneType.NOTIFICATIONS)) { return CompetitionStatus.FUNDERS_PANEL; } else if (!isMilestoneReached(MilestoneType.FEEDBACK_RELEASED)) { return ASSESSOR_FEEDBACK; } else if (isMilestoneReached(MilestoneType.FEEDBACK_RELEASED) && CompetitionCompletionStage.RELEASE_FEEDBACK.equals(getCompletionStage())) { return PREVIOUS; } else { return PROJECT_SETUP; } } else { return COMPETITION_SETUP; } } Competition(); Competition(List<Question> questions,
List<Section> sections,
String name,
ZonedDateTime startDate,
ZonedDateTime endDate,
ZonedDateTime registrationDate,
GrantTermsAndConditions termsAndConditions); Competition(String name, ZonedDateTime startDate, ZonedDateTime endDate); CompetitionStatus getCompetitionStatus(); CovidType getCovidType(); void setCovidType(CovidType covidType); List<FinanceRowType> getFinanceRowTypes(); List<ProjectStages> getProjectStages(); void setProjectStages(List<ProjectStages> projectStages); void addProjectStage(ProjectStages stage); void removeProjectStage(ProjectStages stage); List<Section> getSections(); Long getId(); String getName(); Boolean getSetupComplete(); void setSetupComplete(Boolean setupComplete); void setSections(List<Section> sections); void setQuestions(List<Question> questions); @JsonIgnore long getDaysLeft(); @JsonIgnore long getTotalDays(); @JsonIgnore long getStartDateToEndDatePercentage(); @JsonIgnore List<Question> getQuestions(); @JsonIgnore boolean inProjectSetup(); void setName(String name); ZonedDateTime getEndDate(); void setEndDate(ZonedDateTime endDate); ZonedDateTime getRegistrationDate(); void setRegistrationDate(ZonedDateTime endDate); ZonedDateTime getStartDate(); void setStartDate(ZonedDateTime startDate); ZonedDateTime getAssessorAcceptsDate(); void setAssessorAcceptsDate(ZonedDateTime assessorAcceptsDate); ZonedDateTime getAssessorDeadlineDate(); void setAssessorDeadlineDate(ZonedDateTime assessorDeadlineDate); ZonedDateTime getReleaseFeedbackDate(); void setReleaseFeedbackDate(ZonedDateTime releaseFeedbackDate); void setFeedbackReleasedDate(ZonedDateTime feedbackReleasedDate); ZonedDateTime getFeedbackReleasedDate(); ZonedDateTime getAssessmentPanelDate(); ZonedDateTime getAssessmentClosedDate(); void setAssessmentPanelDate(ZonedDateTime assessmentPanelDate); ZonedDateTime getPanelDate(); void setPanelDate(ZonedDateTime panelDate); ZonedDateTime getFundersPanelDate(); void setFundersPanelDate(ZonedDateTime fundersPanelDate); ZonedDateTime getAssessorFeedbackDate(); void setAssessorFeedbackDate(ZonedDateTime assessorFeedbackDate); ZonedDateTime getFundersPanelEndDate(); void setFundersPanelEndDate(ZonedDateTime fundersPanelEndDate); ZonedDateTime getAssessorBriefingDate(); void setAssessorBriefingDate(ZonedDateTime assessorBriefingDate); Integer getMaxResearchRatio(); void setMaxResearchRatio(Integer maxResearchRatio); Integer getAcademicGrantPercentage(); void setAcademicGrantPercentage(Integer academicGrantPercentage); void setId(Long id); User getExecutive(); void setExecutive(User executive); User getLeadTechnologist(); void setLeadTechnologist(User leadTechnologist); String getPafCode(); void setPafCode(String pafCode); String getBudgetCode(); void setBudgetCode(String budgetCode); String getCode(); void setCode(String code); CompetitionType getCompetitionType(); void setCompetitionType(CompetitionType competitionType); InnovationSector getInnovationSector(); void setInnovationSector(InnovationSector innovationSector); Set<InnovationArea> getInnovationAreas(); void addInnovationArea(InnovationArea innovationArea); void setInnovationAreas(Set<InnovationArea> innovationAreas); Set<ResearchCategory> getResearchCategories(); void addResearchCategory(ResearchCategory researchCategory); void setResearchCategories(Set<ResearchCategory> researchCategories); List<CompetitionDocument> getCompetitionDocuments(); void setCompetitionDocuments(List<CompetitionDocument> competitionDocuments); List<Milestone> getMilestones(); void setMilestones(List<Milestone> milestones); boolean isMultiStream(); void setMultiStream(boolean multiStream); Boolean getResubmission(); void setResubmission(Boolean resubmission); String getStreamName(); void setStreamName(String streamName); CollaborationLevel getCollaborationLevel(); void setCollaborationLevel(CollaborationLevel collaborationLevel); List<OrganisationType> getLeadApplicantTypes(); void setLeadApplicantTypes(List<OrganisationType> leadApplicantTypes); String getActivityCode(); void setActivityCode(String activityCode); List<CompetitionFunder> getFunders(); void setFunders(List<CompetitionFunder> funders); String startDateDisplay(); String submissionDateDisplay(); Integer getAssessorCount(); void setAssessorCount(Integer assessorCount); BigDecimal getAssessorPay(); void setAssessorPay(BigDecimal assessorPay); boolean isTemplate(); void setTemplate(boolean template); Boolean getUseResubmissionQuestion(); void setUseResubmissionQuestion(Boolean useResubmissionQuestion); void notifyAssessors(ZonedDateTime date); boolean isNonFinanceType(); @Override boolean isH2020(); @Override boolean isFullyFunded(); boolean isLoan(); boolean isGrant(); boolean isProcurement(); boolean isKtp(); void releaseFeedback(ZonedDateTime date); void closeAssessment(ZonedDateTime date); boolean isNonIfs(); void setNonIfs(boolean nonIfs); String getNonIfsUrl(); void setNonIfsUrl(String nonIfsUrl); Boolean isHasAssessmentPanel(); void setHasAssessmentPanel(Boolean hasAssessmentPanel); Boolean isHasInterviewStage(); void setHasInterviewStage(Boolean hasInterviewStage); AssessorFinanceView getAssessorFinanceView(); void setAssessorFinanceView(AssessorFinanceView assessorFinanceView); List<GrantClaimMaximum> getGrantClaimMaximums(); void setGrantClaimMaximums(List<GrantClaimMaximum> grantClaimMaximums); GrantTermsAndConditions getTermsAndConditions(); void setTermsAndConditions(GrantTermsAndConditions termsAndConditions); boolean isLocationPerPartner(); void setLocationPerPartner(boolean locationPerPartner); Integer getMaxProjectDuration(); void setMaxProjectDuration(Integer maxProjectDuration); Integer getMinProjectDuration(); void setMinProjectDuration(Integer minProjectDuration); Boolean getStateAid(); void setStateAid(Boolean stateAid); Boolean getIncludeYourOrganisationSection(); void setIncludeYourOrganisationSection(final Boolean includeYourOrganisationSection); ApplicationFinanceType getApplicationFinanceType(); void setApplicationFinanceType(final ApplicationFinanceType applicationFinanceType); Boolean getIncludeJesForm(); void setIncludeJesForm(Boolean includeJesForm); Boolean getIncludeProjectGrowthTable(); void setIncludeProjectGrowthTable(final Boolean includeProjectGrowthTable); CompetitionCompletionStage getCompletionStage(); void setCompletionStage(CompetitionCompletionStage completionStage); FundingType getFundingType(); void setFundingType(FundingType fundingType); void setCompetitionTerms(FileEntry competitionTerms); Optional<FileEntry> getCompetitionTerms(); List<ProjectSetupStage> getProjectSetupStages(); ZonedDateTime getProjectSetupStarted(); void setProjectSetupStarted(ZonedDateTime projectSetupStarted); CompetitionOrganisationConfig getCompetitionOrganisationConfig(); void setCompetitionOrganisationConfig(CompetitionOrganisationConfig competitionOrganisationConfig); CompetitionApplicationConfig getCompetitionApplicationConfig(); void setCompetitionApplicationConfig(CompetitionApplicationConfig competitionApplicationConfig); boolean isUseDocusignForGrantOfferLetter(); void setUseDocusignForGrantOfferLetter(boolean useDocusignForGrantOfferLetter); boolean isHasAssessmentStage(); List<CompetitionFinanceRowTypes> getCompetitionFinanceRowTypes(); void setHasAssessmentStage(boolean hasAssessmentStage); CompetitionAssessmentConfig getCompetitionAssessmentConfig(); void setCompetitionAssessmentConfig(CompetitionAssessmentConfig competitionAssessmentConfig); CompetitionTypeEnum getCompetitionTypeEnum(); @Override boolean isExpressionOfInterest(); @Override boolean isSbriPilot(); @Override ApplicationConfiguration getApplicationConfiguration(); } | @Test public void competitionStatusOpen() { assertEquals(OPEN, competition.getCompetitionStatus()); } |
PublicContentServiceImpl extends BaseTransactionalService implements PublicContentService { @Override public ServiceResult<PublicContentResource> findByCompetitionId(long id) { return find(publicContentRepository.findByCompetitionId(id), notFoundError(PublicContent.class, id)) .andOnSuccessReturn(publicContent -> sortGroups(publicContentMapper.mapToResource(publicContent))); } @Override ServiceResult<PublicContentResource> findByCompetitionId(long id); @Override @Transactional ServiceResult<Void> initialiseByCompetitionId(long competitionId); @Override @Transactional ServiceResult<Void> publishByCompetitionId(long competitionId); @Override @Transactional ServiceResult<Void> updateSection(PublicContentResource resource, PublicContentSectionType section); @Override @Transactional ServiceResult<Void> markSectionAsComplete(PublicContentResource resource, PublicContentSectionType section); } | @Test public void testGetById() { PublicContent publicContent = newPublicContent().build(); PublicContentResource resource = newPublicContentResource().withContentSections(COMPLETE_SECTIONS).build(); when(publicContentRepository.findByCompetitionId(COMPETITION_ID)).thenReturn(publicContent); when(publicContentMapper.mapToResource(publicContent)).thenReturn(resource); ServiceResult<PublicContentResource> result = service.findByCompetitionId(COMPETITION_ID); assertThat(result.getSuccess(), equalTo(resource)); verify(publicContentRepository).findByCompetitionId(COMPETITION_ID); assertTrue(isSortedByPriority(result.getSuccess())); } |
Milestone { public boolean isSet() { assert date != null || !type.isPresetDate(); return date != null; } private Milestone(); Milestone(MilestoneType type, Competition competition); Milestone(MilestoneType type, ZonedDateTime date, Competition competition); Long getId(); void setId(Long id); void setCompetition(Competition competition); Competition getCompetition(); MilestoneType getType(); void setType(MilestoneType type); ZonedDateTime getDate(); void setDate(ZonedDateTime date); boolean isSet(); void ifSet(Consumer<ZonedDateTime> consumer); boolean isReached(ZonedDateTime now); } | @Test public void isSet() { Milestone assessorsNotifiedMilestone = new Milestone(MilestoneType.ASSESSORS_NOTIFIED, newCompetition().build()); assertFalse(assessorsNotifiedMilestone.isSet()); assessorsNotifiedMilestone.setDate(ZonedDateTime.now()); assertTrue(assessorsNotifiedMilestone.isSet()); } |
Milestone { public boolean isReached(ZonedDateTime now) { return date != null && !date.isAfter(now); } private Milestone(); Milestone(MilestoneType type, Competition competition); Milestone(MilestoneType type, ZonedDateTime date, Competition competition); Long getId(); void setId(Long id); void setCompetition(Competition competition); Competition getCompetition(); MilestoneType getType(); void setType(MilestoneType type); ZonedDateTime getDate(); void setDate(ZonedDateTime date); boolean isSet(); void ifSet(Consumer<ZonedDateTime> consumer); boolean isReached(ZonedDateTime now); } | @Test public void isReached() { ZonedDateTime now = ZonedDateTime.now(); ZonedDateTime future = now.plusNanos(1); ZonedDateTime past = now.minusNanos(1); assertFalse( new Milestone(MilestoneType.ALLOCATE_ASSESSORS, future, newCompetition().build()).isReached(now) ); assertTrue( new Milestone(MilestoneType.ALLOCATE_ASSESSORS, now, newCompetition().build()).isReached(now) ); assertTrue( new Milestone(MilestoneType.ALLOCATE_ASSESSORS, past, newCompetition().build()).isReached(now) ); } |
InterviewPermissionRules extends BasePermissionRules { @PermissionRule(value = "READ_INTERVIEW_DASHBOARD", description = "Assessors can view all Assessment Interviews on the competition " + "dashboard") public boolean userCanReadInterviewOnDashboard(InterviewResource interview, UserResource user) { Set<InterviewState> allowedStates = EnumSet.of(ASSIGNED); return isAssessorForInterview(interview, user, allowedStates); } @PermissionRule(value = "READ_INTERVIEW_DASHBOARD", description = "Assessors can view all Assessment Interviews on the competition " + "dashboard") boolean userCanReadInterviewOnDashboard(InterviewResource interview, UserResource user); @PermissionRule(value = "UPDATE", description = "An assessor may only update their own invites to assessment Interviews") boolean userCanUpdateInterview(InterviewResource interview, UserResource loggedInUser); @PermissionRule(value = "READ", description = "An assessor may only read their own invites to assessment Interviews") boolean userCanReadInterviews(InterviewResource interview, UserResource loggedInUser); } | @Test public void ownersCanReadAssessmentsOnDashboard() { EnumSet<InterviewState> allowedStates = EnumSet.of(ASSIGNED); allowedStates.forEach(state -> assertTrue("the owner of an assessment Interview should be able to read that assessment Interview on the dashboard", rules.userCanReadInterviewOnDashboard(assessmentInterviews.get(state), assessorUser))); EnumSet.complementOf(allowedStates).forEach(state -> assertFalse("the owner of an assessment Interview should not be able to read that assessment Interview on the dashboard", rules.userCanReadInterviewOnDashboard(assessmentInterviews.get(state), assessorUser))); }
@Test public void otherUsersCanNotReadAssessmentsOnDashboard() { EnumSet.allOf(InterviewState.class).forEach(state -> assertFalse("other users should not be able to read any assessment Interviews", rules.userCanReadInterviewOnDashboard(assessmentInterviews.get(state), otherUser))); } |
InterviewParticipantPermissionRules extends BasePermissionRules { @PermissionRule(value = "ACCEPT", description = "only the same user can accept an interview panel invitation") public boolean userCanAcceptInterviewInvite(InterviewParticipantResource interviewParticipant, UserResource user) { return user != null && interviewParticipant != null && isSameUser(interviewParticipant, user); } @PermissionRule(value = "ACCEPT", description = "only the same user can accept an interview panel invitation") boolean userCanAcceptInterviewInvite(InterviewParticipantResource interviewParticipant, UserResource user); @PermissionRule(value = "READ", description = "only the same user can read their interview panel participation") boolean userCanViewTheirOwnInterviewParticipation(InterviewParticipantResource assessmentInterviewPanelParticipant, UserResource user); } | @Test public void userCanAcceptAssessmentPanelInvite() { InterviewParticipantResource interviewParticipantResource = newInterviewParticipantResource() .withUser(1L) .build(); UserResource userResource = newUserResource() .withId(1L) .withRolesGlobal(singletonList(ASSESSOR)) .build(); assertTrue(rules.userCanAcceptInterviewInvite(interviewParticipantResource, userResource)); }
@Test public void userCanAcceptAssessmentPanelInvite_differentParticipantUser() { InterviewParticipantResource interviewParticipantResource = newInterviewParticipantResource() .withUser(1L) .build(); UserResource userResource = newUserResource() .withId(2L) .withRolesGlobal(singletonList(ASSESSOR)) .build(); assertFalse(rules.userCanAcceptInterviewInvite(interviewParticipantResource, userResource)); }
@Test public void userCanAcceptAssessmentPanelInvite_noParticipantUserAndSameEmail() { InterviewParticipantResource interviewParticipantResource = newInterviewParticipantResource() .withInvite(newInterviewInviteResource().withEmail("[email protected]")) .build(); UserResource userResource = newUserResource() .withEmail("[email protected]") .withRolesGlobal(singletonList(ASSESSOR)) .build(); assertTrue(rules.userCanAcceptInterviewInvite(interviewParticipantResource, userResource)); }
@Test public void userCanAcceptCompetitionInvite_noParticipantUserAndDifferentEmail() { InterviewParticipantResource interviewParticipantResource = newInterviewParticipantResource() .withInvite(newInterviewInviteResource().withEmail("[email protected]")) .build(); UserResource userResource = newUserResource() .withEmail("[email protected]") .withRolesGlobal(singletonList(ASSESSOR)) .build(); assertFalse(rules.userCanAcceptInterviewInvite(interviewParticipantResource, userResource)); } |
InterviewParticipantPermissionRules extends BasePermissionRules { @PermissionRule(value = "READ", description = "only the same user can read their interview panel participation") public boolean userCanViewTheirOwnInterviewParticipation(InterviewParticipantResource assessmentInterviewPanelParticipant, UserResource user) { return isSameParticipant(assessmentInterviewPanelParticipant, user); } @PermissionRule(value = "ACCEPT", description = "only the same user can accept an interview panel invitation") boolean userCanAcceptInterviewInvite(InterviewParticipantResource interviewParticipant, UserResource user); @PermissionRule(value = "READ", description = "only the same user can read their interview panel participation") boolean userCanViewTheirOwnInterviewParticipation(InterviewParticipantResource assessmentInterviewPanelParticipant, UserResource user); } | @Test public void userCanViewTheirOwnAssessmentPanelParticipation() { InterviewParticipantResource interviewParticipantResource = newInterviewParticipantResource() .withUser(7L) .withInvite(newInterviewInviteResource().withStatus(SENT).build()) .build(); UserResource userResource = newUserResource() .withId(7L) .withRolesGlobal(singletonList(ASSESSOR)) .build(); assertTrue(rules.userCanViewTheirOwnInterviewParticipation(interviewParticipantResource, userResource)); }
@Test public void userCanViewTheirOwnAssessmentPanelParticipation_differentUser() { InterviewParticipantResource interviewParticipantResource = newInterviewParticipantResource() .withUser(7L) .build(); UserResource userResource = newUserResource() .withId(11L) .withRolesGlobal(singletonList(ASSESSOR)) .build(); assertFalse(rules.userCanViewTheirOwnInterviewParticipation(interviewParticipantResource, userResource)); } |
InterviewAssignmentController { @GetMapping("/available-applications/{competitionId}") public RestResult<AvailableApplicationPageResource> getAvailableApplications( @PathVariable long competitionId, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"id"}, direction = Sort.Direction.ASC) Pageable pageable) { return interviewAssignmentService.getAvailableApplications(competitionId, pageable).toGetResponse(); } @Autowired InterviewAssignmentController(InterviewAssignmentService interviewAssignmentService,
InterviewApplicationFeedbackService interviewApplicationFeedbackService,
InterviewApplicationInviteService interviewApplicationInviteService); @GetMapping("/available-applications/{competitionId}") RestResult<AvailableApplicationPageResource> getAvailableApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/staged-applications/{competitionId}") RestResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/assigned-applications/{competitionId}") RestResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/available-application-ids/{competitionId}") RestResult<List<Long>> getAvailableApplicationIds(@PathVariable long competitionId); @PostMapping("/assign-applications") RestResult<Void> assignApplications(@Valid @RequestBody StagedApplicationListResource stagedApplicationListResource); @PostMapping("/unstage-application/{applicationId}") RestResult<Void> unstageApplication(@PathVariable long applicationId); @PostMapping("/unstage-applications/{competitionId}") RestResult<Void> unstageApplications(@PathVariable long competitionId); @GetMapping("/email-template") RestResult<ApplicantInterviewInviteResource> getEmailTemplate(); @PostMapping("/send-invites/{competitionId}") RestResult<Void> sendInvites(@PathVariable long competitionId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/is-assigned/{applicationId}") RestResult<Boolean> isApplicationAssigned(@PathVariable long applicationId); @PostMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> uploadFeedback(@RequestHeader(value = "Content-Type", required = false) String contentType,
@RequestHeader(value = "Content-Length", required = false) String contentLength,
@RequestParam(value = "filename", required = false) String originalFilename,
@PathVariable("applicationId") long applicationId,
HttpServletRequest request); @DeleteMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> deleteFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback/{applicationId}", produces = "application/json") @ResponseBody ResponseEntity<Object> downloadFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback-details/{applicationId}", produces = "application/json") RestResult<FileEntryResource> findFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/sent-invite/{applicationId}", produces = "application/json") RestResult<InterviewApplicationSentInviteResource> getSentInvite(@PathVariable("applicationId") long applicationId); @PostMapping("/resend-invite/{applicationId}") RestResult<Void> resendInvite(@PathVariable long applicationId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); } | @Test public void getAvailableApplications() throws Exception { int page = 5; int pageSize = 30; List<AvailableApplicationResource> expectedAvailableApplicationResources = newAvailableApplicationResource().build(2); AvailableApplicationPageResource expectedAvailableApplications = newAvailableApplicationPageResource() .withContent(expectedAvailableApplicationResources) .withNumber(page) .withTotalElements(300L) .withTotalPages(10) .withSize(30) .build(); Pageable pageable = PageRequest.of(page, pageSize, new Sort(ASC, "id")); when(interviewAssignmentServiceMock.getAvailableApplications(COMPETITION_ID, pageable)) .thenReturn(serviceSuccess(expectedAvailableApplications)); mockMvc.perform(get("/interview-panel/available-applications/{competition-id}", COMPETITION_ID) .param("page", String.valueOf(page)) .param("size", String.valueOf(pageSize)) .param("sort", "id")) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedAvailableApplications))); verify(interviewAssignmentServiceMock, only()).getAvailableApplications(COMPETITION_ID, pageable); } |
InterviewAssignmentController { @GetMapping("/staged-applications/{competitionId}") public RestResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications( @PathVariable long competitionId, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable) { return interviewAssignmentService.getStagedApplications(competitionId, pageable).toGetResponse(); } @Autowired InterviewAssignmentController(InterviewAssignmentService interviewAssignmentService,
InterviewApplicationFeedbackService interviewApplicationFeedbackService,
InterviewApplicationInviteService interviewApplicationInviteService); @GetMapping("/available-applications/{competitionId}") RestResult<AvailableApplicationPageResource> getAvailableApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/staged-applications/{competitionId}") RestResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/assigned-applications/{competitionId}") RestResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/available-application-ids/{competitionId}") RestResult<List<Long>> getAvailableApplicationIds(@PathVariable long competitionId); @PostMapping("/assign-applications") RestResult<Void> assignApplications(@Valid @RequestBody StagedApplicationListResource stagedApplicationListResource); @PostMapping("/unstage-application/{applicationId}") RestResult<Void> unstageApplication(@PathVariable long applicationId); @PostMapping("/unstage-applications/{competitionId}") RestResult<Void> unstageApplications(@PathVariable long competitionId); @GetMapping("/email-template") RestResult<ApplicantInterviewInviteResource> getEmailTemplate(); @PostMapping("/send-invites/{competitionId}") RestResult<Void> sendInvites(@PathVariable long competitionId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/is-assigned/{applicationId}") RestResult<Boolean> isApplicationAssigned(@PathVariable long applicationId); @PostMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> uploadFeedback(@RequestHeader(value = "Content-Type", required = false) String contentType,
@RequestHeader(value = "Content-Length", required = false) String contentLength,
@RequestParam(value = "filename", required = false) String originalFilename,
@PathVariable("applicationId") long applicationId,
HttpServletRequest request); @DeleteMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> deleteFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback/{applicationId}", produces = "application/json") @ResponseBody ResponseEntity<Object> downloadFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback-details/{applicationId}", produces = "application/json") RestResult<FileEntryResource> findFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/sent-invite/{applicationId}", produces = "application/json") RestResult<InterviewApplicationSentInviteResource> getSentInvite(@PathVariable("applicationId") long applicationId); @PostMapping("/resend-invite/{applicationId}") RestResult<Void> resendInvite(@PathVariable long applicationId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); } | @Test public void getStagedApplications() throws Exception { int page = 5; int pageSize = 30; List<InterviewAssignmentStagedApplicationResource> expectedStagedApplicationResources = newInterviewAssignmentStagedApplicationResource().build(2); InterviewAssignmentStagedApplicationPageResource expectedStagedApplications = newInterviewAssignmentStagedApplicationPageResource() .withContent(expectedStagedApplicationResources) .withNumber(page) .withTotalElements(300L) .withTotalPages(10) .withSize(30) .build(); Pageable pageable = PageRequest.of(page, pageSize, new Sort(ASC, "id")); when(interviewAssignmentServiceMock.getStagedApplications(COMPETITION_ID, pageable)) .thenReturn(serviceSuccess(expectedStagedApplications)); mockMvc.perform(get("/interview-panel/staged-applications/{competition-id}", COMPETITION_ID) .param("page", String.valueOf(page)) .param("size", String.valueOf(pageSize)) .param("sort", "id")) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedStagedApplications))); verify(interviewAssignmentServiceMock, only()).getStagedApplications(COMPETITION_ID, pageable); } |
InterviewAssignmentController { @GetMapping("/available-application-ids/{competitionId}") public RestResult<List<Long>> getAvailableApplicationIds(@PathVariable long competitionId) { return interviewAssignmentService.getAvailableApplicationIds(competitionId).toGetResponse(); } @Autowired InterviewAssignmentController(InterviewAssignmentService interviewAssignmentService,
InterviewApplicationFeedbackService interviewApplicationFeedbackService,
InterviewApplicationInviteService interviewApplicationInviteService); @GetMapping("/available-applications/{competitionId}") RestResult<AvailableApplicationPageResource> getAvailableApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/staged-applications/{competitionId}") RestResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/assigned-applications/{competitionId}") RestResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/available-application-ids/{competitionId}") RestResult<List<Long>> getAvailableApplicationIds(@PathVariable long competitionId); @PostMapping("/assign-applications") RestResult<Void> assignApplications(@Valid @RequestBody StagedApplicationListResource stagedApplicationListResource); @PostMapping("/unstage-application/{applicationId}") RestResult<Void> unstageApplication(@PathVariable long applicationId); @PostMapping("/unstage-applications/{competitionId}") RestResult<Void> unstageApplications(@PathVariable long competitionId); @GetMapping("/email-template") RestResult<ApplicantInterviewInviteResource> getEmailTemplate(); @PostMapping("/send-invites/{competitionId}") RestResult<Void> sendInvites(@PathVariable long competitionId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/is-assigned/{applicationId}") RestResult<Boolean> isApplicationAssigned(@PathVariable long applicationId); @PostMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> uploadFeedback(@RequestHeader(value = "Content-Type", required = false) String contentType,
@RequestHeader(value = "Content-Length", required = false) String contentLength,
@RequestParam(value = "filename", required = false) String originalFilename,
@PathVariable("applicationId") long applicationId,
HttpServletRequest request); @DeleteMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> deleteFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback/{applicationId}", produces = "application/json") @ResponseBody ResponseEntity<Object> downloadFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback-details/{applicationId}", produces = "application/json") RestResult<FileEntryResource> findFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/sent-invite/{applicationId}", produces = "application/json") RestResult<InterviewApplicationSentInviteResource> getSentInvite(@PathVariable("applicationId") long applicationId); @PostMapping("/resend-invite/{applicationId}") RestResult<Void> resendInvite(@PathVariable long applicationId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); } | @Test public void getAvailableApplicationIds() throws Exception { List<Long> expectedAvailableApplicationIds = asList(1L, 2L); when(interviewAssignmentServiceMock.getAvailableApplicationIds(COMPETITION_ID)) .thenReturn(serviceSuccess(expectedAvailableApplicationIds)); mockMvc.perform(get("/interview-panel/available-application-ids/{competitionId}", COMPETITION_ID)) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedAvailableApplicationIds))); verify(interviewAssignmentServiceMock, only()).getAvailableApplicationIds(COMPETITION_ID); } |
InterviewAssignmentController { @PostMapping("/assign-applications") public RestResult<Void> assignApplications(@Valid @RequestBody StagedApplicationListResource stagedApplicationListResource) { return interviewAssignmentService.assignApplications(stagedApplicationListResource.getInvites()).toPostWithBodyResponse(); } @Autowired InterviewAssignmentController(InterviewAssignmentService interviewAssignmentService,
InterviewApplicationFeedbackService interviewApplicationFeedbackService,
InterviewApplicationInviteService interviewApplicationInviteService); @GetMapping("/available-applications/{competitionId}") RestResult<AvailableApplicationPageResource> getAvailableApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/staged-applications/{competitionId}") RestResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/assigned-applications/{competitionId}") RestResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/available-application-ids/{competitionId}") RestResult<List<Long>> getAvailableApplicationIds(@PathVariable long competitionId); @PostMapping("/assign-applications") RestResult<Void> assignApplications(@Valid @RequestBody StagedApplicationListResource stagedApplicationListResource); @PostMapping("/unstage-application/{applicationId}") RestResult<Void> unstageApplication(@PathVariable long applicationId); @PostMapping("/unstage-applications/{competitionId}") RestResult<Void> unstageApplications(@PathVariable long competitionId); @GetMapping("/email-template") RestResult<ApplicantInterviewInviteResource> getEmailTemplate(); @PostMapping("/send-invites/{competitionId}") RestResult<Void> sendInvites(@PathVariable long competitionId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/is-assigned/{applicationId}") RestResult<Boolean> isApplicationAssigned(@PathVariable long applicationId); @PostMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> uploadFeedback(@RequestHeader(value = "Content-Type", required = false) String contentType,
@RequestHeader(value = "Content-Length", required = false) String contentLength,
@RequestParam(value = "filename", required = false) String originalFilename,
@PathVariable("applicationId") long applicationId,
HttpServletRequest request); @DeleteMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> deleteFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback/{applicationId}", produces = "application/json") @ResponseBody ResponseEntity<Object> downloadFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback-details/{applicationId}", produces = "application/json") RestResult<FileEntryResource> findFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/sent-invite/{applicationId}", produces = "application/json") RestResult<InterviewApplicationSentInviteResource> getSentInvite(@PathVariable("applicationId") long applicationId); @PostMapping("/resend-invite/{applicationId}") RestResult<Void> resendInvite(@PathVariable long applicationId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); } | @Test public void assignApplications() throws Exception { StagedApplicationListResource applications = newStagedApplicationListResource() .withInvites(newStagedApplicationResource().build(2)) .build(); when(interviewAssignmentServiceMock.assignApplications(applications.getInvites())).thenReturn(serviceSuccess()); mockMvc.perform(post("/interview-panel/assign-applications") .contentType(APPLICATION_JSON) .content(toJson(applications))) .andExpect(status().isOk()); verify(interviewAssignmentServiceMock, only()).assignApplications(applications.getInvites()); } |
InterviewAssignmentController { @PostMapping("/unstage-application/{applicationId}") public RestResult<Void> unstageApplication(@PathVariable long applicationId) { return interviewAssignmentService.unstageApplication(applicationId).toPostWithBodyResponse(); } @Autowired InterviewAssignmentController(InterviewAssignmentService interviewAssignmentService,
InterviewApplicationFeedbackService interviewApplicationFeedbackService,
InterviewApplicationInviteService interviewApplicationInviteService); @GetMapping("/available-applications/{competitionId}") RestResult<AvailableApplicationPageResource> getAvailableApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/staged-applications/{competitionId}") RestResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/assigned-applications/{competitionId}") RestResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/available-application-ids/{competitionId}") RestResult<List<Long>> getAvailableApplicationIds(@PathVariable long competitionId); @PostMapping("/assign-applications") RestResult<Void> assignApplications(@Valid @RequestBody StagedApplicationListResource stagedApplicationListResource); @PostMapping("/unstage-application/{applicationId}") RestResult<Void> unstageApplication(@PathVariable long applicationId); @PostMapping("/unstage-applications/{competitionId}") RestResult<Void> unstageApplications(@PathVariable long competitionId); @GetMapping("/email-template") RestResult<ApplicantInterviewInviteResource> getEmailTemplate(); @PostMapping("/send-invites/{competitionId}") RestResult<Void> sendInvites(@PathVariable long competitionId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/is-assigned/{applicationId}") RestResult<Boolean> isApplicationAssigned(@PathVariable long applicationId); @PostMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> uploadFeedback(@RequestHeader(value = "Content-Type", required = false) String contentType,
@RequestHeader(value = "Content-Length", required = false) String contentLength,
@RequestParam(value = "filename", required = false) String originalFilename,
@PathVariable("applicationId") long applicationId,
HttpServletRequest request); @DeleteMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> deleteFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback/{applicationId}", produces = "application/json") @ResponseBody ResponseEntity<Object> downloadFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback-details/{applicationId}", produces = "application/json") RestResult<FileEntryResource> findFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/sent-invite/{applicationId}", produces = "application/json") RestResult<InterviewApplicationSentInviteResource> getSentInvite(@PathVariable("applicationId") long applicationId); @PostMapping("/resend-invite/{applicationId}") RestResult<Void> resendInvite(@PathVariable long applicationId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); } | @Test public void unstageApplication() throws Exception { long applicationId = 1L; when(interviewAssignmentServiceMock.unstageApplication(applicationId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/interview-panel/unstage-application/{applicationId}", applicationId) .contentType(APPLICATION_JSON)) .andExpect(status().isOk()); verify(interviewAssignmentServiceMock, only()).unstageApplication(applicationId); } |
InterviewAssignmentController { @PostMapping("/unstage-applications/{competitionId}") public RestResult<Void> unstageApplications(@PathVariable long competitionId) { return interviewAssignmentService.unstageApplications(competitionId).toPostWithBodyResponse(); } @Autowired InterviewAssignmentController(InterviewAssignmentService interviewAssignmentService,
InterviewApplicationFeedbackService interviewApplicationFeedbackService,
InterviewApplicationInviteService interviewApplicationInviteService); @GetMapping("/available-applications/{competitionId}") RestResult<AvailableApplicationPageResource> getAvailableApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/staged-applications/{competitionId}") RestResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/assigned-applications/{competitionId}") RestResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/available-application-ids/{competitionId}") RestResult<List<Long>> getAvailableApplicationIds(@PathVariable long competitionId); @PostMapping("/assign-applications") RestResult<Void> assignApplications(@Valid @RequestBody StagedApplicationListResource stagedApplicationListResource); @PostMapping("/unstage-application/{applicationId}") RestResult<Void> unstageApplication(@PathVariable long applicationId); @PostMapping("/unstage-applications/{competitionId}") RestResult<Void> unstageApplications(@PathVariable long competitionId); @GetMapping("/email-template") RestResult<ApplicantInterviewInviteResource> getEmailTemplate(); @PostMapping("/send-invites/{competitionId}") RestResult<Void> sendInvites(@PathVariable long competitionId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/is-assigned/{applicationId}") RestResult<Boolean> isApplicationAssigned(@PathVariable long applicationId); @PostMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> uploadFeedback(@RequestHeader(value = "Content-Type", required = false) String contentType,
@RequestHeader(value = "Content-Length", required = false) String contentLength,
@RequestParam(value = "filename", required = false) String originalFilename,
@PathVariable("applicationId") long applicationId,
HttpServletRequest request); @DeleteMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> deleteFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback/{applicationId}", produces = "application/json") @ResponseBody ResponseEntity<Object> downloadFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback-details/{applicationId}", produces = "application/json") RestResult<FileEntryResource> findFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/sent-invite/{applicationId}", produces = "application/json") RestResult<InterviewApplicationSentInviteResource> getSentInvite(@PathVariable("applicationId") long applicationId); @PostMapping("/resend-invite/{applicationId}") RestResult<Void> resendInvite(@PathVariable long applicationId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); } | @Test public void unstageApplications() throws Exception { long competitionId = 1L; when(interviewAssignmentServiceMock.unstageApplications(competitionId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/interview-panel/unstage-applications/{competitionId}", competitionId) .contentType(APPLICATION_JSON)) .andExpect(status().isOk()); verify(interviewAssignmentServiceMock, only()).unstageApplications(competitionId); } |
InterviewAssignmentController { @GetMapping("/email-template") public RestResult<ApplicantInterviewInviteResource> getEmailTemplate() { return interviewApplicationInviteService.getEmailTemplate().toGetResponse(); } @Autowired InterviewAssignmentController(InterviewAssignmentService interviewAssignmentService,
InterviewApplicationFeedbackService interviewApplicationFeedbackService,
InterviewApplicationInviteService interviewApplicationInviteService); @GetMapping("/available-applications/{competitionId}") RestResult<AvailableApplicationPageResource> getAvailableApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/staged-applications/{competitionId}") RestResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/assigned-applications/{competitionId}") RestResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/available-application-ids/{competitionId}") RestResult<List<Long>> getAvailableApplicationIds(@PathVariable long competitionId); @PostMapping("/assign-applications") RestResult<Void> assignApplications(@Valid @RequestBody StagedApplicationListResource stagedApplicationListResource); @PostMapping("/unstage-application/{applicationId}") RestResult<Void> unstageApplication(@PathVariable long applicationId); @PostMapping("/unstage-applications/{competitionId}") RestResult<Void> unstageApplications(@PathVariable long competitionId); @GetMapping("/email-template") RestResult<ApplicantInterviewInviteResource> getEmailTemplate(); @PostMapping("/send-invites/{competitionId}") RestResult<Void> sendInvites(@PathVariable long competitionId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/is-assigned/{applicationId}") RestResult<Boolean> isApplicationAssigned(@PathVariable long applicationId); @PostMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> uploadFeedback(@RequestHeader(value = "Content-Type", required = false) String contentType,
@RequestHeader(value = "Content-Length", required = false) String contentLength,
@RequestParam(value = "filename", required = false) String originalFilename,
@PathVariable("applicationId") long applicationId,
HttpServletRequest request); @DeleteMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> deleteFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback/{applicationId}", produces = "application/json") @ResponseBody ResponseEntity<Object> downloadFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback-details/{applicationId}", produces = "application/json") RestResult<FileEntryResource> findFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/sent-invite/{applicationId}", produces = "application/json") RestResult<InterviewApplicationSentInviteResource> getSentInvite(@PathVariable("applicationId") long applicationId); @PostMapping("/resend-invite/{applicationId}") RestResult<Void> resendInvite(@PathVariable long applicationId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); } | @Test public void getEmailTemplate() throws Exception { ApplicantInterviewInviteResource interviewInviteResource = new ApplicantInterviewInviteResource("content"); when(interviewApplicationInviteServiceMock.getEmailTemplate()).thenReturn(serviceSuccess(interviewInviteResource)); mockMvc.perform(get("/interview-panel/email-template") .contentType(APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().json(toJson(interviewInviteResource))); verify(interviewApplicationInviteServiceMock, only()).getEmailTemplate(); } |
InterviewAssignmentController { @PostMapping("/send-invites/{competitionId}") public RestResult<Void> sendInvites(@PathVariable long competitionId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource) { return interviewApplicationInviteService.sendInvites(competitionId, assessorInviteSendResource).toPostWithBodyResponse(); } @Autowired InterviewAssignmentController(InterviewAssignmentService interviewAssignmentService,
InterviewApplicationFeedbackService interviewApplicationFeedbackService,
InterviewApplicationInviteService interviewApplicationInviteService); @GetMapping("/available-applications/{competitionId}") RestResult<AvailableApplicationPageResource> getAvailableApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/staged-applications/{competitionId}") RestResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/assigned-applications/{competitionId}") RestResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/available-application-ids/{competitionId}") RestResult<List<Long>> getAvailableApplicationIds(@PathVariable long competitionId); @PostMapping("/assign-applications") RestResult<Void> assignApplications(@Valid @RequestBody StagedApplicationListResource stagedApplicationListResource); @PostMapping("/unstage-application/{applicationId}") RestResult<Void> unstageApplication(@PathVariable long applicationId); @PostMapping("/unstage-applications/{competitionId}") RestResult<Void> unstageApplications(@PathVariable long competitionId); @GetMapping("/email-template") RestResult<ApplicantInterviewInviteResource> getEmailTemplate(); @PostMapping("/send-invites/{competitionId}") RestResult<Void> sendInvites(@PathVariable long competitionId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/is-assigned/{applicationId}") RestResult<Boolean> isApplicationAssigned(@PathVariable long applicationId); @PostMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> uploadFeedback(@RequestHeader(value = "Content-Type", required = false) String contentType,
@RequestHeader(value = "Content-Length", required = false) String contentLength,
@RequestParam(value = "filename", required = false) String originalFilename,
@PathVariable("applicationId") long applicationId,
HttpServletRequest request); @DeleteMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> deleteFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback/{applicationId}", produces = "application/json") @ResponseBody ResponseEntity<Object> downloadFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback-details/{applicationId}", produces = "application/json") RestResult<FileEntryResource> findFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/sent-invite/{applicationId}", produces = "application/json") RestResult<InterviewApplicationSentInviteResource> getSentInvite(@PathVariable("applicationId") long applicationId); @PostMapping("/resend-invite/{applicationId}") RestResult<Void> resendInvite(@PathVariable long applicationId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); } | @Test public void sendInvites() throws Exception { long competitionId = 1L; AssessorInviteSendResource sendResource = new AssessorInviteSendResource("Subject", "Content"); when(interviewApplicationInviteServiceMock.sendInvites(competitionId, sendResource)).thenReturn(serviceSuccess()); mockMvc.perform(post("/interview-panel/send-invites/{competitionId}", competitionId) .contentType(APPLICATION_JSON) .content(toJson(sendResource))) .andExpect(status().isOk()); verify(interviewApplicationInviteServiceMock, only()).sendInvites(competitionId, sendResource); } |
InterviewAssignmentController { @GetMapping("/is-assigned/{applicationId}") public RestResult<Boolean> isApplicationAssigned(@PathVariable long applicationId) { return interviewAssignmentService.isApplicationAssigned(applicationId).toGetResponse(); } @Autowired InterviewAssignmentController(InterviewAssignmentService interviewAssignmentService,
InterviewApplicationFeedbackService interviewApplicationFeedbackService,
InterviewApplicationInviteService interviewApplicationInviteService); @GetMapping("/available-applications/{competitionId}") RestResult<AvailableApplicationPageResource> getAvailableApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/staged-applications/{competitionId}") RestResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/assigned-applications/{competitionId}") RestResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/available-application-ids/{competitionId}") RestResult<List<Long>> getAvailableApplicationIds(@PathVariable long competitionId); @PostMapping("/assign-applications") RestResult<Void> assignApplications(@Valid @RequestBody StagedApplicationListResource stagedApplicationListResource); @PostMapping("/unstage-application/{applicationId}") RestResult<Void> unstageApplication(@PathVariable long applicationId); @PostMapping("/unstage-applications/{competitionId}") RestResult<Void> unstageApplications(@PathVariable long competitionId); @GetMapping("/email-template") RestResult<ApplicantInterviewInviteResource> getEmailTemplate(); @PostMapping("/send-invites/{competitionId}") RestResult<Void> sendInvites(@PathVariable long competitionId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/is-assigned/{applicationId}") RestResult<Boolean> isApplicationAssigned(@PathVariable long applicationId); @PostMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> uploadFeedback(@RequestHeader(value = "Content-Type", required = false) String contentType,
@RequestHeader(value = "Content-Length", required = false) String contentLength,
@RequestParam(value = "filename", required = false) String originalFilename,
@PathVariable("applicationId") long applicationId,
HttpServletRequest request); @DeleteMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> deleteFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback/{applicationId}", produces = "application/json") @ResponseBody ResponseEntity<Object> downloadFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback-details/{applicationId}", produces = "application/json") RestResult<FileEntryResource> findFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/sent-invite/{applicationId}", produces = "application/json") RestResult<InterviewApplicationSentInviteResource> getSentInvite(@PathVariable("applicationId") long applicationId); @PostMapping("/resend-invite/{applicationId}") RestResult<Void> resendInvite(@PathVariable long applicationId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); } | @Test public void isApplicationAssigned() throws Exception { long applicationId = 1L; when(interviewAssignmentServiceMock.isApplicationAssigned(applicationId)).thenReturn(serviceSuccess(true)); mockMvc.perform(get("/interview-panel/is-assigned/{applicationId}", applicationId) .contentType(APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string("true")); verify(interviewAssignmentServiceMock, only()).isApplicationAssigned(applicationId); } |
InterviewAssignmentController { @PostMapping(value = "/feedback/{applicationId}", produces = "application/json") public RestResult<Void> uploadFeedback(@RequestHeader(value = "Content-Type", required = false) String contentType, @RequestHeader(value = "Content-Length", required = false) String contentLength, @RequestParam(value = "filename", required = false) String originalFilename, @PathVariable("applicationId") long applicationId, HttpServletRequest request) { return interviewApplicationFeedbackService.uploadFeedback(contentType, contentLength, originalFilename, applicationId, request).toPostCreateResponse(); } @Autowired InterviewAssignmentController(InterviewAssignmentService interviewAssignmentService,
InterviewApplicationFeedbackService interviewApplicationFeedbackService,
InterviewApplicationInviteService interviewApplicationInviteService); @GetMapping("/available-applications/{competitionId}") RestResult<AvailableApplicationPageResource> getAvailableApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/staged-applications/{competitionId}") RestResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/assigned-applications/{competitionId}") RestResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/available-application-ids/{competitionId}") RestResult<List<Long>> getAvailableApplicationIds(@PathVariable long competitionId); @PostMapping("/assign-applications") RestResult<Void> assignApplications(@Valid @RequestBody StagedApplicationListResource stagedApplicationListResource); @PostMapping("/unstage-application/{applicationId}") RestResult<Void> unstageApplication(@PathVariable long applicationId); @PostMapping("/unstage-applications/{competitionId}") RestResult<Void> unstageApplications(@PathVariable long competitionId); @GetMapping("/email-template") RestResult<ApplicantInterviewInviteResource> getEmailTemplate(); @PostMapping("/send-invites/{competitionId}") RestResult<Void> sendInvites(@PathVariable long competitionId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/is-assigned/{applicationId}") RestResult<Boolean> isApplicationAssigned(@PathVariable long applicationId); @PostMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> uploadFeedback(@RequestHeader(value = "Content-Type", required = false) String contentType,
@RequestHeader(value = "Content-Length", required = false) String contentLength,
@RequestParam(value = "filename", required = false) String originalFilename,
@PathVariable("applicationId") long applicationId,
HttpServletRequest request); @DeleteMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> deleteFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback/{applicationId}", produces = "application/json") @ResponseBody ResponseEntity<Object> downloadFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback-details/{applicationId}", produces = "application/json") RestResult<FileEntryResource> findFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/sent-invite/{applicationId}", produces = "application/json") RestResult<InterviewApplicationSentInviteResource> getSentInvite(@PathVariable("applicationId") long applicationId); @PostMapping("/resend-invite/{applicationId}") RestResult<Void> resendInvite(@PathVariable long applicationId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); } | @Test public void testUploadFeedback() throws Exception { final long applicationId = 77L; when(interviewApplicationFeedbackServiceMock.uploadFeedback(eq("application/pdf"), eq("1234"), eq("randomFile.pdf"), eq(applicationId), any(HttpServletRequest.class))).thenReturn(serviceSuccess()); mockMvc.perform(post("/interview-panel/feedback/{applicationId}", applicationId) .param("filename", "randomFile.pdf") .headers(createFileUploadHeader("application/pdf", 1234))) .andExpect(status().isCreated()); verify(interviewApplicationFeedbackServiceMock).uploadFeedback(eq("application/pdf"), eq("1234"), eq("randomFile.pdf"), eq(applicationId), any(HttpServletRequest.class)); } |
InterviewAssignmentController { @GetMapping(value = "/sent-invite/{applicationId}", produces = "application/json") public RestResult<InterviewApplicationSentInviteResource> getSentInvite(@PathVariable("applicationId") long applicationId) throws IOException { return interviewApplicationInviteService.getSentInvite(applicationId).toGetResponse(); } @Autowired InterviewAssignmentController(InterviewAssignmentService interviewAssignmentService,
InterviewApplicationFeedbackService interviewApplicationFeedbackService,
InterviewApplicationInviteService interviewApplicationInviteService); @GetMapping("/available-applications/{competitionId}") RestResult<AvailableApplicationPageResource> getAvailableApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/staged-applications/{competitionId}") RestResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/assigned-applications/{competitionId}") RestResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/available-application-ids/{competitionId}") RestResult<List<Long>> getAvailableApplicationIds(@PathVariable long competitionId); @PostMapping("/assign-applications") RestResult<Void> assignApplications(@Valid @RequestBody StagedApplicationListResource stagedApplicationListResource); @PostMapping("/unstage-application/{applicationId}") RestResult<Void> unstageApplication(@PathVariable long applicationId); @PostMapping("/unstage-applications/{competitionId}") RestResult<Void> unstageApplications(@PathVariable long competitionId); @GetMapping("/email-template") RestResult<ApplicantInterviewInviteResource> getEmailTemplate(); @PostMapping("/send-invites/{competitionId}") RestResult<Void> sendInvites(@PathVariable long competitionId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/is-assigned/{applicationId}") RestResult<Boolean> isApplicationAssigned(@PathVariable long applicationId); @PostMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> uploadFeedback(@RequestHeader(value = "Content-Type", required = false) String contentType,
@RequestHeader(value = "Content-Length", required = false) String contentLength,
@RequestParam(value = "filename", required = false) String originalFilename,
@PathVariable("applicationId") long applicationId,
HttpServletRequest request); @DeleteMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> deleteFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback/{applicationId}", produces = "application/json") @ResponseBody ResponseEntity<Object> downloadFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback-details/{applicationId}", produces = "application/json") RestResult<FileEntryResource> findFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/sent-invite/{applicationId}", produces = "application/json") RestResult<InterviewApplicationSentInviteResource> getSentInvite(@PathVariable("applicationId") long applicationId); @PostMapping("/resend-invite/{applicationId}") RestResult<Void> resendInvite(@PathVariable long applicationId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); } | @Test public void getSentInvite() throws Exception { long applicationId = 1L; InterviewApplicationSentInviteResource invite = newInterviewApplicationSentInviteResource().build(); when(interviewApplicationInviteServiceMock.getSentInvite(applicationId)).thenReturn(serviceSuccess(invite)); mockMvc.perform(get("/interview-panel/sent-invite/{applicationId}", applicationId) .contentType(APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().json(toJson(invite))); verify(interviewApplicationInviteServiceMock, only()).getSentInvite(applicationId); } |
InterviewAssignmentController { @PostMapping("/resend-invite/{applicationId}") public RestResult<Void> resendInvite(@PathVariable long applicationId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource) { return interviewApplicationInviteService.resendInvite(applicationId, assessorInviteSendResource).toPostWithBodyResponse(); } @Autowired InterviewAssignmentController(InterviewAssignmentService interviewAssignmentService,
InterviewApplicationFeedbackService interviewApplicationFeedbackService,
InterviewApplicationInviteService interviewApplicationInviteService); @GetMapping("/available-applications/{competitionId}") RestResult<AvailableApplicationPageResource> getAvailableApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/staged-applications/{competitionId}") RestResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/assigned-applications/{competitionId}") RestResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"target.id"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/available-application-ids/{competitionId}") RestResult<List<Long>> getAvailableApplicationIds(@PathVariable long competitionId); @PostMapping("/assign-applications") RestResult<Void> assignApplications(@Valid @RequestBody StagedApplicationListResource stagedApplicationListResource); @PostMapping("/unstage-application/{applicationId}") RestResult<Void> unstageApplication(@PathVariable long applicationId); @PostMapping("/unstage-applications/{competitionId}") RestResult<Void> unstageApplications(@PathVariable long competitionId); @GetMapping("/email-template") RestResult<ApplicantInterviewInviteResource> getEmailTemplate(); @PostMapping("/send-invites/{competitionId}") RestResult<Void> sendInvites(@PathVariable long competitionId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/is-assigned/{applicationId}") RestResult<Boolean> isApplicationAssigned(@PathVariable long applicationId); @PostMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> uploadFeedback(@RequestHeader(value = "Content-Type", required = false) String contentType,
@RequestHeader(value = "Content-Length", required = false) String contentLength,
@RequestParam(value = "filename", required = false) String originalFilename,
@PathVariable("applicationId") long applicationId,
HttpServletRequest request); @DeleteMapping(value = "/feedback/{applicationId}", produces = "application/json") RestResult<Void> deleteFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback/{applicationId}", produces = "application/json") @ResponseBody ResponseEntity<Object> downloadFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/feedback-details/{applicationId}", produces = "application/json") RestResult<FileEntryResource> findFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/sent-invite/{applicationId}", produces = "application/json") RestResult<InterviewApplicationSentInviteResource> getSentInvite(@PathVariable("applicationId") long applicationId); @PostMapping("/resend-invite/{applicationId}") RestResult<Void> resendInvite(@PathVariable long applicationId, @Valid @RequestBody AssessorInviteSendResource assessorInviteSendResource); } | @Test public void resendInvite() throws Exception { long applicationId = 1L; AssessorInviteSendResource sendResource = new AssessorInviteSendResource("Subject", "Content"); when(interviewApplicationInviteServiceMock.resendInvite(applicationId, sendResource)).thenReturn(serviceSuccess()); mockMvc.perform(post("/interview-panel/resend-invite/{applicationId}", applicationId) .contentType(APPLICATION_JSON) .content(toJson(sendResource))) .andExpect(status().isOk()); verify(interviewApplicationInviteServiceMock, only()).resendInvite(applicationId, sendResource); } |
InterviewResponseController { @PostMapping(value = "/{applicationId}", produces = "application/json") public RestResult<Void> uploadResponse(@RequestHeader(value = "Content-Type", required = false) String contentType, @RequestHeader(value = "Content-Length", required = false) String contentLength, @RequestParam(value = "filename", required = false) String originalFilename, @PathVariable("applicationId") long applicationId, HttpServletRequest request) { return interviewResponseService.uploadResponse(contentType, contentLength, originalFilename, applicationId, request).toPostCreateResponse(); } @Autowired InterviewResponseController(InterviewResponseService interviewResponseService); @PostMapping(value = "/{applicationId}", produces = "application/json") RestResult<Void> uploadResponse(@RequestHeader(value = "Content-Type", required = false) String contentType,
@RequestHeader(value = "Content-Length", required = false) String contentLength,
@RequestParam(value = "filename", required = false) String originalFilename,
@PathVariable("applicationId") long applicationId,
HttpServletRequest request); @DeleteMapping(value = "/{applicationId}", produces = "application/json") RestResult<Void> deleteFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/{applicationId}", produces = "application/json") @ResponseBody ResponseEntity<Object> downloadFile(@PathVariable("applicationId") long applicationId); @GetMapping(value = "/details/{applicationId}", produces = "application/json") RestResult<FileEntryResource> findFile(@PathVariable("applicationId") long applicationId); } | @Test public void testUploadResponse() throws Exception { final long applicationId = 77L; when(interviewResponseService.uploadResponse(eq("application/pdf"), eq("1234"), eq("randomFile.pdf"), eq(applicationId), any(HttpServletRequest.class))).thenReturn(serviceSuccess()); mockMvc.perform(post("/interview-response/{applicationId}", applicationId) .param("filename", "randomFile.pdf") .headers(createFileUploadHeader("application/pdf", 1234))) .andExpect(status().isCreated()); verify(interviewResponseService).uploadResponse(eq("application/pdf"), eq("1234"), eq("randomFile.pdf"), eq(applicationId), any(HttpServletRequest.class)); } |
InterviewAllocationController { @GetMapping("/allocate-assessors/{competitionId}") public RestResult<InterviewAcceptedAssessorsPageResource> getInterviewAcceptedAssessors( @PathVariable long competitionId, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable) { return interviewAllocationService.getInterviewAcceptedAssessors(competitionId, pageable).toGetResponse(); } @GetMapping("/allocate-assessors/{competitionId}") RestResult<InterviewAcceptedAssessorsPageResource> getInterviewAcceptedAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/allocated-applications/{assessorId}") RestResult<InterviewApplicationPageResource> getAllocatedApplications(
@PathVariable long competitionId,
@PathVariable long assessorId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "target.id", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/allocated-applications-assessor-id/{assessorId}") RestResult<List<InterviewResource>> getAllocatedApplicationsByAssessorId(
@PathVariable long competitionId,
@PathVariable long assessorId
); @GetMapping("/{competitionId}/unallocated-applications/all/{applicationIds}") RestResult<List<InterviewApplicationResource>> getAllocatedApplications(@PathVariable List<Long> applicationIds); @GetMapping("/{competitionId}/allocated-applications/{assessorId}/invite-to-send") RestResult<AssessorInvitesToSendResource> getInviteToSend(@PathVariable long competitionId, @PathVariable long assessorId); @PostMapping("/{competitionId}/allocated-applications/{assessorId}/send-invite") RestResult<Void> sendInvite(@RequestBody InterviewNotifyAllocationResource interviewNotifyAllocationResource); @PostMapping("/allocated-applications/{assessorId}/unallocate/{applicationId}") RestResult<Void> unallocateApplication(@PathVariable long assessorId, @PathVariable long applicationId); @GetMapping("/{competitionId}/unallocated-applications/{assessorId}") RestResult<InterviewApplicationPageResource> getUnallocatedApplications(
@PathVariable long competitionId,
@PathVariable long assessorId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "target.id", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/unallocated-application-ids/{assessorId}") RestResult<List<Long>> getUnallocatedApplicationIds(
@PathVariable long competitionId,
@PathVariable long assessorId); } | @Test public void getInterviewAcceptedAssessors() throws Exception { long competitionId = 1L; int page = 2; int size = 10; InterviewAcceptedAssessorsPageResource expectedPageResource = newInterviewAcceptedAssessorsPageResource() .withContent(newInterviewAcceptedAssessorsResource().build(2)) .build(); Pageable pageable = PageRequest.of(page, size, new Sort(Sort.Direction.ASC, "invite.email")); when(interviewAllocationServiceMock.getInterviewAcceptedAssessors(competitionId, pageable)) .thenReturn(serviceSuccess(expectedPageResource)); mockMvc.perform(get("/interview-panel/allocate-assessors/{competitionId}", competitionId) .param("page", "2") .param("size", "10") .param("sort", "invite.email")) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedPageResource))); verify(interviewAllocationServiceMock, only()).getInterviewAcceptedAssessors(competitionId, pageable); } |
InterviewAllocationController { @GetMapping("/{competitionId}/allocated-applications/{assessorId}") public RestResult<InterviewApplicationPageResource> getAllocatedApplications( @PathVariable long competitionId, @PathVariable long assessorId, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "target.id", direction = Sort.Direction.ASC) Pageable pageable) { return interviewAllocationService.getAllocatedApplications(competitionId, assessorId, pageable).toGetResponse(); } @GetMapping("/allocate-assessors/{competitionId}") RestResult<InterviewAcceptedAssessorsPageResource> getInterviewAcceptedAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/allocated-applications/{assessorId}") RestResult<InterviewApplicationPageResource> getAllocatedApplications(
@PathVariable long competitionId,
@PathVariable long assessorId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "target.id", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/allocated-applications-assessor-id/{assessorId}") RestResult<List<InterviewResource>> getAllocatedApplicationsByAssessorId(
@PathVariable long competitionId,
@PathVariable long assessorId
); @GetMapping("/{competitionId}/unallocated-applications/all/{applicationIds}") RestResult<List<InterviewApplicationResource>> getAllocatedApplications(@PathVariable List<Long> applicationIds); @GetMapping("/{competitionId}/allocated-applications/{assessorId}/invite-to-send") RestResult<AssessorInvitesToSendResource> getInviteToSend(@PathVariable long competitionId, @PathVariable long assessorId); @PostMapping("/{competitionId}/allocated-applications/{assessorId}/send-invite") RestResult<Void> sendInvite(@RequestBody InterviewNotifyAllocationResource interviewNotifyAllocationResource); @PostMapping("/allocated-applications/{assessorId}/unallocate/{applicationId}") RestResult<Void> unallocateApplication(@PathVariable long assessorId, @PathVariable long applicationId); @GetMapping("/{competitionId}/unallocated-applications/{assessorId}") RestResult<InterviewApplicationPageResource> getUnallocatedApplications(
@PathVariable long competitionId,
@PathVariable long assessorId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "target.id", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/unallocated-application-ids/{assessorId}") RestResult<List<Long>> getUnallocatedApplicationIds(
@PathVariable long competitionId,
@PathVariable long assessorId); } | @Test public void getAllocatedApplications() throws Exception { long competitionId = 1L; long userId = 2L; int page = 2; int size = 10; InterviewApplicationPageResource expectedPageResource = newInterviewApplicationPageResource() .withContent(newInterviewApplicationResource().build(2)) .build(); Pageable pageable = PageRequest.of(page, size, new Sort(Sort.Direction.ASC, "target.id")); when(interviewAllocationServiceMock.getAllocatedApplications(competitionId, userId, pageable)) .thenReturn(serviceSuccess(expectedPageResource)); mockMvc.perform(get("/interview-panel/{competitionId}/allocated-applications/{userId}", competitionId, userId) .param("page", "2") .param("size", "10") .param("sort", "target.id")) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedPageResource))); verify(interviewAllocationServiceMock, only()).getAllocatedApplications(competitionId, userId, pageable); } |
InterviewAllocationController { @GetMapping("/{competitionId}/allocated-applications-assessor-id/{assessorId}") public RestResult<List<InterviewResource>> getAllocatedApplicationsByAssessorId( @PathVariable long competitionId, @PathVariable long assessorId ) { return interviewAllocationService.getAllocatedApplicationsByAssessorId(competitionId, assessorId).toGetResponse(); } @GetMapping("/allocate-assessors/{competitionId}") RestResult<InterviewAcceptedAssessorsPageResource> getInterviewAcceptedAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/allocated-applications/{assessorId}") RestResult<InterviewApplicationPageResource> getAllocatedApplications(
@PathVariable long competitionId,
@PathVariable long assessorId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "target.id", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/allocated-applications-assessor-id/{assessorId}") RestResult<List<InterviewResource>> getAllocatedApplicationsByAssessorId(
@PathVariable long competitionId,
@PathVariable long assessorId
); @GetMapping("/{competitionId}/unallocated-applications/all/{applicationIds}") RestResult<List<InterviewApplicationResource>> getAllocatedApplications(@PathVariable List<Long> applicationIds); @GetMapping("/{competitionId}/allocated-applications/{assessorId}/invite-to-send") RestResult<AssessorInvitesToSendResource> getInviteToSend(@PathVariable long competitionId, @PathVariable long assessorId); @PostMapping("/{competitionId}/allocated-applications/{assessorId}/send-invite") RestResult<Void> sendInvite(@RequestBody InterviewNotifyAllocationResource interviewNotifyAllocationResource); @PostMapping("/allocated-applications/{assessorId}/unallocate/{applicationId}") RestResult<Void> unallocateApplication(@PathVariable long assessorId, @PathVariable long applicationId); @GetMapping("/{competitionId}/unallocated-applications/{assessorId}") RestResult<InterviewApplicationPageResource> getUnallocatedApplications(
@PathVariable long competitionId,
@PathVariable long assessorId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "target.id", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/unallocated-application-ids/{assessorId}") RestResult<List<Long>> getUnallocatedApplicationIds(
@PathVariable long competitionId,
@PathVariable long assessorId); } | @Test public void getAllocatedApplicationsByAssessorId() throws Exception { long competitionId = 1L; long userId = 2L; List<InterviewResource> expectedInterviewResources = newInterviewResource() .build(2); when(interviewAllocationServiceMock.getAllocatedApplicationsByAssessorId(competitionId, userId)) .thenReturn(serviceSuccess(expectedInterviewResources)); mockMvc.perform(get("/interview-panel/{competitionId}/allocated-applications-assessor-id/{userId}", competitionId, userId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedInterviewResources))); verify(interviewAllocationServiceMock, only()).getAllocatedApplicationsByAssessorId(competitionId, userId); } |
InterviewAllocationController { @GetMapping("/{competitionId}/unallocated-applications/{assessorId}") public RestResult<InterviewApplicationPageResource> getUnallocatedApplications( @PathVariable long competitionId, @PathVariable long assessorId, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "target.id", direction = Sort.Direction.ASC) Pageable pageable) { return interviewAllocationService.getUnallocatedApplications(competitionId, assessorId, pageable).toGetResponse(); } @GetMapping("/allocate-assessors/{competitionId}") RestResult<InterviewAcceptedAssessorsPageResource> getInterviewAcceptedAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/allocated-applications/{assessorId}") RestResult<InterviewApplicationPageResource> getAllocatedApplications(
@PathVariable long competitionId,
@PathVariable long assessorId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "target.id", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/allocated-applications-assessor-id/{assessorId}") RestResult<List<InterviewResource>> getAllocatedApplicationsByAssessorId(
@PathVariable long competitionId,
@PathVariable long assessorId
); @GetMapping("/{competitionId}/unallocated-applications/all/{applicationIds}") RestResult<List<InterviewApplicationResource>> getAllocatedApplications(@PathVariable List<Long> applicationIds); @GetMapping("/{competitionId}/allocated-applications/{assessorId}/invite-to-send") RestResult<AssessorInvitesToSendResource> getInviteToSend(@PathVariable long competitionId, @PathVariable long assessorId); @PostMapping("/{competitionId}/allocated-applications/{assessorId}/send-invite") RestResult<Void> sendInvite(@RequestBody InterviewNotifyAllocationResource interviewNotifyAllocationResource); @PostMapping("/allocated-applications/{assessorId}/unallocate/{applicationId}") RestResult<Void> unallocateApplication(@PathVariable long assessorId, @PathVariable long applicationId); @GetMapping("/{competitionId}/unallocated-applications/{assessorId}") RestResult<InterviewApplicationPageResource> getUnallocatedApplications(
@PathVariable long competitionId,
@PathVariable long assessorId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "target.id", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/unallocated-application-ids/{assessorId}") RestResult<List<Long>> getUnallocatedApplicationIds(
@PathVariable long competitionId,
@PathVariable long assessorId); } | @Test public void getUnallocatedApplications() throws Exception { long competitionId = 1L; long userId = 2L; int page = 2; int size = 10; InterviewApplicationPageResource expectedPageResource = newInterviewApplicationPageResource() .withContent(newInterviewApplicationResource().build(2)) .build(); Pageable pageable = PageRequest.of(page, size, new Sort(Sort.Direction.ASC, "target.id")); when(interviewAllocationServiceMock.getUnallocatedApplications(competitionId, userId, pageable)) .thenReturn(serviceSuccess(expectedPageResource)); mockMvc.perform(get("/interview-panel/{competitionId}/unallocated-applications/{userId}", competitionId, userId) .param("page", "2") .param("size", "10") .param("sort", "target.id")) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedPageResource))); verify(interviewAllocationServiceMock, only()).getUnallocatedApplications(competitionId, userId, pageable); } |
InterviewAllocationController { @GetMapping("/{competitionId}/unallocated-application-ids/{assessorId}") public RestResult<List<Long>> getUnallocatedApplicationIds( @PathVariable long competitionId, @PathVariable long assessorId) { return interviewAllocationService.getUnallocatedApplicationIds(competitionId, assessorId).toGetResponse(); } @GetMapping("/allocate-assessors/{competitionId}") RestResult<InterviewAcceptedAssessorsPageResource> getInterviewAcceptedAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/allocated-applications/{assessorId}") RestResult<InterviewApplicationPageResource> getAllocatedApplications(
@PathVariable long competitionId,
@PathVariable long assessorId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "target.id", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/allocated-applications-assessor-id/{assessorId}") RestResult<List<InterviewResource>> getAllocatedApplicationsByAssessorId(
@PathVariable long competitionId,
@PathVariable long assessorId
); @GetMapping("/{competitionId}/unallocated-applications/all/{applicationIds}") RestResult<List<InterviewApplicationResource>> getAllocatedApplications(@PathVariable List<Long> applicationIds); @GetMapping("/{competitionId}/allocated-applications/{assessorId}/invite-to-send") RestResult<AssessorInvitesToSendResource> getInviteToSend(@PathVariable long competitionId, @PathVariable long assessorId); @PostMapping("/{competitionId}/allocated-applications/{assessorId}/send-invite") RestResult<Void> sendInvite(@RequestBody InterviewNotifyAllocationResource interviewNotifyAllocationResource); @PostMapping("/allocated-applications/{assessorId}/unallocate/{applicationId}") RestResult<Void> unallocateApplication(@PathVariable long assessorId, @PathVariable long applicationId); @GetMapping("/{competitionId}/unallocated-applications/{assessorId}") RestResult<InterviewApplicationPageResource> getUnallocatedApplications(
@PathVariable long competitionId,
@PathVariable long assessorId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "target.id", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/unallocated-application-ids/{assessorId}") RestResult<List<Long>> getUnallocatedApplicationIds(
@PathVariable long competitionId,
@PathVariable long assessorId); } | @Test public void getUnallocatedApplicationIds() throws Exception { long competitionId = 1L; long userId = 2L; List<Long> ids = asList(1L); when(interviewAllocationServiceMock.getUnallocatedApplicationIds(competitionId, userId)) .thenReturn(serviceSuccess(ids)); mockMvc.perform(get("/interview-panel/{competitionId}/unallocated-application-ids/{userId}", competitionId, userId) .param("page", "2") .param("size", "10") .param("sort", "target.id")) .andExpect(status().isOk()) .andExpect(content().json(toJson(ids))); verify(interviewAllocationServiceMock, only()).getUnallocatedApplicationIds(competitionId, userId); } |
InterviewAllocationController { @GetMapping("/{competitionId}/allocated-applications/{assessorId}/invite-to-send") public RestResult<AssessorInvitesToSendResource> getInviteToSend(@PathVariable long competitionId, @PathVariable long assessorId) { return interviewAllocationService.getInviteToSend(competitionId, assessorId).toGetResponse(); } @GetMapping("/allocate-assessors/{competitionId}") RestResult<InterviewAcceptedAssessorsPageResource> getInterviewAcceptedAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/allocated-applications/{assessorId}") RestResult<InterviewApplicationPageResource> getAllocatedApplications(
@PathVariable long competitionId,
@PathVariable long assessorId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "target.id", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/allocated-applications-assessor-id/{assessorId}") RestResult<List<InterviewResource>> getAllocatedApplicationsByAssessorId(
@PathVariable long competitionId,
@PathVariable long assessorId
); @GetMapping("/{competitionId}/unallocated-applications/all/{applicationIds}") RestResult<List<InterviewApplicationResource>> getAllocatedApplications(@PathVariable List<Long> applicationIds); @GetMapping("/{competitionId}/allocated-applications/{assessorId}/invite-to-send") RestResult<AssessorInvitesToSendResource> getInviteToSend(@PathVariable long competitionId, @PathVariable long assessorId); @PostMapping("/{competitionId}/allocated-applications/{assessorId}/send-invite") RestResult<Void> sendInvite(@RequestBody InterviewNotifyAllocationResource interviewNotifyAllocationResource); @PostMapping("/allocated-applications/{assessorId}/unallocate/{applicationId}") RestResult<Void> unallocateApplication(@PathVariable long assessorId, @PathVariable long applicationId); @GetMapping("/{competitionId}/unallocated-applications/{assessorId}") RestResult<InterviewApplicationPageResource> getUnallocatedApplications(
@PathVariable long competitionId,
@PathVariable long assessorId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "target.id", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/unallocated-application-ids/{assessorId}") RestResult<List<Long>> getUnallocatedApplicationIds(
@PathVariable long competitionId,
@PathVariable long assessorId); } | @Test public void getInviteToSend() throws Exception { long competitionId = 1L; long userId = 2L; AssessorInvitesToSendResource assessorInvitesToSendResource = newAssessorInvitesToSendResource().build(); when(interviewAllocationServiceMock.getInviteToSend(competitionId, userId)).thenReturn(serviceSuccess(assessorInvitesToSendResource)); mockMvc.perform(get("/interview-panel/{competitionId}/allocated-applications/{userId}/invite-to-send", competitionId, userId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(assessorInvitesToSendResource))); verify(interviewAllocationServiceMock, only()).getInviteToSend(competitionId, userId); } |
InterviewAllocationController { @PostMapping("/{competitionId}/allocated-applications/{assessorId}/send-invite") public RestResult<Void> sendInvite(@RequestBody InterviewNotifyAllocationResource interviewNotifyAllocationResource) { return interviewAllocationService.notifyAllocation(interviewNotifyAllocationResource).toPostResponse(); } @GetMapping("/allocate-assessors/{competitionId}") RestResult<InterviewAcceptedAssessorsPageResource> getInterviewAcceptedAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/allocated-applications/{assessorId}") RestResult<InterviewApplicationPageResource> getAllocatedApplications(
@PathVariable long competitionId,
@PathVariable long assessorId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "target.id", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/allocated-applications-assessor-id/{assessorId}") RestResult<List<InterviewResource>> getAllocatedApplicationsByAssessorId(
@PathVariable long competitionId,
@PathVariable long assessorId
); @GetMapping("/{competitionId}/unallocated-applications/all/{applicationIds}") RestResult<List<InterviewApplicationResource>> getAllocatedApplications(@PathVariable List<Long> applicationIds); @GetMapping("/{competitionId}/allocated-applications/{assessorId}/invite-to-send") RestResult<AssessorInvitesToSendResource> getInviteToSend(@PathVariable long competitionId, @PathVariable long assessorId); @PostMapping("/{competitionId}/allocated-applications/{assessorId}/send-invite") RestResult<Void> sendInvite(@RequestBody InterviewNotifyAllocationResource interviewNotifyAllocationResource); @PostMapping("/allocated-applications/{assessorId}/unallocate/{applicationId}") RestResult<Void> unallocateApplication(@PathVariable long assessorId, @PathVariable long applicationId); @GetMapping("/{competitionId}/unallocated-applications/{assessorId}") RestResult<InterviewApplicationPageResource> getUnallocatedApplications(
@PathVariable long competitionId,
@PathVariable long assessorId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "target.id", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/unallocated-application-ids/{assessorId}") RestResult<List<Long>> getUnallocatedApplicationIds(
@PathVariable long competitionId,
@PathVariable long assessorId); } | @Test public void sendInvite() throws Exception { long competitionId = 1L; long userId = 2L; InterviewNotifyAllocationResource allocationResource = newInterviewNotifyAllocationResource().build(); when(interviewAllocationServiceMock.notifyAllocation(allocationResource)).thenReturn(serviceSuccess()); mockMvc.perform(post("/interview-panel/{competitionId}/allocated-applications/{assessorId}/send-invite", competitionId, userId) .contentType(MediaType.APPLICATION_JSON) .content(toJson(allocationResource))) .andExpect(status().isOk()); verify(interviewAllocationServiceMock).notifyAllocation(allocationResource); } |
PublicContentServiceImpl extends BaseTransactionalService implements PublicContentService { @Override @Transactional public ServiceResult<Void> markSectionAsComplete(PublicContentResource resource, PublicContentSectionType section) { return saveSection(resource, section) .andOnSuccessReturnVoid(publicContent -> markSectionAsComplete(publicContent, section)); } @Override ServiceResult<PublicContentResource> findByCompetitionId(long id); @Override @Transactional ServiceResult<Void> initialiseByCompetitionId(long competitionId); @Override @Transactional ServiceResult<Void> publishByCompetitionId(long competitionId); @Override @Transactional ServiceResult<Void> updateSection(PublicContentResource resource, PublicContentSectionType section); @Override @Transactional ServiceResult<Void> markSectionAsComplete(PublicContentResource resource, PublicContentSectionType section); } | @Test public void testMarkAsComplete() { PublicContent publicContent = mock(PublicContent.class); PublicContentResource publicContentResource = newPublicContentResource().withKeywords(Collections.emptyList()).build(); when(publicContentMapper.mapToDomain(publicContentResource)).thenReturn(publicContent); when(publicContentRepository.save(publicContent)).thenReturn(publicContent); ContentSection section = newContentSection().withType(PublicContentSectionType.SEARCH).withStatus(IN_PROGRESS).build(); when(publicContent.getContentSections()).thenReturn(asList(section)); when(publicContent.getId()).thenReturn(1L); when(publicContent.getPublishDate()).thenReturn(null); ServiceResult<Void> result = service.markSectionAsComplete(publicContentResource, PublicContentSectionType.SEARCH); assertThat(section.getStatus(), equalTo(COMPLETE)); assertTrue(result.isSuccess()); } |
InterviewAllocationController { @PostMapping("/allocated-applications/{assessorId}/unallocate/{applicationId}") public RestResult<Void> unallocateApplication(@PathVariable long assessorId, @PathVariable long applicationId) { return interviewAllocationService.unallocateApplication(assessorId, applicationId).toPostResponse(); } @GetMapping("/allocate-assessors/{competitionId}") RestResult<InterviewAcceptedAssessorsPageResource> getInterviewAcceptedAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/allocated-applications/{assessorId}") RestResult<InterviewApplicationPageResource> getAllocatedApplications(
@PathVariable long competitionId,
@PathVariable long assessorId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "target.id", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/allocated-applications-assessor-id/{assessorId}") RestResult<List<InterviewResource>> getAllocatedApplicationsByAssessorId(
@PathVariable long competitionId,
@PathVariable long assessorId
); @GetMapping("/{competitionId}/unallocated-applications/all/{applicationIds}") RestResult<List<InterviewApplicationResource>> getAllocatedApplications(@PathVariable List<Long> applicationIds); @GetMapping("/{competitionId}/allocated-applications/{assessorId}/invite-to-send") RestResult<AssessorInvitesToSendResource> getInviteToSend(@PathVariable long competitionId, @PathVariable long assessorId); @PostMapping("/{competitionId}/allocated-applications/{assessorId}/send-invite") RestResult<Void> sendInvite(@RequestBody InterviewNotifyAllocationResource interviewNotifyAllocationResource); @PostMapping("/allocated-applications/{assessorId}/unallocate/{applicationId}") RestResult<Void> unallocateApplication(@PathVariable long assessorId, @PathVariable long applicationId); @GetMapping("/{competitionId}/unallocated-applications/{assessorId}") RestResult<InterviewApplicationPageResource> getUnallocatedApplications(
@PathVariable long competitionId,
@PathVariable long assessorId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "target.id", direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/{competitionId}/unallocated-application-ids/{assessorId}") RestResult<List<Long>> getUnallocatedApplicationIds(
@PathVariable long competitionId,
@PathVariable long assessorId); } | @Test public void unAssignApplication() throws Exception { long assessorId = 1L; long applicationId = 2L; when(interviewAllocationServiceMock.unallocateApplication(assessorId, applicationId)).thenReturn(serviceSuccess()); mockMvc.perform(RestDocumentationRequestBuilders.post("/interview-panel/allocated-applications/{assessorId}/unallocate/{applicationId}", assessorId, applicationId)) .andExpect(status().isOk()); verify(interviewAllocationServiceMock, only()).unallocateApplication(assessorId, applicationId); } |
InterviewInviteController { @GetMapping("/get-available-assessors/{competitionId}") public RestResult<AvailableAssessorPageResource> getAvailableAssessors( @PathVariable long competitionId, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable) { return interviewInviteService.getAvailableAssessors(competitionId, pageable).toGetResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId,
@RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable
); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping(value = "/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<InterviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping(value = "/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping("/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview(
@PathVariable long competitionId,
@RequestParam List<ParticipantStatus> statuses,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<InterviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); } | @Test public void getAvailableAssessors() throws Exception { int page = 5; int pageSize = 30; List<AvailableAssessorResource> expectedAvailableAssessorResources = newAvailableAssessorResource().build(2); AvailableAssessorPageResource expectedAvailableAssessorPageResource = newAvailableAssessorPageResource() .withContent(expectedAvailableAssessorResources) .withNumber(page) .withTotalElements(300L) .withTotalPages(10) .withSize(30) .build(); Pageable pageable = PageRequest.of(page, pageSize, new Sort(DESC, "lastName")); when(interviewInviteServiceMock.getAvailableAssessors(COMPETITION_ID, pageable)) .thenReturn(serviceSuccess(expectedAvailableAssessorPageResource)); mockMvc.perform(get("/interview-panel-invite/get-available-assessors/{competitionId}", COMPETITION_ID) .param("page", String.valueOf(page)) .param("size", String.valueOf(pageSize)) .param("sort", "lastName,desc")) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedAvailableAssessorPageResource))); verify(interviewInviteServiceMock, only()).getAvailableAssessors(COMPETITION_ID, pageable); }
@Test public void getAvailableAssessors_defaultParameters() throws Exception { int page = 0; int pageSize = 20; List<AvailableAssessorResource> expectedAvailableAssessorResources = newAvailableAssessorResource().build(2); AvailableAssessorPageResource expectedAvailableAssessorPageResource = newAvailableAssessorPageResource() .withContent(expectedAvailableAssessorResources) .withNumber(page) .withTotalElements(300L) .withTotalPages(10) .withSize(30) .build(); Pageable pageable = PageRequest.of(page, pageSize, new Sort(ASC, "user.firstName", "user.lastName")); when(interviewInviteServiceMock.getAvailableAssessors(COMPETITION_ID, pageable)) .thenReturn(serviceSuccess(expectedAvailableAssessorPageResource)); mockMvc.perform(get("/interview-panel-invite/get-available-assessors/{competitionId}", COMPETITION_ID)) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedAvailableAssessorPageResource))); verify(interviewInviteServiceMock, only()).getAvailableAssessors(COMPETITION_ID, pageable); } |
InterviewInviteController { @GetMapping(value = "/get-available-assessor-ids/{competitionId}") public RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId) { return interviewInviteService.getAvailableAssessorIds(competitionId).toGetResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId,
@RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable
); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping(value = "/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<InterviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping(value = "/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping("/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview(
@PathVariable long competitionId,
@RequestParam List<ParticipantStatus> statuses,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<InterviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); } | @Test public void getAvailableAssessorsIds() throws Exception { List<Long> expectedAvailableAssessorIds = asList(1L, 2L); when(interviewInviteServiceMock.getAvailableAssessorIds(COMPETITION_ID)) .thenReturn(serviceSuccess(expectedAvailableAssessorIds)); mockMvc.perform(get("/interview-panel-invite/get-available-assessor-ids/{competitionId}", COMPETITION_ID)) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedAvailableAssessorIds))); verify(interviewInviteServiceMock, only()).getAvailableAssessorIds(COMPETITION_ID); } |
InterviewInviteController { @GetMapping("/get-created-invites/{competitionId}") public RestResult<AssessorCreatedInvitePageResource> getCreatedInvites( @PathVariable long competitionId, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable ) { return interviewInviteService.getCreatedInvites(competitionId, pageable).toGetResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId,
@RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable
); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping(value = "/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<InterviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping(value = "/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping("/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview(
@PathVariable long competitionId,
@RequestParam List<ParticipantStatus> statuses,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<InterviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); } | @Test public void getCreatedInvites() throws Exception { int page = 5; int pageSize = 40; List<AssessorCreatedInviteResource> expectedAssessorCreatedInviteResources = newAssessorCreatedInviteResource() .build(2); AssessorCreatedInvitePageResource expectedPageResource = newAssessorCreatedInvitePageResource() .withContent(expectedAssessorCreatedInviteResources) .withNumber(page) .withTotalElements(200L) .withTotalPages(10) .withSize(pageSize) .build(); Pageable pageable = PageRequest.of(page, pageSize, new Sort(ASC, "email")); when(interviewInviteServiceMock.getCreatedInvites(COMPETITION_ID, pageable)).thenReturn(serviceSuccess(expectedPageResource)); mockMvc.perform(get("/interview-panel-invite/get-created-invites/{competitionId}", COMPETITION_ID) .param("page", String.valueOf(page)) .param("size", String.valueOf(pageSize)) .param("sort", "email,ASC")) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedPageResource))); verify(interviewInviteServiceMock, only()).getCreatedInvites(COMPETITION_ID, pageable); }
@Test public void getCreatedInvites_defaultParameters() throws Exception { int page = 0; int pageSize = 20; List<AssessorCreatedInviteResource> expectedAssessorCreatedInviteResources = newAssessorCreatedInviteResource() .build(2); AssessorCreatedInvitePageResource expectedPageResource = newAssessorCreatedInvitePageResource() .withContent(expectedAssessorCreatedInviteResources) .withNumber(page) .withTotalElements(200L) .withTotalPages(10) .withSize(pageSize) .build(); Pageable pageable = PageRequest.of(page, pageSize, new Sort(ASC, "name")); when(interviewInviteServiceMock.getCreatedInvites(COMPETITION_ID, pageable)).thenReturn(serviceSuccess(expectedPageResource)); mockMvc.perform(get("/interview-panel-invite/get-created-invites/{competitionId}", COMPETITION_ID)) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedPageResource))); verify(interviewInviteServiceMock, only()).getCreatedInvites(COMPETITION_ID, pageable); } |
InterviewInviteController { @PostMapping("/invite-users") public RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites) { return interviewInviteService.inviteUsers(existingUserStagedInvites.getInvites()).toPostWithBodyResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId,
@RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable
); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping(value = "/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<InterviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping(value = "/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping("/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview(
@PathVariable long competitionId,
@RequestParam List<ParticipantStatus> statuses,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<InterviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); } | @Test public void inviteUsers() throws Exception { List<ExistingUserStagedInviteResource> existingUserStagedInvites = newExistingUserStagedInviteResource() .withUserId(1L, 2L) .withCompetitionId(1L) .build(2); ExistingUserStagedInviteListResource existingUserStagedInviteList = newExistingUserStagedInviteListResource() .withInvites(existingUserStagedInvites) .build(); when(interviewInviteServiceMock.inviteUsers(existingUserStagedInvites)).thenReturn(serviceSuccess()); mockMvc.perform(post("/interview-panel-invite/invite-users") .contentType(MediaType.APPLICATION_JSON) .content(toJson(existingUserStagedInviteList))) .andExpect(status().isOk()); verify(interviewInviteServiceMock, only()).inviteUsers(existingUserStagedInvites); } |
InterviewInviteController { @PostMapping("/send-all-invites/{competitionId}") public RestResult<Void> sendAllInvites(@PathVariable long competitionId, @RequestBody AssessorInviteSendResource assessorInviteSendResource) { return interviewInviteService.sendAllInvites(competitionId, assessorInviteSendResource).toPostResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId,
@RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable
); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping(value = "/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<InterviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping(value = "/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping("/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview(
@PathVariable long competitionId,
@RequestParam List<ParticipantStatus> statuses,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<InterviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); } | @Test public void sendAllInvites() throws Exception { AssessorInviteSendResource assessorInviteSendResource = newAssessorInviteSendResource() .withSubject("subject") .withContent("content") .build(); when(interviewInviteServiceMock.sendAllInvites(COMPETITION_ID, assessorInviteSendResource)).thenReturn(serviceSuccess()); mockMvc.perform(post("/interview-panel-invite/send-all-invites/{competitionId}", COMPETITION_ID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(assessorInviteSendResource))) .andExpect(status().isOk()); verify(interviewInviteServiceMock).sendAllInvites(COMPETITION_ID, assessorInviteSendResource); } |
InterviewInviteController { @GetMapping("/get-all-invites-to-send/{competitionId}") public RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId) { return interviewInviteService.getAllInvitesToSend(competitionId).toGetResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId,
@RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable
); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping(value = "/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<InterviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping(value = "/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping("/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview(
@PathVariable long competitionId,
@RequestParam List<ParticipantStatus> statuses,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<InterviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); } | @Test public void getAllInvitesToSend() throws Exception { AssessorInvitesToSendResource resource = newAssessorInvitesToSendResource().build(); when(interviewInviteServiceMock.getAllInvitesToSend(COMPETITION_ID)).thenReturn(serviceSuccess(resource)); mockMvc.perform(get("/interview-panel-invite/get-all-invites-to-send/{competitionId}", COMPETITION_ID).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); verify(interviewInviteServiceMock, only()).getAllInvitesToSend(COMPETITION_ID); } |
InterviewInviteController { @GetMapping("/get-all-invites-by-user/{userId}") public RestResult<List<InterviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId) { return interviewInviteService.getAllInvitesByUser(userId).toGetResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId,
@RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable
); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping(value = "/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<InterviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping(value = "/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping("/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview(
@PathVariable long competitionId,
@RequestParam List<ParticipantStatus> statuses,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<InterviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); } | @Test public void getAllInvitesByUser() throws Exception { final long USER_ID = 12L; InterviewInviteResource invite = newInterviewInviteResource() .withCompetitionId(1L) .withCompetitionName("Juggling craziness") .withInviteHash("") .withStatus(InviteStatus.SENT) .build(); InterviewParticipantResource interviewParticipantResource = newInterviewParticipantResource() .withStatus(PENDING) .withInvite(invite) .build(); when(interviewInviteServiceMock.getAllInvitesByUser(USER_ID)).thenReturn(serviceSuccess(singletonList(interviewParticipantResource))); mockMvc.perform(get("/interview-panel-invite/get-all-invites-by-user/{user_id}", USER_ID)) .andExpect(status().isOk()); } |
EmailAddressResolver { public static EmailAddress fromNotificationSource(NotificationSource notificationSource) { return new EmailAddress(notificationSource.getEmailAddress(), notificationSource.getName()); } private EmailAddressResolver(); static EmailAddress fromNotificationSource(NotificationSource notificationSource); static EmailAddress fromNotificationTarget(NotificationTarget notificationTarget); } | @Test public void testFromNotificationSourceWithUserNotificationSource() { User user = newUser().withFirstName("My").withLastName("User").withEmailAddress("[email protected]").build(); UserNotificationSource notificationSource = new UserNotificationSource(user.getName(), user.getEmail()); EmailAddress resolvedEmailAddress = EmailAddressResolver.fromNotificationSource(notificationSource); assertEquals("My User", resolvedEmailAddress.getName()); assertEquals("[email protected]", resolvedEmailAddress.getEmailAddress()); } |
PartitionSortRepeats { public static void groupByAge(List<Person> people) { } static void groupByAge(List<Person> people); } | @Test public void groupByAge() throws Exception { expected = new HashMap<>(); expected.put(23, new AtomicInteger(2)); expected.put(25, new AtomicInteger(3)); expected.put(26, new AtomicInteger(2)); people = Arrays.asList( new PartitionSortRepeats.Person(25, "Rita"), new PartitionSortRepeats.Person(23, "Felipe"), new PartitionSortRepeats.Person(25, "Vera"), new PartitionSortRepeats.Person(25, "Nathan"), new PartitionSortRepeats.Person(26, "Daniel"), new PartitionSortRepeats.Person(23, "Zach"), new PartitionSortRepeats.Person(26, "Tom") ); test(expected, people); } |
LRUCache { public LRUCache(int capacity) { this.capacity = capacity; } LRUCache(int capacity); Integer lookup(Integer key); Integer insert(Integer key, Integer value); Integer remove(Integer key); } | @Test public void lruCache() { final int capacity = 8; final Map<Integer, Integer> map = new HashMap<>(); final List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10); final LRUCache cache = new LRUCache(capacity); list.forEach(i -> { cache.insert(i, i); }); assertNull(cache.lookup(1)); assertNull(cache.lookup(2)); assertEquals(list.get(3), cache.lookup(3)); cache.insert(1, 1); assertNull(cache.lookup(4)); cache.remove(1); assertNull(cache.lookup(1)); } |
InsertionAndDeletionBST extends BinaryTree<Integer> { public boolean insert(Integer key) { return false; } InsertionAndDeletionBST(Integer data); boolean insert(Integer key); boolean delete(Integer key); } | @Test public void test1() { InsertionAndDeletionBST tree = new InsertionAndDeletionBST(2); tree.insert(0); tree.insert(1); assertEquals(tree, BinaryTreeUtil.getEvenBST()); }
@Test public void test2() { InsertionAndDeletionBST tree = new InsertionAndDeletionBST(4); tree.insert(6); tree.insert(1); tree.insert(2); tree.insert(5); tree.insert(7); tree.insert(3); assertEquals(tree, BinaryTreeUtil.getFullBST()); } |
AuthenticationContextClassReferencePrincipal implements CloneablePrincipal { @Override public boolean equals(final Object other) { if (other == null) { return false; } if (this == other) { return true; } if (other instanceof AuthenticationContextClassReferencePrincipal) { return authnContextClassReference.equals(((AuthenticationContextClassReferencePrincipal) other).getName()); } return false; } AuthenticationContextClassReferencePrincipal(
@Nonnull @NotEmpty @ParameterName(name = "classRef") final String classRef); @Override @Nonnull @NotEmpty String getName(); @Override int hashCode(); @Override boolean equals(final Object other); @Override String toString(); @Override AuthenticationContextClassReferencePrincipal clone(); static final String UNSPECIFIED; } | @Test public void testEquals() { Assert.assertNotEquals(principal, null); Assert.assertEquals(principal, principal); Assert.assertEquals(principal, new AuthenticationContextClassReferencePrincipal("testvalue")); Assert.assertNotEquals(principal, new AuthenticationContextClassReferencePrincipal("testvalue2")); } |
ServiceableProviderMetadataProvider extends AbstractServiceableComponent<ProviderMetadataResolver> implements RefreshableProviderMetadataResolver, Comparable<ServiceableProviderMetadataProvider> { @Override public void setId(@Nonnull @NotEmpty final String componentId) { super.setId(componentId); } ServiceableProviderMetadataProvider(); void setSortKey(final int key); @Nonnull void setEmbeddedResolver(@Nonnull final ProviderMetadataResolver theResolver); @Nonnull ProviderMetadataResolver getEmbeddedResolver(); @Override @Nonnull Iterable<OIDCProviderMetadata> resolve(final ProfileRequestContext profileRequestContext); @Override @Nullable OIDCProviderMetadata resolveSingle(@Nullable final ProfileRequestContext profileRequestContext); @Override void setId(@Nonnull @NotEmpty final String componentId); @Override @Nonnull ProviderMetadataResolver getComponent(); @Override void refresh(); @Override DateTime getLastRefresh(); @Override DateTime getLastUpdate(); @Override int compareTo(final ServiceableProviderMetadataProvider other); @Override boolean equals(final Object other); @Override int hashCode(); } | @Test(expectedExceptions = ComponentInitializationException.class) public void testNoResolver() throws ComponentInitializationException { provider.setId("mockId"); provider.initialize(); } |
ServiceableProviderMetadataProvider extends AbstractServiceableComponent<ProviderMetadataResolver> implements RefreshableProviderMetadataResolver, Comparable<ServiceableProviderMetadataProvider> { @Override public boolean equals(final Object other) { if (null == other) { return false; } if (!(other instanceof ServiceableProviderMetadataProvider)) { return false; } final ServiceableProviderMetadataProvider otherRp = (ServiceableProviderMetadataProvider) other; return Objects.equal(otherRp.sortKey, sortKey) && Objects.equal(getId(), otherRp.getId()); } ServiceableProviderMetadataProvider(); void setSortKey(final int key); @Nonnull void setEmbeddedResolver(@Nonnull final ProviderMetadataResolver theResolver); @Nonnull ProviderMetadataResolver getEmbeddedResolver(); @Override @Nonnull Iterable<OIDCProviderMetadata> resolve(final ProfileRequestContext profileRequestContext); @Override @Nullable OIDCProviderMetadata resolveSingle(@Nullable final ProfileRequestContext profileRequestContext); @Override void setId(@Nonnull @NotEmpty final String componentId); @Override @Nonnull ProviderMetadataResolver getComponent(); @Override void refresh(); @Override DateTime getLastRefresh(); @Override DateTime getLastUpdate(); @Override int compareTo(final ServiceableProviderMetadataProvider other); @Override boolean equals(final Object other); @Override int hashCode(); } | @Test public void testEquals() throws ResolverException, URISyntaxException, ComponentInitializationException { int sortKey = 1234; provider.setId("mockId"); provider.setEmbeddedResolver(buildMetadataResolver("mock1", "mock2")); provider.setSortKey(sortKey); provider.initialize(); ServiceableProviderMetadataProvider provider2 = new ServiceableProviderMetadataProvider(); provider2.setId("mockId"); provider2.setEmbeddedResolver(buildMetadataResolver("mock1", "mock2")); provider2.setSortKey(sortKey); provider2.initialize(); ServiceableProviderMetadataProvider provider3 = new ServiceableProviderMetadataProvider(); provider3.setId("mockId"); provider3.setEmbeddedResolver(buildMetadataResolver("mock1", "mock2")); provider3.setSortKey(sortKey + 1); provider3.initialize(); Assert.assertTrue(provider.equals(provider2)); Assert.assertFalse(provider.equals(provider3)); } |
RemoteJwkSetCache extends AbstractIdentifiableInitializableComponent { public void setStorage(@Nonnull final StorageService storageService) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); storage = Constraint.isNotNull(storageService, "StorageService cannot be null"); final StorageCapabilities caps = storage.getCapabilities(); if (caps instanceof StorageCapabilitiesEx) { Constraint.isTrue(((StorageCapabilitiesEx) caps).isServerSide(), "StorageService cannot be client-side"); } } @NonnullAfterInit StorageService getStorage(); void setStorage(@Nonnull final StorageService storageService); void setHttpClient(@Nonnull final HttpClient client); void setHttpClientSecurityParameters(@Nullable final HttpClientSecurityParameters params); @Override void doInitialize(); JWKSet fetch(@Nonnull final URI uri, final long expires); JWKSet fetch(@Nonnull @NotEmpty final String context, @Nonnull final URI uri, final long expires); static final String CONTEXT_NAME; } | @Test(expectedExceptions = ComponentInitializationException.class) public void testNoHttpClient() throws ComponentInitializationException { jwkSetCache.setStorage(storageService); jwkSetCache.initialize(); } |
RemoteJwkSetCache extends AbstractIdentifiableInitializableComponent { public void setHttpClient(@Nonnull final HttpClient client) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); ComponentSupport.ifDestroyedThrowDestroyedComponentException(this); httpClient = Constraint.isNotNull(client, "HttpClient cannot be null"); } @NonnullAfterInit StorageService getStorage(); void setStorage(@Nonnull final StorageService storageService); void setHttpClient(@Nonnull final HttpClient client); void setHttpClientSecurityParameters(@Nullable final HttpClientSecurityParameters params); @Override void doInitialize(); JWKSet fetch(@Nonnull final URI uri, final long expires); JWKSet fetch(@Nonnull @NotEmpty final String context, @Nonnull final URI uri, final long expires); static final String CONTEXT_NAME; } | @Test(expectedExceptions = ComponentInitializationException.class) public void testNoStorageService() throws ComponentInitializationException { jwkSetCache.setHttpClient(HttpClientBuilder.create().build()); jwkSetCache.initialize(); } |
AbstractAuthenticationRequestLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, T> { @Override @Nullable public T apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getInboundMessageContext() == null || input.getOutboundMessageContext() == null) { return null; } Object message = input.getInboundMessageContext().getMessage(); if (message == null || !(message instanceof AuthenticationRequest)) { return null; } OIDCAuthenticationResponseContext ctx = input.getOutboundMessageContext().getSubcontext(OIDCAuthenticationResponseContext.class, false); if (ctx == null) { return null; } requestObject = ctx.getRequestObject(); return doLookup((AuthenticationRequest) message); } @Override @Nullable T apply(@Nullable final ProfileRequestContext input); } | @Test public void testOK() { Assert.assertEquals("OK", mock.apply(prc)); }
@Test public void testNoInboundCtxts() { Assert.assertNull(mock.apply(null)); prc.setInboundMessageContext(null); Assert.assertNull(mock.apply(prc)); prc.setInboundMessageContext(msgCtx); msgCtx.setMessage(null); Assert.assertNull(mock.apply(prc)); }
@Test public void testNoOutboundCtxts() { prc.setOutboundMessageContext(null); Assert.assertNull(mock.apply(prc)); prc.setOutboundMessageContext(new MessageContext()); Assert.assertNull(mock.apply(prc)); } |
AbstractTokenRequestLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, T> { @Override @Nullable public T apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getInboundMessageContext() == null) { return null; } Object message = input.getInboundMessageContext().getMessage(); if (!(message instanceof TokenRequest)) { return null; } return doLookup((TokenRequest) message); } @Override @Nullable T apply(@Nullable final ProfileRequestContext input); } | @Test public void testOK() { Assert.assertEquals("OK", mock.apply(prc)); }
@Test public void testNoInboundCtxts() { Assert.assertNull(mock.apply(null)); prc.setInboundMessageContext(null); Assert.assertNull(mock.apply(prc)); prc.setInboundMessageContext(msgCtx); msgCtx.setMessage(null); Assert.assertNull(mock.apply(prc)); } |
SectorIdentifierLookupFunction extends AbstractIdentifiableInitializableComponent implements ContextDataLookupFunction<ProfileRequestContext, String> { @Override @Nullable public String apply(@Nullable final ProfileRequestContext input) { if (input == null) { return null; } String sectorIdentifier = null; OIDCMetadataContext ctx = oidcMetadataContextLookupStrategy.apply(input); if (ctx == null || ctx.getClientInformation() == null || ctx.getClientInformation().getOIDCMetadata() == null) { log.warn("oidc metadata context not available"); } else if (ctx.getClientInformation().getOIDCMetadata().getSectorIDURI() != null) { sectorIdentifier = ctx.getClientInformation().getOIDCMetadata().getSectorIDURI().getHost(); log.debug("sector identifier by sector uri {}", sectorIdentifier); } else if (ctx.getClientInformation().getOIDCMetadata().getRedirectionURIs() != null && ctx.getClientInformation().getOIDCMetadata().getRedirectionURIs().size() > 1) { log.warn("multiple registered redirection uris, unable to determine sector identifier"); } else { URI redirection = ctx.getClientInformation().getOIDCMetadata().getRedirectionURI(); if (redirection != null) { sectorIdentifier = redirection.getHost(); log.debug("sector identifier by redirect uri {}", sectorIdentifier); } else { log.warn("redirection uri not available"); } } return sectorIdentifier; } SectorIdentifierLookupFunction(); void setOIDCMetadataContextLookupStrategy(
@Nonnull final Function<ProfileRequestContext, OIDCMetadataContext> strategy); @Override @Nullable String apply(@Nullable final ProfileRequestContext input); } | @Test public void testSuccessSectorID() { ctx.getClientInformation().getOIDCMetadata().setSectorIDURI(sector); String locatedSector = lookup.apply(prc); Assert.assertEquals(locatedSector, sector.getHost()); }
@Test public void testSuccessRedirectURI() { ctx.getClientInformation().getOIDCMetadata().setRedirectionURI(sector); String locatedSector = lookup.apply(prc); Assert.assertEquals(locatedSector, sector.getHost()); }
@Test public void testSuccessRedirectURIs() { Set<URI> redirectURIs = new HashSet<URI>(); redirectURIs.add(sector); ctx.getClientInformation().getOIDCMetadata().setRedirectionURIs(redirectURIs ); String locatedSector = lookup.apply(prc); Assert.assertEquals(locatedSector, sector.getHost()); }
@Test public void testFailRedirectURIs() throws URISyntaxException { Set<URI> redirectURIs = new HashSet<URI>(); redirectURIs.add(sector); redirectURIs.add(new URI("https: ctx.getClientInformation().getOIDCMetadata().setRedirectionURIs(redirectURIs); String locatedSector = lookup.apply(prc); Assert.assertNull(locatedSector); }
@Test public void testFailNoURIs() throws URISyntaxException { String locatedSector = lookup.apply(prc); Assert.assertNull(locatedSector); }
@Test public void testFailNoCtx() throws URISyntaxException { msgCtx.removeSubcontext(OIDCMetadataContext.class); String locatedSector = lookup.apply(prc); Assert.assertNull(locatedSector); }
@Test public void testFailNoClientInformation() throws URISyntaxException { ctx.setClientInformation(null); String locatedSector = lookup.apply(prc); Assert.assertNull(locatedSector); } |
FilesystemClientInformationResolver extends AbstractFileOIDCEntityResolver<ClientID, OIDCClientInformation> implements ClientInformationResolver, RefreshableClientInformationResolver { @Override public OIDCClientInformation resolveSingle(CriteriaSet criteria) throws ResolverException { final Iterable<OIDCClientInformation> iterable = resolve(criteria); if (iterable != null) { final Iterator<OIDCClientInformation> iterator = iterable.iterator(); if (iterator != null && iterator.hasNext()) { return iterator.next(); } } log.warn("Could not find any clients with the given criteria"); return null; } FilesystemClientInformationResolver(@Nonnull final Resource metadata); FilesystemClientInformationResolver(@Nullable final Timer backgroundTaskTimer,
@Nonnull final Resource metadata); void setRemoteJwkSetCache(final RemoteJwkSetCache jwkSetCache); void setKeyFetchInterval(@Duration @Positive long interval); @Override Iterable<OIDCClientInformation> resolve(CriteriaSet criteria); @Override OIDCClientInformation resolveSingle(CriteriaSet criteria); } | @Test public void testSingleSuccess() throws Exception { initTest("/org/geant/idpextension/oidc/metadata/impl/oidc-client.json"); final ClientIDCriterion criterion = new ClientIDCriterion(new ClientID(clientId)); final OIDCClientInformation clientInfo = resolver.resolveSingle(new CriteriaSet(criterion)); Assert.assertNotNull(clientInfo); Assert.assertEquals(clientInfo.getID().getValue(), clientId); final Set<URI> redirectUris = clientInfo.getOIDCMetadata().getRedirectionURIs(); Assert.assertEquals(redirectUris.size(), 1); Assert.assertTrue(redirectUris.contains(redirectUri)); testScope(clientInfo.getOIDCMetadata().getScope()); final Set<ResponseType> responseTypes = clientInfo.getOIDCMetadata().getResponseTypes(); Assert.assertEquals(responseTypes.size(), 2); Assert.assertTrue(responseTypes.contains(new ResponseType(OIDCResponseTypeValue.ID_TOKEN))); }
@Test public void testArraySuccess() throws Exception { initTest("/org/geant/idpextension/oidc/metadata/impl/oidc-clients.json"); final ClientIDCriterion criterion = new ClientIDCriterion(new ClientID(clientId2)); final OIDCClientInformation clientInfo = resolver.resolveSingle(new CriteriaSet(criterion)); Assert.assertNotNull(clientInfo); Assert.assertEquals(clientInfo.getID().getValue(), clientId2); final Set<URI> redirectUris = clientInfo.getOIDCMetadata().getRedirectionURIs(); Assert.assertEquals(redirectUris.size(), 1); Assert.assertTrue(redirectUris.contains(redirectUri2)); testScope(clientInfo.getOIDCMetadata().getScope()); final Set<ResponseType> responseTypes = clientInfo.getOIDCMetadata().getResponseTypes(); Assert.assertEquals(responseTypes.size(), 2); Assert.assertTrue(responseTypes.contains(new ResponseType(OIDCResponseTypeValue.ID_TOKEN))); }
@Test public void testNotFound() throws Exception { initTest("/org/geant/idpextension/oidc/metadata/impl/oidc-client.json"); final ClientIDCriterion criterion = new ClientIDCriterion(new ClientID("not_found")); final ClientInformation clientInfo = resolver.resolveSingle(new CriteriaSet(criterion)); Assert.assertNull(clientInfo); } |
OIDCRegistrationResponseContextLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, OIDCClientRegistrationResponseContext> { @Override @Nullable public OIDCClientRegistrationResponseContext apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getOutboundMessageContext() == null) { return null; } return input.getOutboundMessageContext().getSubcontext(OIDCClientRegistrationResponseContext.class, false); } @Override @Nullable OIDCClientRegistrationResponseContext apply(@Nullable final ProfileRequestContext input); } | @Test public void testSuccess() { Assert.assertNotNull(lookup.apply(prc)); }
@SuppressWarnings("unchecked") @Test public void testNoInput() { Assert.assertNull(lookup.apply(null)); prc.getOutboundMessageContext().removeSubcontext(OIDCClientRegistrationResponseContext.class); Assert.assertNull(lookup.apply(prc)); prc.setOutboundMessageContext(null); Assert.assertNull(lookup.apply(prc)); } |
DefaultUserInfoSigningAlgLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, JWSAlgorithm> { @Override @Nullable public JWSAlgorithm apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getInboundMessageContext() == null) { return null; } OIDCMetadataContext ctx = input.getInboundMessageContext().getSubcontext(OIDCMetadataContext.class, false); if (ctx == null || ctx.getClientInformation() == null || ctx.getClientInformation().getOIDCMetadata() == null) { return null; } return ctx.getClientInformation().getOIDCMetadata().getUserInfoJWSAlg(); } @Override @Nullable JWSAlgorithm apply(@Nullable final ProfileRequestContext input); } | @Test public void testSuccess() { Assert.assertEquals(JWSAlgorithm.ES256, lookup.apply(prc)); }
@SuppressWarnings("unchecked") @Test public void testNoInput() { Assert.assertNull(lookup.apply(null)); ctx.setClientInformation(null); Assert.assertNull(lookup.apply(prc)); prc.getInboundMessageContext().removeSubcontext(OIDCMetadataContext.class); Assert.assertNull(lookup.apply(prc)); prc.setInboundMessageContext(null); Assert.assertNull(lookup.apply(prc)); } |
UserInfoResponseClaimsSetLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, ClaimsSet> { @Override @Nullable public ClaimsSet apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getOutboundMessageContext() == null) { return null; } OIDCAuthenticationResponseContext ctx = input.getOutboundMessageContext().getSubcontext(OIDCAuthenticationResponseContext.class, false); if (ctx == null) { return null; } return ctx.getUserInfo(); } @Override @Nullable ClaimsSet apply(@Nullable final ProfileRequestContext input); } | @Test public void testSuccess() { Assert.assertEquals("sub", (String) lookup.apply(prc).getClaim("sub")); }
@SuppressWarnings("unchecked") @Test public void testNoInput() { Assert.assertNull(lookup.apply(null)); oidcCtx.setUserInfo(null); Assert.assertNull(lookup.apply(prc)); prc.getOutboundMessageContext().removeSubcontext(OIDCAuthenticationResponseContext.class); Assert.assertNull(lookup.apply(prc)); prc.setOutboundMessageContext(null); Assert.assertNull(lookup.apply(prc)); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.