src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
ProjectDetailsController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_DETAILS_SECTION')") @GetMapping("/{projectId}/details/start-date") public String viewStartDate(@PathVariable("projectId") final long projectId, Model model, UserResource loggedInUser) { ProjectResource projectResource = projectService.getById(projectId); CompetitionResource competitionResource = competitionRestService.getCompetitionById(projectResource.getCompetition()).getSuccess(); model.addAttribute("model", new ProjectDetailsStartDateViewModel(projectResource, competitionResource)); return "project/details-start-date"; } @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_DETAILS_SECTION')") @GetMapping("/{projectId}/details") String viewProjectDetails(@PathVariable("projectId") final Long projectId, Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_DETAILS_SECTION')") @GetMapping("/{projectId}/details/readonly") String viewProjectDetailsInReadOnly(@PathVariable("projectId") final Long projectId, Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_DETAILS_SECTION')") @GetMapping("/{projectId}/details/start-date") String viewStartDate(@PathVariable("projectId") final long projectId, Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PARTNER_PROJECT_LOCATION_PAGE')") @GetMapping("/{projectId}/organisation/{organisationId}/partner-project-location") String viewPartnerProjectLocation(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PARTNER_PROJECT_LOCATION_PAGE')") @PostMapping("/{projectId}/organisation/{organisationId}/partner-project-location") String updatePartnerProjectLocation(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId,
@ModelAttribute(FORM_ATTR_NAME) PartnerProjectLocationForm form,
@SuppressWarnings("unused") BindingResult bindingResult, ValidationHandler validationHandler,
Model model,
UserResource loggedInUser); } | @Test public void viewStartDate() throws Exception { long projectId = 20L; LocalDate targetStartDate = LocalDate.now(); CompetitionResource competitionResource = newCompetitionResource() .build(); ProjectResource project = newProjectResource() .withId(projectId) .withCompetition(competitionResource.getId()) .withDuration(23L) .withTargetStartDate(targetStartDate) .build(); when(projectService.getById(project.getId())).thenReturn(project); when(competitionRestService.getCompetitionById(project.getCompetition())).thenReturn(restSuccess(competitionResource)); MvcResult result = mockMvc.perform(get("/project/{projectId}/details/start-date", projectId)) .andExpect(status().isOk()) .andExpect(view().name("project/details-start-date")) .andReturn(); ProjectDetailsStartDateViewModel model = (ProjectDetailsStartDateViewModel) result.getModelAndView().getModel().get("model"); assertEquals(project.getName(), model.getProjectName()); assertEquals(project.getTargetStartDate(), model.getTargetStartDate()); verify(projectService).getById(project.getId()); verifyNoMoreInteractions(projectService); assertFalse(model.isKtpCompetition()); } |
ProjectDetailsController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PARTNER_PROJECT_LOCATION_PAGE')") @GetMapping("/{projectId}/organisation/{organisationId}/partner-project-location") public String viewPartnerProjectLocation(@PathVariable("projectId") final long projectId, @PathVariable("organisationId") final long organisationId, Model model, UserResource loggedInUser) { PartnerOrganisationResource partnerOrganisation = partnerOrganisationService.getPartnerOrganisation(projectId, organisationId).getSuccess(); OrganisationResource organisation = organisationRestService.getOrganisationById(organisationId).getSuccess(); PartnerProjectLocationForm form = new PartnerProjectLocationForm(partnerOrganisation.getPostcode(), partnerOrganisation.getInternationalLocation()); return doViewPartnerProjectLocation(projectId, organisation, loggedInUser, model, form); } @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_DETAILS_SECTION')") @GetMapping("/{projectId}/details") String viewProjectDetails(@PathVariable("projectId") final Long projectId, Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_DETAILS_SECTION')") @GetMapping("/{projectId}/details/readonly") String viewProjectDetailsInReadOnly(@PathVariable("projectId") final Long projectId, Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_DETAILS_SECTION')") @GetMapping("/{projectId}/details/start-date") String viewStartDate(@PathVariable("projectId") final long projectId, Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PARTNER_PROJECT_LOCATION_PAGE')") @GetMapping("/{projectId}/organisation/{organisationId}/partner-project-location") String viewPartnerProjectLocation(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PARTNER_PROJECT_LOCATION_PAGE')") @PostMapping("/{projectId}/organisation/{organisationId}/partner-project-location") String updatePartnerProjectLocation(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId,
@ModelAttribute(FORM_ATTR_NAME) PartnerProjectLocationForm form,
@SuppressWarnings("unused") BindingResult bindingResult, ValidationHandler validationHandler,
Model model,
UserResource loggedInUser); } | @Test public void viewPartnerProjectLocation() throws Exception { long projectId = 1L; long organisationId = 2L; ProjectResource projectResource = newProjectResource() .withId(projectId) .withName("Project 1") .build(); PartnerOrganisationResource partnerOrganisation = PartnerOrganisationResourceBuilder.newPartnerOrganisationResource() .withPostcode("TW14 9QG") .build(); OrganisationResource organisationResource = OrganisationResourceBuilder.newOrganisationResource().withId(organisationId).build(); when(partnerOrganisationRestService.getPartnerOrganisation(projectId, organisationId)).thenReturn(restSuccess(partnerOrganisation)); when(organisationRestService.getOrganisationById(organisationId)).thenReturn(restSuccess(organisationResource)); when(projectService.userIsPartnerInOrganisationForProject(projectId, organisationId, loggedInUser.getId())).thenReturn(true); when(projectService.getById(projectId)).thenReturn(projectResource); MvcResult result = mockMvc.perform(get("/project/{projectId}/organisation/{organisationId}/partner-project-location", projectId, organisationId)) .andExpect(status().isOk()) .andExpect(view().name("project/partner-project-location")) .andReturn(); PartnerProjectLocationViewModel model = (PartnerProjectLocationViewModel) result.getModelAndView().getModel().get("model"); assertEquals(projectId, model.getProjectId()); assertEquals("Project 1", model.getProjectName()); assertEquals(organisationId, model.getOrganisationId()); PartnerProjectLocationForm form = (PartnerProjectLocationForm) result.getModelAndView().getModel().get(FORM_ATTR_NAME); assertEquals("TW14 9QG", form.getPostcode()); } |
ProjectDetailsController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PARTNER_PROJECT_LOCATION_PAGE')") @PostMapping("/{projectId}/organisation/{organisationId}/partner-project-location") public String updatePartnerProjectLocation(@PathVariable("projectId") final long projectId, @PathVariable("organisationId") final long organisationId, @ModelAttribute(FORM_ATTR_NAME) PartnerProjectLocationForm form, @SuppressWarnings("unused") BindingResult bindingResult, ValidationHandler validationHandler, Model model, UserResource loggedInUser) { OrganisationResource organisation = organisationRestService.getOrganisationById(organisationId).getSuccess(); Supplier<String> failureView = () -> doViewPartnerProjectLocation(projectId, organisation, loggedInUser, model, form); return validationHandler.failNowOrSucceedWith(failureView, () -> { PostcodeAndTownResource postcodeAndTownResource = new PostcodeAndTownResource(form.getPostcode(), form.getTown()); ServiceResult<Void> updateResult = projectDetailsService.updatePartnerProjectLocation(projectId, organisationId, postcodeAndTownResource); return validationHandler.addAnyErrors(updateResult, errorConverter(organisation)). failNowOrSucceedWith(failureView, () -> redirectToProjectDetails(projectId)); }); } @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_DETAILS_SECTION')") @GetMapping("/{projectId}/details") String viewProjectDetails(@PathVariable("projectId") final Long projectId, Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_DETAILS_SECTION')") @GetMapping("/{projectId}/details/readonly") String viewProjectDetailsInReadOnly(@PathVariable("projectId") final Long projectId, Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_DETAILS_SECTION')") @GetMapping("/{projectId}/details/start-date") String viewStartDate(@PathVariable("projectId") final long projectId, Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PARTNER_PROJECT_LOCATION_PAGE')") @GetMapping("/{projectId}/organisation/{organisationId}/partner-project-location") String viewPartnerProjectLocation(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PARTNER_PROJECT_LOCATION_PAGE')") @PostMapping("/{projectId}/organisation/{organisationId}/partner-project-location") String updatePartnerProjectLocation(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId,
@ModelAttribute(FORM_ATTR_NAME) PartnerProjectLocationForm form,
@SuppressWarnings("unused") BindingResult bindingResult, ValidationHandler validationHandler,
Model model,
UserResource loggedInUser); } | @Test public void updatePartnerProjectLocationWhenUpdateFails() throws Exception { long projectId = 1L; long organisationId = 2L; String postcode = "UB7 8QF"; PostcodeAndTownResource postcodeAndTown = new PostcodeAndTownResource(postcode, null); ProjectResource projectResource = newProjectResource() .withId(projectId) .withName("Project 1") .build(); OrganisationResource organisationResource = OrganisationResourceBuilder.newOrganisationResource().build(); when(projectDetailsService.updatePartnerProjectLocation(projectId, organisationId, postcodeAndTown)) .thenReturn(serviceFailure(PROJECT_SETUP_LOCATION_CANNOT_BE_UPDATED_IF_GOL_GENERATED)); when(projectService.userIsPartnerInOrganisationForProject(projectId, organisationId, loggedInUser.getId())).thenReturn(true); when(projectService.getById(projectId)).thenReturn(projectResource); when(organisationRestService.getOrganisationById(organisationId)).thenReturn(restSuccess(organisationResource)); MvcResult result = mockMvc.perform(post("/project/{projectId}/organisation/{organisationId}/partner-project-location", projectId, organisationId). contentType(MediaType.APPLICATION_FORM_URLENCODED). param("postcode", postcode)). andExpect(status().isOk()). andExpect(view().name("project/partner-project-location")). andReturn(); PartnerProjectLocationForm form = (PartnerProjectLocationForm) result.getModelAndView().getModel().get(FORM_ATTR_NAME); assertEquals(new PartnerProjectLocationForm(postcode, null), form); }
@Test public void updatePartnerProjectLocationSuccess() throws Exception { long projectId = 1L; long organisationId = 2L; String postcode = "UB7 8QF"; PostcodeAndTownResource postcodeAndTown = new PostcodeAndTownResource(postcode, null); OrganisationResource organisationResource = OrganisationResourceBuilder.newOrganisationResource().build(); when(projectDetailsService.updatePartnerProjectLocation(projectId, organisationId, postcodeAndTown)) .thenReturn(serviceSuccess()); when(organisationRestService.getOrganisationById(organisationId)).thenReturn(restSuccess(organisationResource)); MvcResult result = mockMvc.perform(post("/project/{projectId}/organisation/{organisationId}/partner-project-location", projectId, organisationId). contentType(MediaType.APPLICATION_FORM_URLENCODED). param("postcode", postcode)). andExpect(status().is3xxRedirection()). andExpect(view().name("redirect:/project/" + projectId + "/details")). andReturn(); PartnerProjectLocationForm form = (PartnerProjectLocationForm) result.getModelAndView().getModel().get(FORM_ATTR_NAME); assertEquals(new PartnerProjectLocationForm(postcode, null), form); verify(projectDetailsService).updatePartnerProjectLocation(projectId, organisationId, postcodeAndTown); verify(projectService, never()).userIsPartnerInOrganisationForProject(projectId, organisationId, loggedInUser.getId()); verify(projectService, never()).getById(projectId); } |
DocumentsController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_DOCUMENTS_SECTION')") @GetMapping("/all") public String viewAllDocuments(@PathVariable("projectId") long projectId, Model model, UserResource loggedInUser) { model.addAttribute("model", populator.populateAllDocuments(projectId, loggedInUser.getId())); return "project/documents-all"; } DocumentsController(); @Autowired DocumentsController(DocumentsPopulator populator, DocumentsRestService documentsRestService); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_DOCUMENTS_SECTION')") @GetMapping("/all") String viewAllDocuments(@PathVariable("projectId") long projectId, Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_DOCUMENTS_SECTION')") @GetMapping("/config/{documentConfigId}") String viewDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'EDIT_DOCUMENTS_SECTION')") @PostMapping(value = "/config/{documentConfigId}", params = "uploadDocument") String uploadDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
@ModelAttribute(FORM_ATTR) DocumentForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_DOCUMENTS_SECTION')") @GetMapping("/config/{documentConfigId}/download") @ResponseBody ResponseEntity<ByteArrayResource> downloadDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'EDIT_DOCUMENTS_SECTION')") @PostMapping(value = "/config/{documentConfigId}", params = "deleteDocument") String deleteDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
@ModelAttribute(FORM_ATTR) DocumentForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'EDIT_DOCUMENTS_SECTION')") @PostMapping(value = "/config/{documentConfigId}", params = "submitDocument") String submitDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
@ModelAttribute(FORM_ATTR) DocumentForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
UserResource loggedInUser); } | @Test public void viewAllDocuments() throws Exception { long projectId = 1L; ProjectResource project = newProjectResource() .withId(projectId) .withApplication(3L) .withCompetition(2L) .withName("Project 12") .build(); AllDocumentsViewModel viewModel = new AllDocumentsViewModel(project, emptyList(), true, false); when(populator.populateAllDocuments(projectId, loggedInUser.getId())).thenReturn(viewModel); MvcResult result = mockMvc.perform(get("/project/" + projectId + "/document/all")) .andExpect(view().name("project/documents-all")) .andReturn(); AllDocumentsViewModel returnedViewModel = (AllDocumentsViewModel) result.getModelAndView().getModel().get("model"); assertEquals(viewModel, returnedViewModel); } |
DocumentsController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_DOCUMENTS_SECTION')") @GetMapping("/config/{documentConfigId}") public String viewDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId, Model model, UserResource loggedInUser) { return doViewDocument(projectId, documentConfigId, model, loggedInUser, new DocumentForm()); } DocumentsController(); @Autowired DocumentsController(DocumentsPopulator populator, DocumentsRestService documentsRestService); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_DOCUMENTS_SECTION')") @GetMapping("/all") String viewAllDocuments(@PathVariable("projectId") long projectId, Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_DOCUMENTS_SECTION')") @GetMapping("/config/{documentConfigId}") String viewDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'EDIT_DOCUMENTS_SECTION')") @PostMapping(value = "/config/{documentConfigId}", params = "uploadDocument") String uploadDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
@ModelAttribute(FORM_ATTR) DocumentForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_DOCUMENTS_SECTION')") @GetMapping("/config/{documentConfigId}/download") @ResponseBody ResponseEntity<ByteArrayResource> downloadDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'EDIT_DOCUMENTS_SECTION')") @PostMapping(value = "/config/{documentConfigId}", params = "deleteDocument") String deleteDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
@ModelAttribute(FORM_ATTR) DocumentForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'EDIT_DOCUMENTS_SECTION')") @PostMapping(value = "/config/{documentConfigId}", params = "submitDocument") String submitDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
@ModelAttribute(FORM_ATTR) DocumentForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
UserResource loggedInUser); } | @Test public void viewDocument() throws Exception { long projectId = 1L; long documentConfigId = 2L; long applicationId = 3L; DocumentViewModel viewModel = new DocumentViewModel(projectId, "Project 12", applicationId, documentConfigId, "Risk Register", "Guidance for Risk Register", null, DocumentStatus.UNSET, "",true, true); when(populator.populateViewDocument(projectId, loggedInUser.getId(), documentConfigId)).thenReturn(viewModel); MvcResult result = mockMvc.perform(get("/project/" + projectId + "/document/config/" + documentConfigId)) .andExpect(view().name("project/document")) .andReturn(); Map<String, Object> model = result.getModelAndView().getModel(); DocumentViewModel returnedViewModel = (DocumentViewModel) model.get("model"); assertEquals(viewModel, returnedViewModel); assertEquals(new DocumentForm(), model.get("form")); } |
DocumentsController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'EDIT_DOCUMENTS_SECTION')") @PostMapping(value = "/config/{documentConfigId}", params = "uploadDocument") public String uploadDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId, @ModelAttribute(FORM_ATTR) DocumentForm form, @SuppressWarnings("unused") BindingResult bindingResult, ValidationHandler validationHandler, Model model, UserResource loggedInUser) { return performActionOrBindErrorsToField( projectId, documentConfigId, validationHandler, model, loggedInUser, "document", form, () -> { MultipartFile file = form.getDocument(); return documentsRestService.uploadDocument(projectId, documentConfigId, file.getContentType(), file.getSize(), file.getOriginalFilename(), getMultipartFileBytes(file)); }); } DocumentsController(); @Autowired DocumentsController(DocumentsPopulator populator, DocumentsRestService documentsRestService); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_DOCUMENTS_SECTION')") @GetMapping("/all") String viewAllDocuments(@PathVariable("projectId") long projectId, Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_DOCUMENTS_SECTION')") @GetMapping("/config/{documentConfigId}") String viewDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'EDIT_DOCUMENTS_SECTION')") @PostMapping(value = "/config/{documentConfigId}", params = "uploadDocument") String uploadDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
@ModelAttribute(FORM_ATTR) DocumentForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_DOCUMENTS_SECTION')") @GetMapping("/config/{documentConfigId}/download") @ResponseBody ResponseEntity<ByteArrayResource> downloadDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'EDIT_DOCUMENTS_SECTION')") @PostMapping(value = "/config/{documentConfigId}", params = "deleteDocument") String deleteDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
@ModelAttribute(FORM_ATTR) DocumentForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'EDIT_DOCUMENTS_SECTION')") @PostMapping(value = "/config/{documentConfigId}", params = "submitDocument") String submitDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
@ModelAttribute(FORM_ATTR) DocumentForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
UserResource loggedInUser); } | @Test public void uploadDocumentFailure() throws Exception { long projectId = 1L; long documentConfigId = 2L; long applicationId = 3L; MockMultipartFile uploadedFile = new MockMultipartFile("document", "RiskRegister.pdf", "text/plain", "My content!".getBytes()); when(documentsRestService.uploadDocument(projectId, documentConfigId,"text/plain", 11, "RiskRegister.pdf", "My content!".getBytes())). thenReturn(restFailure(asList( unsupportedMediaTypeError(singletonList(APPLICATION_ATOM_XML)), unsupportedMediaTypeError(singletonList(APPLICATION_JSON))))); DocumentViewModel viewModel = new DocumentViewModel(projectId, "Project 12", applicationId, documentConfigId, "Risk Register", "Guidance for Risk Register", null, DocumentStatus.UNSET, "", true, true); when(populator.populateViewDocument(projectId, loggedInUser.getId(), documentConfigId)).thenReturn(viewModel); MvcResult result = mockMvc.perform( fileUpload("/project/" + projectId + "/document/config/" + documentConfigId). file(uploadedFile). param("uploadDocument", "")) .andExpect(status().isOk()) .andExpect(view().name("project/document")) .andReturn(); Map<String, Object> model = result.getModelAndView().getModel(); DocumentViewModel returnedViewModel = (DocumentViewModel) model.get("model"); DocumentForm expectedForm = new DocumentForm(); expectedForm.setDocument(uploadedFile); assertEquals(viewModel, returnedViewModel); assertEquals(expectedForm, model.get("form")); }
@Test public void uploadDocument() throws Exception { long projectId = 1L; long documentConfigId = 2L; FileEntryResource createdFileDetails = newFileEntryResource().withName("Risk Register").build(); MockMultipartFile uploadedFile = new MockMultipartFile("document", "RiskRegister.pdf", "text/plain", "My content!".getBytes()); when(documentsRestService.uploadDocument(projectId, documentConfigId,"text/plain", 11, "RiskRegister.pdf", "My content!".getBytes())). thenReturn(restSuccess(createdFileDetails)); mockMvc.perform( fileUpload("/project/" + projectId + "/document/config/" + documentConfigId). file(uploadedFile). param("uploadDocument", "")) .andExpect(status().is3xxRedirection()) .andExpect(view().name("redirect:/project/" + projectId + "/document/config/" + documentConfigId)); verify(documentsRestService).uploadDocument(projectId, documentConfigId,"text/plain", 11, "RiskRegister.pdf", "My content!".getBytes()); } |
DocumentsController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_DOCUMENTS_SECTION')") @GetMapping("/config/{documentConfigId}/download") @ResponseBody public ResponseEntity<ByteArrayResource> downloadDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId) { final Optional<ByteArrayResource> fileContents = documentsRestService.getFileContents(projectId, documentConfigId).getSuccess(); final Optional<FileEntryResource> fileEntryDetails = documentsRestService.getFileEntryDetails(projectId, documentConfigId).getSuccess(); return returnFileIfFoundOrThrowNotFoundException(projectId, documentConfigId, fileContents, fileEntryDetails); } DocumentsController(); @Autowired DocumentsController(DocumentsPopulator populator, DocumentsRestService documentsRestService); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_DOCUMENTS_SECTION')") @GetMapping("/all") String viewAllDocuments(@PathVariable("projectId") long projectId, Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_DOCUMENTS_SECTION')") @GetMapping("/config/{documentConfigId}") String viewDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'EDIT_DOCUMENTS_SECTION')") @PostMapping(value = "/config/{documentConfigId}", params = "uploadDocument") String uploadDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
@ModelAttribute(FORM_ATTR) DocumentForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_DOCUMENTS_SECTION')") @GetMapping("/config/{documentConfigId}/download") @ResponseBody ResponseEntity<ByteArrayResource> downloadDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'EDIT_DOCUMENTS_SECTION')") @PostMapping(value = "/config/{documentConfigId}", params = "deleteDocument") String deleteDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
@ModelAttribute(FORM_ATTR) DocumentForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'EDIT_DOCUMENTS_SECTION')") @PostMapping(value = "/config/{documentConfigId}", params = "submitDocument") String submitDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
@ModelAttribute(FORM_ATTR) DocumentForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
UserResource loggedInUser); } | @Test public void downloadDocument() throws Exception { long projectId = 1L; long documentConfigId = 2L; ByteArrayResource fileContents = new ByteArrayResource("My content!".getBytes()); FileEntryResource fileEntryDetails = newFileEntryResource().withName("Risk Register").build(); when(documentsRestService.getFileContents(projectId, documentConfigId)). thenReturn(restSuccess(Optional.of(fileContents))); when(documentsRestService.getFileEntryDetails(projectId, documentConfigId)). thenReturn(restSuccess(Optional.of(fileEntryDetails))); MvcResult result = mockMvc.perform(get("/project/" + projectId + "/document/config/" + documentConfigId + "/download")). andExpect(status().isOk()). andReturn(); assertEquals("My content!", result.getResponse().getContentAsString()); assertEquals("inline; filename=\"" + fileEntryDetails.getName() + "\"", result.getResponse().getHeader("Content-Disposition")); } |
DocumentsController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'EDIT_DOCUMENTS_SECTION')") @PostMapping(value = "/config/{documentConfigId}", params = "deleteDocument") public String deleteDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId, @ModelAttribute(FORM_ATTR) DocumentForm form, @SuppressWarnings("unused") BindingResult bindingResult, ValidationHandler validationHandler, Model model, UserResource loggedInUser) { return performActionOrBindErrorsToField(projectId, documentConfigId, validationHandler, model, loggedInUser, "document", form, () -> documentsRestService.deleteDocument(projectId, documentConfigId)); } DocumentsController(); @Autowired DocumentsController(DocumentsPopulator populator, DocumentsRestService documentsRestService); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_DOCUMENTS_SECTION')") @GetMapping("/all") String viewAllDocuments(@PathVariable("projectId") long projectId, Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_DOCUMENTS_SECTION')") @GetMapping("/config/{documentConfigId}") String viewDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'EDIT_DOCUMENTS_SECTION')") @PostMapping(value = "/config/{documentConfigId}", params = "uploadDocument") String uploadDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
@ModelAttribute(FORM_ATTR) DocumentForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_DOCUMENTS_SECTION')") @GetMapping("/config/{documentConfigId}/download") @ResponseBody ResponseEntity<ByteArrayResource> downloadDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'EDIT_DOCUMENTS_SECTION')") @PostMapping(value = "/config/{documentConfigId}", params = "deleteDocument") String deleteDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
@ModelAttribute(FORM_ATTR) DocumentForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'EDIT_DOCUMENTS_SECTION')") @PostMapping(value = "/config/{documentConfigId}", params = "submitDocument") String submitDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
@ModelAttribute(FORM_ATTR) DocumentForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
UserResource loggedInUser); } | @Test public void deleteDocumentFailure() throws Exception { long projectId = 1L; long documentConfigId = 2L; long applicationId = 3L; when(documentsRestService.deleteDocument(projectId, documentConfigId)). thenReturn(restFailure(PROJECT_SETUP_PROJECT_DOCUMENT_CANNOT_BE_DELETED)); FileEntryResource fileEntryDetails = newFileEntryResource().withName("Risk Register").build(); FileDetailsViewModel fileDetailsViewModel = new FileDetailsViewModel(fileEntryDetails); DocumentViewModel viewModel = new DocumentViewModel(projectId, "Project 12", applicationId, documentConfigId, "Risk Register", "Guidance for Risk Register", fileDetailsViewModel, DocumentStatus.SUBMITTED, "",true, true); when(populator.populateViewDocument(projectId, loggedInUser.getId(), documentConfigId)).thenReturn(viewModel); MvcResult result = mockMvc.perform( post("/project/" + projectId + "/document/config/" + documentConfigId) .param("deleteDocument", "")) .andExpect(status().isOk()) .andExpect(view().name("project/document")) .andReturn(); Map<String, Object> model = result.getModelAndView().getModel(); DocumentViewModel returnedViewModel = (DocumentViewModel) model.get("model"); assertEquals(viewModel, returnedViewModel); assertEquals(new DocumentForm(), model.get("form")); }
@Test public void deleteDocument() throws Exception { long projectId = 1L; long documentConfigId = 2L; when(documentsRestService.deleteDocument(projectId, documentConfigId)).thenReturn(restSuccess()); mockMvc.perform( post("/project/" + projectId + "/document/config/" + documentConfigId) .param("deleteDocument", "")) .andExpect(status().is3xxRedirection()) .andExpect(view().name("redirect:/project/" + projectId + "/document/config/" + documentConfigId)); verify(documentsRestService).deleteDocument(projectId, documentConfigId); } |
DocumentsController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'EDIT_DOCUMENTS_SECTION')") @PostMapping(value = "/config/{documentConfigId}", params = "submitDocument") public String submitDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId, @ModelAttribute(FORM_ATTR) DocumentForm form, @SuppressWarnings("unused") BindingResult bindingResult, ValidationHandler validationHandler, Model model, UserResource loggedInUser) { Supplier<String> successView = () -> redirectToViewDocumentPage(projectId, documentConfigId); Supplier<String> failureView = () -> doViewDocument(projectId, documentConfigId, model, loggedInUser, form); RestResult<Void> result = documentsRestService.submitDocument(projectId, documentConfigId); return validationHandler.addAnyErrors(result, asGlobalErrors()). failNowOrSucceedWith(failureView, successView); } DocumentsController(); @Autowired DocumentsController(DocumentsPopulator populator, DocumentsRestService documentsRestService); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_DOCUMENTS_SECTION')") @GetMapping("/all") String viewAllDocuments(@PathVariable("projectId") long projectId, Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_DOCUMENTS_SECTION')") @GetMapping("/config/{documentConfigId}") String viewDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'EDIT_DOCUMENTS_SECTION')") @PostMapping(value = "/config/{documentConfigId}", params = "uploadDocument") String uploadDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
@ModelAttribute(FORM_ATTR) DocumentForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_DOCUMENTS_SECTION')") @GetMapping("/config/{documentConfigId}/download") @ResponseBody ResponseEntity<ByteArrayResource> downloadDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'EDIT_DOCUMENTS_SECTION')") @PostMapping(value = "/config/{documentConfigId}", params = "deleteDocument") String deleteDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
@ModelAttribute(FORM_ATTR) DocumentForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'EDIT_DOCUMENTS_SECTION')") @PostMapping(value = "/config/{documentConfigId}", params = "submitDocument") String submitDocument(@PathVariable("projectId") long projectId,
@PathVariable("documentConfigId") long documentConfigId,
@ModelAttribute(FORM_ATTR) DocumentForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
Model model,
UserResource loggedInUser); } | @Test public void submitDocumentFailure() throws Exception { long projectId = 1L; long documentConfigId = 2L; long applicationId = 3L; when(documentsRestService.submitDocument(projectId, documentConfigId)). thenReturn(restFailure(PROJECT_SETUP_PROJECT_DOCUMENT_NOT_YET_UPLOADED)); FileEntryResource fileEntryDetails = newFileEntryResource().withName("Risk Register").build(); FileDetailsViewModel fileDetailsViewModel = new FileDetailsViewModel(fileEntryDetails); DocumentViewModel viewModel = new DocumentViewModel(projectId, "Project 12", applicationId, documentConfigId, "Risk Register", "Guidance for Risk Register", fileDetailsViewModel, DocumentStatus.UNSET, "",true, true); when(populator.populateViewDocument(projectId, loggedInUser.getId(), documentConfigId)).thenReturn(viewModel); MvcResult result = mockMvc.perform( post("/project/" + projectId + "/document/config/" + documentConfigId) .param("submitDocument", "")) .andExpect(status().isOk()) .andExpect(view().name("project/document")) .andReturn(); Map<String, Object> model = result.getModelAndView().getModel(); DocumentViewModel returnedViewModel = (DocumentViewModel) model.get("model"); assertEquals(viewModel, returnedViewModel); assertEquals(new DocumentForm(), model.get("form")); }
@Test public void submitDocument() throws Exception { long projectId = 1L; long documentConfigId = 2L; when(documentsRestService.submitDocument(projectId, documentConfigId)).thenReturn(restSuccess()); mockMvc.perform( post("/project/" + projectId + "/document/config/" + documentConfigId) .param("submitDocument", "")) .andExpect(status().is3xxRedirection()) .andExpect(view().name("redirect:/project/" + projectId + "/document/config/" + documentConfigId)); verify(documentsRestService).submitDocument(projectId, documentConfigId); } |
SetupCompleteViewModelPopulator { public SetupCompleteViewModel populate(long projectId) { ProjectResource project = projectService.getById(projectId); return new SetupCompleteViewModel( project, getSubmittedTime(project)); } SetupCompleteViewModel populate(long projectId); } | @Test public void populate() { long projectId = 1L; long competitionId = 2L; ProjectResource projectResource = newProjectResource() .withId(projectId) .withName("Project Name") .withProjectState(LIVE) .withCompetition(competitionId) .build(); CompetitionResource competitionResource = newCompetitionResource() .withId(competitionId) .withName("Comp Name") .build(); when(projectServiceMock.getById(projectId)).thenReturn(projectResource); SetupCompleteViewModel viewModel = service.populate(projectId); assertEquals(viewModel.getCompetitionId(), competitionId); assertEquals(viewModel.getProjectId(), projectId); verify(projectServiceMock).getById(projectId); } |
GrantOfferLetterModel implements BasicProjectDetailsViewModel { public boolean isShowSubmitButton() { return projectManager && !isSubmitted() && isOfferSigned() && grantOfferLetterFile != null; } GrantOfferLetterModel(String title, Long projectId, String projectName, boolean leadPartner, FileDetailsViewModel grantOfferLetterFile,
FileDetailsViewModel signedGrantOfferLetterFile, FileDetailsViewModel additionalContractFile,
boolean projectManager, GrantOfferLetterStateResource golState, boolean useDocusign,
boolean procurement); @Override Long getProjectId(); @Override String getProjectName(); boolean isLeadPartner(); GrantOfferLetterStateResource getGolState(); boolean isSubmitted(); FileDetailsViewModel getGrantOfferLetterFile(); boolean isGrantOfferLetterApproved(); FileDetailsViewModel getAdditionalContractFile(); boolean isOfferSigned(); FileDetailsViewModel getSignedGrantOfferLetterFile(); boolean isUseDocusign(); String getTitle(); boolean isProcurement(); boolean isShowSubmitButton(); boolean isProjectManager(); boolean isGrantOfferLetterSent(); boolean isGrantOfferLetterRejected(); boolean isShowGrantOfferLetterRejectedMessage(); boolean isAbleToRemoveSignedGrantOffer(); boolean isShowGrantOfferLetterReceivedByInnovateMessage(); boolean isShowAwaitingSignatureFromLeadPartnerMessage(); boolean isShowGrantOfferLetterApprovedByInnovateMessage(); } | @Test public void testShowSubmitButtonWhenSentSignedAndNotSubmittedAsProjectManager() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmGeneratedOfferSentToProjectTeam); assertThat(model.isShowSubmitButton(), is(true)); }
@Test public void testShowSubmitButtonNotShownWhenNotProjectManager() { boolean leadPartner = true; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerGeneratedOfferSentToProjectTeam); assertThat(model.isShowSubmitButton(), is(false)); }
@Test public void testShowSubmitButtonNotShownWhenSignedLetterNotYetUploaded() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmGeneratedOfferSentToProjectTeam); assertThat(model.isShowSubmitButton(), is(false)); }
@Test public void testShowSubmitButtonNotShownWhenSignedLetterAlreadySubmitted() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferSubmittedToInternalTeam); assertThat(model.isShowSubmitButton(), is(false)); } |
OrganisationInitialCreationServiceImpl extends BaseTransactionalService implements OrganisationInitialCreationService { @Override @Transactional public ServiceResult<OrganisationResource> createOrMatch(OrganisationResource organisationToCreate) { Optional<Organisation> matchedOrganisation = organisationMatchingService.findOrganisationMatch(organisationToCreate); Organisation resultingOrganisation = matchedOrganisation.orElseGet(() -> createNewOrganisation(organisationToCreate)); return serviceSuccess(organisationMapper.mapToResource(resultingOrganisation)); } @Override @Transactional ServiceResult<OrganisationResource> createOrMatch(OrganisationResource organisationToCreate); } | @Test public void createOrMatch_noMatchFound_organisationSouldBeSaved() { Organisation createdOrganisation = newOrganisation().build(); when(organisationMatchingService.findOrganisationMatch(any())).thenReturn(Optional.empty()); when(organisationRepositoryMock.save(any(Organisation.class))).thenReturn(createdOrganisation); ServiceResult<OrganisationResource> result = service.createOrMatch(organisationResource); assertTrue(result.isSuccess()); verify(organisationRepositoryMock).save(any(Organisation.class)); }
@Test public void createOrMatch_matchFound_organisationShouldNotBeSaved() { Organisation createdOrganisation = newOrganisation().build(); when(organisationMatchingService.findOrganisationMatch(any())).thenReturn(Optional.of(newOrganisation().build())); when(organisationRepositoryMock.save(any(Organisation.class))).thenReturn(createdOrganisation); ServiceResult<OrganisationResource> result = service.createOrMatch(organisationResource); assertTrue(result.isSuccess()); verify(organisationRepositoryMock, never()).save(any(Organisation.class)); } |
GrantOfferLetterModel implements BasicProjectDetailsViewModel { public boolean isShowGrantOfferLetterRejectedMessage() { if (!isProjectManager()) { return false; } return isGrantOfferLetterRejected(); } GrantOfferLetterModel(String title, Long projectId, String projectName, boolean leadPartner, FileDetailsViewModel grantOfferLetterFile,
FileDetailsViewModel signedGrantOfferLetterFile, FileDetailsViewModel additionalContractFile,
boolean projectManager, GrantOfferLetterStateResource golState, boolean useDocusign,
boolean procurement); @Override Long getProjectId(); @Override String getProjectName(); boolean isLeadPartner(); GrantOfferLetterStateResource getGolState(); boolean isSubmitted(); FileDetailsViewModel getGrantOfferLetterFile(); boolean isGrantOfferLetterApproved(); FileDetailsViewModel getAdditionalContractFile(); boolean isOfferSigned(); FileDetailsViewModel getSignedGrantOfferLetterFile(); boolean isUseDocusign(); String getTitle(); boolean isProcurement(); boolean isShowSubmitButton(); boolean isProjectManager(); boolean isGrantOfferLetterSent(); boolean isGrantOfferLetterRejected(); boolean isShowGrantOfferLetterRejectedMessage(); boolean isAbleToRemoveSignedGrantOffer(); boolean isShowGrantOfferLetterReceivedByInnovateMessage(); boolean isShowAwaitingSignatureFromLeadPartnerMessage(); boolean isShowGrantOfferLetterApprovedByInnovateMessage(); } | @Test public void testShowGrantOfferLetterRejectedMessageWhenProjectManagerAndGrantOfferIsRejected() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferRejected); assertThat(model.isShowGrantOfferLetterRejectedMessage(), is(true)); }
@Test public void testShowGrantOfferLetterRejectedMessageNotShownWhenNotProjectManager() { boolean leadPartner = true; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerSignedGrantOfferRejected); assertThat(model.isShowGrantOfferLetterRejectedMessage(), is(false)); }
@Test public void testShowGrantOfferLetterRejectedMessageNotShownWhenGrantOfferLetterNotRejected() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferSubmittedToInternalTeam); assertThat(model.isShowGrantOfferLetterRejectedMessage(), is(false)); } |
GrantOfferLetterModel implements BasicProjectDetailsViewModel { public boolean isAbleToRemoveSignedGrantOffer() { if (getSignedGrantOfferLetterFile() == null) { return false; } if (isGrantOfferLetterApproved()) { return false; } if (isGrantOfferLetterRejected()) { return isProjectManager(); } if (!isSubmitted()) { return isLeadPartner(); } return false; } GrantOfferLetterModel(String title, Long projectId, String projectName, boolean leadPartner, FileDetailsViewModel grantOfferLetterFile,
FileDetailsViewModel signedGrantOfferLetterFile, FileDetailsViewModel additionalContractFile,
boolean projectManager, GrantOfferLetterStateResource golState, boolean useDocusign,
boolean procurement); @Override Long getProjectId(); @Override String getProjectName(); boolean isLeadPartner(); GrantOfferLetterStateResource getGolState(); boolean isSubmitted(); FileDetailsViewModel getGrantOfferLetterFile(); boolean isGrantOfferLetterApproved(); FileDetailsViewModel getAdditionalContractFile(); boolean isOfferSigned(); FileDetailsViewModel getSignedGrantOfferLetterFile(); boolean isUseDocusign(); String getTitle(); boolean isProcurement(); boolean isShowSubmitButton(); boolean isProjectManager(); boolean isGrantOfferLetterSent(); boolean isGrantOfferLetterRejected(); boolean isShowGrantOfferLetterRejectedMessage(); boolean isAbleToRemoveSignedGrantOffer(); boolean isShowGrantOfferLetterReceivedByInnovateMessage(); boolean isShowAwaitingSignatureFromLeadPartnerMessage(); boolean isShowGrantOfferLetterApprovedByInnovateMessage(); } | @Test public void testAbleToRemoveSignedGrantOfferIfUploadedAndNotSubmittedAndLeadPartner() { boolean leadPartner = true; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerGeneratedOfferSentToProjectTeam); assertThat(model.isAbleToRemoveSignedGrantOffer(), is(true)); }
@Test public void testAbleToRemoveSignedGrantOfferNotAllowedIfNotLeadPartnerOrProjectManager() { boolean leadPartner = false; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerGeneratedOfferSentToProjectTeam); assertThat(model.isAbleToRemoveSignedGrantOffer(), is(false)); }
@Test public void testAbleToRemoveSignedGrantOfferNotAllowedIfNotUploaded() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmGeneratedOfferSentToProjectTeam); assertThat(model.isAbleToRemoveSignedGrantOffer(), is(false)); }
@Test public void testAbleToRemoveSignedGrantOfferNotAllowedIfSubmittedToInnovate() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferSubmittedToInternalTeam); assertThat(model.isAbleToRemoveSignedGrantOffer(), is(false)); }
@Test public void testAbleToRemoveSignedGrantOfferIfRejectedAndProjectManager() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferRejected); assertThat(model.isAbleToRemoveSignedGrantOffer(), is(true)); }
@Test public void testAbleToRemoveSignedGrantOfferNotAllowedIfRejectedButNotProjectManager() { boolean leadPartner = true; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerSignedGrantOfferRejected); assertThat(model.isAbleToRemoveSignedGrantOffer(), is(false)); }
@Test public void testAbleToRemoveSignedGrantOfferNotAllowedIfApproved() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferApproved); assertThat(model.isAbleToRemoveSignedGrantOffer(), is(false)); } |
GrantOfferLetterModel implements BasicProjectDetailsViewModel { public boolean isShowGrantOfferLetterReceivedByInnovateMessage() { if (isGrantOfferLetterRejected() && !isLeadPartner()) { return true; } if (isGrantOfferLetterApproved()) { return false; } return isSubmitted(); } GrantOfferLetterModel(String title, Long projectId, String projectName, boolean leadPartner, FileDetailsViewModel grantOfferLetterFile,
FileDetailsViewModel signedGrantOfferLetterFile, FileDetailsViewModel additionalContractFile,
boolean projectManager, GrantOfferLetterStateResource golState, boolean useDocusign,
boolean procurement); @Override Long getProjectId(); @Override String getProjectName(); boolean isLeadPartner(); GrantOfferLetterStateResource getGolState(); boolean isSubmitted(); FileDetailsViewModel getGrantOfferLetterFile(); boolean isGrantOfferLetterApproved(); FileDetailsViewModel getAdditionalContractFile(); boolean isOfferSigned(); FileDetailsViewModel getSignedGrantOfferLetterFile(); boolean isUseDocusign(); String getTitle(); boolean isProcurement(); boolean isShowSubmitButton(); boolean isProjectManager(); boolean isGrantOfferLetterSent(); boolean isGrantOfferLetterRejected(); boolean isShowGrantOfferLetterRejectedMessage(); boolean isAbleToRemoveSignedGrantOffer(); boolean isShowGrantOfferLetterReceivedByInnovateMessage(); boolean isShowAwaitingSignatureFromLeadPartnerMessage(); boolean isShowGrantOfferLetterApprovedByInnovateMessage(); } | @Test public void testShowGrantOfferLetterReceivedByInnovateMessageIfSubmittedToInnovate() { boolean leadPartner = false; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerSignedGrantOfferSubmittedToInternalTeam); assertThat(model.isShowGrantOfferLetterReceivedByInnovateMessage(), is(true)); }
@Test public void testShowGrantOfferLetterReceivedByInnovateMessageIfRejectedAndNotLeadPartnerOrProjectManager() { boolean leadPartner = false; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerSignedGrantOfferRejected); assertThat(model.isShowGrantOfferLetterReceivedByInnovateMessage(), is(true)); }
@Test public void testShowGrantOfferLetterReceivedByInnovateMessageShownIfRejectedAndLeadPartnerButNotProjectManager() { boolean leadPartner = true; boolean projectManager = false; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerSignedGrantOfferRejected); assertThat(model.isShowGrantOfferLetterReceivedByInnovateMessage(), is(true)); }
@Test public void testShowGrantOfferLetterReceivedByInnovateMessageNotAllowedIfRejectedAndProjectManager() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferRejected); assertThat(model.isShowGrantOfferLetterReceivedByInnovateMessage(), is(false)); }
@Test public void testShowGrantOfferLetterReceivedByInnovateMessageNotAllowedIfApproved() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferApproved); assertThat(model.isShowGrantOfferLetterReceivedByInnovateMessage(), is(false)); } |
GrantOfferLetterModel implements BasicProjectDetailsViewModel { public boolean isShowAwaitingSignatureFromLeadPartnerMessage() { if (isLeadPartner()) { return false; } if (!isGrantOfferLetterSent()) { return false; } return !isSubmitted(); } GrantOfferLetterModel(String title, Long projectId, String projectName, boolean leadPartner, FileDetailsViewModel grantOfferLetterFile,
FileDetailsViewModel signedGrantOfferLetterFile, FileDetailsViewModel additionalContractFile,
boolean projectManager, GrantOfferLetterStateResource golState, boolean useDocusign,
boolean procurement); @Override Long getProjectId(); @Override String getProjectName(); boolean isLeadPartner(); GrantOfferLetterStateResource getGolState(); boolean isSubmitted(); FileDetailsViewModel getGrantOfferLetterFile(); boolean isGrantOfferLetterApproved(); FileDetailsViewModel getAdditionalContractFile(); boolean isOfferSigned(); FileDetailsViewModel getSignedGrantOfferLetterFile(); boolean isUseDocusign(); String getTitle(); boolean isProcurement(); boolean isShowSubmitButton(); boolean isProjectManager(); boolean isGrantOfferLetterSent(); boolean isGrantOfferLetterRejected(); boolean isShowGrantOfferLetterRejectedMessage(); boolean isAbleToRemoveSignedGrantOffer(); boolean isShowGrantOfferLetterReceivedByInnovateMessage(); boolean isShowAwaitingSignatureFromLeadPartnerMessage(); boolean isShowGrantOfferLetterApprovedByInnovateMessage(); } | @Test public void testShowAwaitingSignatureFromLeadPartnerMessageIfGrantOfferLetterSentButNotYetSignedAndNotLeadPartner() { boolean leadPartner = false; boolean projectManager = false; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerGeneratedOfferSentToProjectTeam); assertThat(model.isShowAwaitingSignatureFromLeadPartnerMessage(), is(true)); }
@Test public void testShowAwaitingSignatureFromLeadPartnerMessageNotAllowedIfLeadPartner() { boolean leadPartner = true; boolean projectManager = false; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerGeneratedOfferSentToProjectTeam); assertThat(model.isShowAwaitingSignatureFromLeadPartnerMessage(), is(false)); }
@Test public void testShowAwaitingSignatureFromLeadPartnerMessageNotAllowedIfProjectManager() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmGeneratedOfferSentToProjectTeam); assertThat(model.isShowAwaitingSignatureFromLeadPartnerMessage(), is(false)); }
@Test public void testShowAwaitingSignatureFromLeadPartnerMessageNotAllowedIfGrantOfferNotYetSent() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmGeneratedGrantOfferNotYetSentToProjectTeam); assertThat(model.isShowAwaitingSignatureFromLeadPartnerMessage(), is(false)); }
@Test public void testShowAwaitingSignatureFromLeadPartnerMessageNotAllowedIfSigned() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferSubmittedToInternalTeam); assertThat(model.isShowAwaitingSignatureFromLeadPartnerMessage(), is(false)); }
@Test public void testShowAwaitingSignatureFromLeadPartnerMessageNotAllowedIfGrantOfferLetterRejectedAndNotLeadPartner() { boolean leadPartner = false; boolean projectManager = false; boolean signedGrantOfferUploaded = false; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPartnerSignedGrantOfferRejected); assertThat(model.isShowAwaitingSignatureFromLeadPartnerMessage(), is(false)); } |
KnowledgeBaseServiceImpl extends RootTransactionalService implements KnowledgeBaseService { @Override public ServiceResult<String> getKnowledgeBaseName(long id) { return find(knowledgeBaseRepository.findById(id), notFoundError(KnowledgeBase.class, singletonList(id))) .andOnSuccessReturn(KnowledgeBase::getName); } @Override ServiceResult<List<String>> getKnowledgeBaseNames(); @Override ServiceResult<String> getKnowledgeBaseName(long id); @Override ServiceResult<KnowledgeBaseResource> getKnowledgeBaseByName(String name); } | @Test public void getKnowledgeBaseName() { when(knowledgeBaseRepository.findById(1L)).thenReturn(Optional.of(knowledgeBase)); ServiceResult<String> result = service.getKnowledgeBaseName(1L); assertTrue(result.isSuccess()); assertEquals(knowledgeBase.getName(), result.getSuccess()); } |
GrantOfferLetterModel implements BasicProjectDetailsViewModel { public boolean isShowGrantOfferLetterApprovedByInnovateMessage() { return isGrantOfferLetterApproved(); } GrantOfferLetterModel(String title, Long projectId, String projectName, boolean leadPartner, FileDetailsViewModel grantOfferLetterFile,
FileDetailsViewModel signedGrantOfferLetterFile, FileDetailsViewModel additionalContractFile,
boolean projectManager, GrantOfferLetterStateResource golState, boolean useDocusign,
boolean procurement); @Override Long getProjectId(); @Override String getProjectName(); boolean isLeadPartner(); GrantOfferLetterStateResource getGolState(); boolean isSubmitted(); FileDetailsViewModel getGrantOfferLetterFile(); boolean isGrantOfferLetterApproved(); FileDetailsViewModel getAdditionalContractFile(); boolean isOfferSigned(); FileDetailsViewModel getSignedGrantOfferLetterFile(); boolean isUseDocusign(); String getTitle(); boolean isProcurement(); boolean isShowSubmitButton(); boolean isProjectManager(); boolean isGrantOfferLetterSent(); boolean isGrantOfferLetterRejected(); boolean isShowGrantOfferLetterRejectedMessage(); boolean isAbleToRemoveSignedGrantOffer(); boolean isShowGrantOfferLetterReceivedByInnovateMessage(); boolean isShowAwaitingSignatureFromLeadPartnerMessage(); boolean isShowGrantOfferLetterApprovedByInnovateMessage(); } | @Test public void testShowGrantOfferLetterApprovedByInnovateMessageIfApproved() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferApproved); assertThat(model.isShowGrantOfferLetterApprovedByInnovateMessage(), is(true)); }
@Test public void testShowGrantOfferLetterApprovedByInnovateMessageNotAllowedIfNotApproved() { boolean leadPartner = true; boolean projectManager = true; boolean signedGrantOfferUploaded = true; GrantOfferLetterModel model = createGrantOfferLetterModel(leadPartner, projectManager, signedGrantOfferUploaded, stateForPmSignedGrantOfferSubmittedToInternalTeam); assertThat(model.isShowGrantOfferLetterApprovedByInnovateMessage(), is(false)); } |
PendingPartnerProgressLandingPageController { @GetMapping public String progressLandingPage(@PathVariable long projectId, @PathVariable long organisationId, Model model, @ModelAttribute("form") JoinProjectForm form) { model.addAttribute("model", populator.populate(projectId, organisationId)); return "project/pending-partner-progress/landing-page"; } @GetMapping String progressLandingPage(@PathVariable long projectId, @PathVariable long organisationId, Model model, @ModelAttribute("form") JoinProjectForm form); @PostMapping String joinProject(@PathVariable long projectId,
@PathVariable long organisationId,
Model model,
@ModelAttribute("form") JoinProjectForm form,
ValidationHandler validationHandler); } | @Test public void progressLandingPage() throws Exception { long projectId = 1L; long organisationId = 2L; PendingPartnerProgressLandingPageViewModel viewModel = mock(PendingPartnerProgressLandingPageViewModel.class); when(populator.populate(projectId, organisationId)).thenReturn(viewModel); mockMvc.perform(get("/project/{projectId}/organisation/{organisationId}/pending-partner-progress", projectId, organisationId)) .andExpect(status().isOk()) .andExpect(view().name("project/pending-partner-progress/landing-page")) .andExpect(model().attribute("model", viewModel)); } |
ProjectTermsController { @GetMapping public String getTerms(@PathVariable long projectId, @PathVariable long organisationId, Model model, @ModelAttribute(name = "form", binding = false) ProjectTermsForm form) { ProjectTermsViewModel viewModel = projectTermsModelPopulator.populate(projectId, organisationId); model.addAttribute("model", viewModel); return "project/pending-partner-progress/terms-and-conditions"; } @GetMapping String getTerms(@PathVariable long projectId,
@PathVariable long organisationId,
Model model,
@ModelAttribute(name = "form", binding = false) ProjectTermsForm form); @PostMapping String acceptTerms(@PathVariable long projectId,
@PathVariable long organisationId,
Model model,
@ModelAttribute(name = "form", binding = false) ProjectTermsForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler); } | @Test public void getTerms() throws Exception { ProjectTermsViewModel viewModel = new ProjectTermsViewModel(project.getId(), organisation.getId(), competitionTermsTemplate, termsAccepted, null); when(projectTermsModelPopulator.populate(project.getId(), organisation.getId())).thenReturn(viewModel); mockMvc.perform(get("/project/{projectId}/organisation/{organisationId}/terms-and-conditions", project.getId(), organisation.getId())) .andExpect(status().isOk()) .andExpect(model().attribute("model", viewModel)) .andExpect(view().name("project/pending-partner-progress/terms-and-conditions")); } |
ProjectTermsController { @PostMapping public String acceptTerms(@PathVariable long projectId, @PathVariable long organisationId, Model model, @ModelAttribute(name = "form", binding = false) ProjectTermsForm form, @SuppressWarnings("unused") BindingResult bindingResult, ValidationHandler validationHandler) { Supplier<String> failureView = () -> getTerms(projectId, organisationId, model, form); return validationHandler.failNowOrSucceedWith(failureView, () -> { RestResult<Void> result = pendingPartnerProgressRestService.markTermsAndConditionsComplete(projectId, organisationId); return validationHandler.addAnyErrors(result) .failNowOrSucceedWith( failureView, () -> format("redirect:/project/{projectId}/organisation/{organisationId}/terms-and-conditions#terms-accepted", projectId, organisationId)); }); } @GetMapping String getTerms(@PathVariable long projectId,
@PathVariable long organisationId,
Model model,
@ModelAttribute(name = "form", binding = false) ProjectTermsForm form); @PostMapping String acceptTerms(@PathVariable long projectId,
@PathVariable long organisationId,
Model model,
@ModelAttribute(name = "form", binding = false) ProjectTermsForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler); } | @Test public void acceptTerms() throws Exception { when(pendingPartnerProgressRestService.markTermsAndConditionsComplete(project.getId(), organisation.getId())).thenReturn(restSuccess()); ProjectTermsForm form = new ProjectTermsForm(); mockMvc.perform(post("/project/{projectId}/organisation/{organisationId}/terms-and-conditions", project.getId(), organisation.getId()) .param("agreed", "true")) .andExpect(status().is3xxRedirection()) .andExpect(model().attribute("form", form)) .andExpect(model().hasNoErrors()) .andExpect(redirectedUrlTemplate("/project/{projectId}/organisation/{organisationId}/terms-and-conditions#terms-accepted", project.getId(), organisation.getId())); verify(pendingPartnerProgressRestService).markTermsAndConditionsComplete(project.getId(), organisation.getId()); verifyNoMoreInteractions(pendingPartnerProgressRestService); } |
PendingPartnerProgressLandingPageViewModelPopulator { public PendingPartnerProgressLandingPageViewModel populate(long projectId, long organisationId) { ProjectResource project = projectRestService.getProjectById(projectId).getSuccess(); PendingPartnerProgressResource progress = pendingPartnerProgressRestService.getPendingPartnerProgress(projectId, organisationId).getSuccess(); CompetitionResource competition = competitionRestService.getCompetitionById(project.getCompetition()).getSuccess(); OrganisationResource organisation = organisationRestService.getOrganisationById(organisationId).getSuccess(); return new PendingPartnerProgressLandingPageViewModel( project, organisationId, progress, !competition.applicantShouldUseJesFinances(organisation.getOrganisationTypeEnum()) ); } PendingPartnerProgressLandingPageViewModel populate(long projectId, long organisationId); } | @Test public void populate() { long projectId = 1L; long organisationId = 2L; CompetitionResource competition = newCompetitionResource() .withFundingType(FundingType.GRANT) .withIncludeJesForm(true) .build(); ProjectResource project = newProjectResource() .withId(projectId) .withName("proj") .withApplication(3L) .withCompetition(competition.getId()).build(); PendingPartnerProgressResource progress = newPendingPartnerProgressResource() .withYourFundingCompletedOn(ZonedDateTime.now()) .withYourOrganisationCompletedOn(ZonedDateTime.now()) .withTermsAndConditionsCompletedOn(ZonedDateTime.now()) .build(); OrganisationResource organisation = newOrganisationResource() .withOrganisationType(RESEARCH.getId()) .build(); when(projectRestService.getProjectById(projectId)).thenReturn(restSuccess(project)); when(pendingPartnerProgressRestService.getPendingPartnerProgress(projectId, organisationId)).thenReturn(restSuccess(progress)); when(competitionRestService.getCompetitionById(project.getCompetition())).thenReturn(restSuccess(competition)); when(organisationRestService.getOrganisationById(organisationId)).thenReturn(restSuccess(organisation)); PendingPartnerProgressLandingPageViewModel viewModel = populator.populate(projectId, organisationId); assertEquals("proj", viewModel.getProjectName()); assertEquals(3L, viewModel.getApplicationId()); assertEquals(projectId, viewModel.getProjectId()); assertFalse( viewModel.isShowYourOrganisation()); assertTrue(viewModel.isTermsAndConditionsComplete()); assertTrue(viewModel.isYourFundingComplete()); assertTrue(viewModel.isYourOrganisationComplete()); } |
ProjectTermsModelPopulator { public ProjectTermsViewModel populate(long projectId, long organisationId) { ProjectResource project = projectRestService.getProjectById(projectId).getSuccess(); OrganisationResource organisation = organisationRestService.getOrganisationById(organisationId).getSuccess(); CompetitionResource competition = competitionRestService.getCompetitionById(project.getCompetition()).getSuccess(); PendingPartnerProgressResource pendingPartnerProgressResource = pendingPartnerProgressRestService.getPendingPartnerProgress(projectId, organisationId).getSuccess(); return new ProjectTermsViewModel( projectId, organisation.getId(), competition.getTermsAndConditions().getTemplate(), pendingPartnerProgressResource.isTermsAndConditionsComplete(), pendingPartnerProgressResource.getTermsAndConditionsCompletedOn() ); } ProjectTermsModelPopulator(ProjectRestService projectRestService,
CompetitionRestService competitionRestService,
OrganisationRestService organisationRestService,
PendingPartnerProgressRestService pendingPartnerProgressRestService); ProjectTermsViewModel populate(long projectId,
long organisationId); } | @Test public void populate() { String termsTemplate = "terms-template"; GrantTermsAndConditionsResource grantTermsAndConditions = newGrantTermsAndConditionsResource() .withName("Name") .withTemplate(termsTemplate) .withVersion(1) .build(); CompetitionResource competition = newCompetitionResource() .withId(1L) .withTermsAndConditions(grantTermsAndConditions) .build(); ProjectResource project = newProjectResource() .withId(3L).withCompetition(competition.getId()) .build(); OrganisationResource organisation = newOrganisationResource().withId(3L).build(); PendingPartnerProgressResource pendingPartnerProgress = newPendingPartnerProgressResource().build(); when(projectRestService.getProjectById(project.getId())).thenReturn(restSuccess(project)); when(organisationRestService.getOrganisationById(organisation.getId())).thenReturn(restSuccess(organisation)); when(competitionRestService.getCompetitionById(project.getCompetition())).thenReturn(restSuccess(competition)); when(pendingPartnerProgressRestService.getPendingPartnerProgress(project.getId(), organisation.getId())).thenReturn(restSuccess(pendingPartnerProgress)); ProjectTermsViewModel actual = projectTermsModelPopulator.populate(project.getId(), organisation.getId()); assertEquals((long) project.getId(), actual.getProjectId()); assertEquals((long) organisation.getId(), actual.getOrganisationId()); assertEquals(competition.getTermsAndConditions().getTemplate(), actual.getCompetitionTermsTemplate()); assertEquals(pendingPartnerProgress.isTermsAndConditionsComplete(), actual.isTermsAccepted()); assertNull(pendingPartnerProgress.getTermsAndConditionsCompletedOn()); InOrder inOrder = inOrder(projectRestService, organisationRestService, competitionRestService, pendingPartnerProgressRestService); inOrder.verify(projectRestService).getProjectById(project.getId()); inOrder.verify(organisationRestService).getOrganisationById(organisation.getId()); inOrder.verify(competitionRestService).getCompetitionById(project.getCompetition()); inOrder.verify(pendingPartnerProgressRestService).getPendingPartnerProgress(project.getId(), organisation.getId()); verifyNoMoreInteractions(projectRestService, organisationRestService, competitionRestService, pendingPartnerProgressRestService); } |
LegacyMonitoringOfficerController { @PreAuthorize("hasPermission(#projectId,'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_MONITORING_OFFICER_SECTION')") @GetMapping("/readonly") public String viewMonitoringOfficerInReadOnly(@P("projectId")@PathVariable("projectId") Long projectId, Model model) { LegacyMonitoringOfficerViewModel viewModel = getMonitoringOfficerViewModel(projectId); model.addAttribute("model", viewModel); model.addAttribute("readOnlyView", true); return "project/monitoring-officer"; } @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_MONITORING_OFFICER_SECTION')") @GetMapping String viewMonitoringOfficer(@P("projectId")@PathVariable("projectId") Long projectId, Model model); @PreAuthorize("hasPermission(#projectId,'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_MONITORING_OFFICER_SECTION')") @GetMapping("/readonly") String viewMonitoringOfficerInReadOnly(@P("projectId")@PathVariable("projectId") Long projectId, Model model); } | @Test public void viewMonitoringOfficerInReadOnly() throws Exception { ProjectResource project = projectBuilder.build(); boolean existingMonitoringOfficer = true; setupViewMonitoringOfficerTestExpectations(project, existingMonitoringOfficer); MvcResult result = mockMvc.perform(get("/project/123/monitoring-officer/readonly")). andExpect(view().name("project/monitoring-officer")). andExpect(model().attributeExists("readOnlyView")). andExpect(model().attribute("readOnlyView", true)). andReturn(); Map<String, Object> modelMap = result.getModelAndView().getModel(); LegacyMonitoringOfficerViewModel model = (LegacyMonitoringOfficerViewModel) modelMap.get("model"); Boolean readOnlyView = (Boolean) modelMap.get("readOnlyView"); assertProjectDetailsPrepopulatedOk(model); assertTrue(model.isMonitoringOfficerAssigned()); assertTrue(readOnlyView); } |
MonitoringOfficerDashboardController { @GetMapping public String viewDashboard(Model model, UserResource user) { model.addAttribute("model", monitoringOfficerDashboardViewModelPopulator.populate(user)); return "monitoring-officer/dashboard"; } MonitoringOfficerDashboardController(); @Autowired MonitoringOfficerDashboardController(MonitoringOfficerDashboardViewModelPopulator monitoringOfficerDashboardViewModelPopulator); @GetMapping String viewDashboard(Model model,
UserResource user); } | @Test public void viewDashboard() throws Exception { MonitoringOfficerDashboardViewModel model = mock(MonitoringOfficerDashboardViewModel.class); when(populator.populate(loggedInUser)).thenReturn(model); mockMvc.perform(get("/monitoring-officer/dashboard")) .andExpect(view().name("monitoring-officer/dashboard")) .andExpect(model().attribute("model", model)); } |
KnowledgeBaseServiceImpl extends RootTransactionalService implements KnowledgeBaseService { @Override public ServiceResult<List<String>> getKnowledgeBaseNames() { return serviceSuccess(stream(knowledgeBaseRepository.findAll().spliterator(), false) .map(KnowledgeBase::getName) .collect(toList())); } @Override ServiceResult<List<String>> getKnowledgeBaseNames(); @Override ServiceResult<String> getKnowledgeBaseName(long id); @Override ServiceResult<KnowledgeBaseResource> getKnowledgeBaseByName(String name); } | @Test public void getKnowledgeBaseNames() { when(knowledgeBaseRepository.findAll()).thenReturn(singleton(knowledgeBase)); ServiceResult<List<String>> result = service.getKnowledgeBaseNames(); assertTrue(result.isSuccess()); assertEquals(knowledgeBase.getName(), result.getSuccess().get(0)); } |
MonitoringOfficerDashboardViewModelPopulator { public MonitoringOfficerDashboardViewModel populate(UserResource user) { List<ProjectResource> projects = monitoringOfficerRestService.getProjectsForMonitoringOfficer(user.getId()).getSuccess(); List<ProjectDashboardRowViewModel> projectViews = projects.stream().map(project -> new ProjectDashboardRowViewModel(project.getApplication(), project.getCompetitionName(), project.getId(), project.getName())).collect(toList()); return new MonitoringOfficerDashboardViewModel(projectViews); } MonitoringOfficerDashboardViewModelPopulator(MonitoringOfficerRestService monitoringOfficerRestService); MonitoringOfficerDashboardViewModel populate(UserResource user); } | @Test public void populate() { UserResource user = newUserResource().build(); ProjectResource projectResource = newProjectResource() .withCompetition(1L) .withCompetitionName("Competition name") .withApplication(2L) .withName("Project name") .build(); when(monitoringOfficerRestService.getProjectsForMonitoringOfficer(user.getId())).thenReturn(restSuccess(singletonList(projectResource))); MonitoringOfficerDashboardViewModel viewModel = populator.populate(user); assertEquals(viewModel.getProjects().size(), 1); assertEquals(viewModel.getProjects().get(0).getProjectId(), (long) projectResource.getId()); assertEquals(viewModel.getProjects().get(0).getApplicationNumber(), projectResource.getApplication()); assertEquals(viewModel.getProjects().get(0).getCompetitionTitle(), "Competition name"); assertEquals(viewModel.getProjects().get(0).getLinkUrl(), String.format("/project-setup/project/%d", projectResource.getId())); assertEquals(viewModel.getProjects().get(0).getProjectTitle(), "Project name"); } |
SpendProfileTableCalculator { public Map<Long, BigDecimal> calculateRowTotal(Map<Long, List<BigDecimal>> tableData) { return simpleMapValue(tableData, rows -> rows.stream() .reduce(BigDecimal.ZERO, BigDecimal::add) ); } Map<Long, BigDecimal> calculateRowTotal(Map<Long, List<BigDecimal>> tableData); List<BigDecimal> calculateMonthlyTotals(Map<Long, List<BigDecimal>> tableData, int numberOfMonths); BigDecimal calculateTotalOfAllActualTotals(Map<Long, List<BigDecimal>> tableData); BigDecimal calculateTotalOfAllEligibleTotals(Map<Long, BigDecimal> eligibleCostData); SpendProfileSummaryModel createSpendProfileSummary(ProjectResource project, Map<Long, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyEligibleCostTotal(ProjectResource project, Map<String, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyGrantAllocationTotal(ProjectResource project,
Map<String, List<BigDecimal>> tableData,
List<LocalDateResource> months,
BigDecimal totalGrantPercentage); BigDecimal getAllocationValue(BigDecimal value, BigDecimal percentage); List<String> generateSpendProfileYears(ProjectResource project); List<BigDecimal> calculateEligibleCostPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months); List<BigDecimal> calculateGrantAllocationPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months, Integer grantPercentage); } | @Test public void testCalculateRowTotal() { Map<Long, BigDecimal> result = spendProfileTableCalculator.calculateRowTotal(TABLE_DATA); assertThat(result.get(ROW_NAME_1), equalTo(ROW_1_EXPECTED_TOTAL)); assertThat(result.get(ROW_NAME_2), equalTo(ROW_2_EXPECTED_TOTAL)); } |
SpendProfileTableCalculator { public List<BigDecimal> calculateMonthlyTotals(Map<Long, List<BigDecimal>> tableData, int numberOfMonths) { return IntStream.range(0, numberOfMonths).mapToObj(index -> tableData.values() .stream() .map(list -> list.get(index)) .reduce(BigDecimal.ZERO, BigDecimal::add) ).collect(Collectors.toList()); } Map<Long, BigDecimal> calculateRowTotal(Map<Long, List<BigDecimal>> tableData); List<BigDecimal> calculateMonthlyTotals(Map<Long, List<BigDecimal>> tableData, int numberOfMonths); BigDecimal calculateTotalOfAllActualTotals(Map<Long, List<BigDecimal>> tableData); BigDecimal calculateTotalOfAllEligibleTotals(Map<Long, BigDecimal> eligibleCostData); SpendProfileSummaryModel createSpendProfileSummary(ProjectResource project, Map<Long, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyEligibleCostTotal(ProjectResource project, Map<String, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyGrantAllocationTotal(ProjectResource project,
Map<String, List<BigDecimal>> tableData,
List<LocalDateResource> months,
BigDecimal totalGrantPercentage); BigDecimal getAllocationValue(BigDecimal value, BigDecimal percentage); List<String> generateSpendProfileYears(ProjectResource project); List<BigDecimal> calculateEligibleCostPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months); List<BigDecimal> calculateGrantAllocationPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months, Integer grantPercentage); } | @Test public void testCalculateMonthlyTotals() { int columns = 2; List<BigDecimal> result = spendProfileTableCalculator.calculateMonthlyTotals(TABLE_DATA, columns); assertThat(result.size(), equalTo(columns)); assertThat(result.get(0), equalTo(COLUMN_1_EXPECTED_TOTAL)); assertThat(result.get(1), equalTo(COLUMN_2_EXPECTED_TOTAL)); } |
SpendProfileTableCalculator { public BigDecimal calculateTotalOfAllActualTotals(Map<Long, List<BigDecimal>> tableData) { return tableData.values() .stream() .map(list -> list.stream() .reduce(BigDecimal.ZERO, BigDecimal::add) ) .reduce(BigDecimal.ZERO, BigDecimal::add); } Map<Long, BigDecimal> calculateRowTotal(Map<Long, List<BigDecimal>> tableData); List<BigDecimal> calculateMonthlyTotals(Map<Long, List<BigDecimal>> tableData, int numberOfMonths); BigDecimal calculateTotalOfAllActualTotals(Map<Long, List<BigDecimal>> tableData); BigDecimal calculateTotalOfAllEligibleTotals(Map<Long, BigDecimal> eligibleCostData); SpendProfileSummaryModel createSpendProfileSummary(ProjectResource project, Map<Long, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyEligibleCostTotal(ProjectResource project, Map<String, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyGrantAllocationTotal(ProjectResource project,
Map<String, List<BigDecimal>> tableData,
List<LocalDateResource> months,
BigDecimal totalGrantPercentage); BigDecimal getAllocationValue(BigDecimal value, BigDecimal percentage); List<String> generateSpendProfileYears(ProjectResource project); List<BigDecimal> calculateEligibleCostPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months); List<BigDecimal> calculateGrantAllocationPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months, Integer grantPercentage); } | @Test public void testCalculateTotalOfAllActualTotals() { BigDecimal result = spendProfileTableCalculator.calculateTotalOfAllActualTotals(TABLE_DATA); assertThat(result, equalTo(TOTAL_OF_ALL_TOTALS)); } |
SpendProfileTableCalculator { public BigDecimal calculateTotalOfAllEligibleTotals(Map<Long, BigDecimal> eligibleCostData) { return eligibleCostData .values() .stream() .reduce(BigDecimal.ZERO, BigDecimal::add); } Map<Long, BigDecimal> calculateRowTotal(Map<Long, List<BigDecimal>> tableData); List<BigDecimal> calculateMonthlyTotals(Map<Long, List<BigDecimal>> tableData, int numberOfMonths); BigDecimal calculateTotalOfAllActualTotals(Map<Long, List<BigDecimal>> tableData); BigDecimal calculateTotalOfAllEligibleTotals(Map<Long, BigDecimal> eligibleCostData); SpendProfileSummaryModel createSpendProfileSummary(ProjectResource project, Map<Long, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyEligibleCostTotal(ProjectResource project, Map<String, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyGrantAllocationTotal(ProjectResource project,
Map<String, List<BigDecimal>> tableData,
List<LocalDateResource> months,
BigDecimal totalGrantPercentage); BigDecimal getAllocationValue(BigDecimal value, BigDecimal percentage); List<String> generateSpendProfileYears(ProjectResource project); List<BigDecimal> calculateEligibleCostPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months); List<BigDecimal> calculateGrantAllocationPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months, Integer grantPercentage); } | @Test public void testCalculateTotalOfAllEligibleTotals() { BigDecimal result = spendProfileTableCalculator.calculateTotalOfAllEligibleTotals(ELIGIBLE_DATA); assertThat(result, equalTo(TOTAL_OF_ALL_TOTALS)); } |
SpendProfileTableCalculator { public SpendProfileSummaryModel createSpendProfileSummary(ProjectResource project, Map<Long, List<BigDecimal>> tableData, List<LocalDateResource> months) { Integer startYear = new FinancialYearDate(DateUtil.asDate(project.getTargetStartDate())).getFiscalYear(); Integer endYear = new FinancialYearDate(DateUtil.asDate(project.getTargetStartDate().plusMonths(project.getDurationInMonths()))).getFiscalYear(); List<SpendProfileSummaryYearModel> years = IntStream.range(startYear, endYear + 1). mapToObj( year -> { Set<Long> keys = tableData.keySet(); BigDecimal totalForYear = BigDecimal.ZERO; for (Long key : keys) { List<BigDecimal> values = tableData.get(key); for (int i = 0; i < values.size(); i++) { LocalDateResource month = months.get(i); FinancialYearDate financialYearDate = new FinancialYearDate(DateUtil.asDate(month.getLocalDate())); if (year == financialYearDate.getFiscalYear()) { totalForYear = totalForYear.add(values.get(i)); } } } return new SpendProfileSummaryYearModel(year, totalForYear.toPlainString()); } ).collect(toList()); return new SpendProfileSummaryModel(years); } Map<Long, BigDecimal> calculateRowTotal(Map<Long, List<BigDecimal>> tableData); List<BigDecimal> calculateMonthlyTotals(Map<Long, List<BigDecimal>> tableData, int numberOfMonths); BigDecimal calculateTotalOfAllActualTotals(Map<Long, List<BigDecimal>> tableData); BigDecimal calculateTotalOfAllEligibleTotals(Map<Long, BigDecimal> eligibleCostData); SpendProfileSummaryModel createSpendProfileSummary(ProjectResource project, Map<Long, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyEligibleCostTotal(ProjectResource project, Map<String, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyGrantAllocationTotal(ProjectResource project,
Map<String, List<BigDecimal>> tableData,
List<LocalDateResource> months,
BigDecimal totalGrantPercentage); BigDecimal getAllocationValue(BigDecimal value, BigDecimal percentage); List<String> generateSpendProfileYears(ProjectResource project); List<BigDecimal> calculateEligibleCostPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months); List<BigDecimal> calculateGrantAllocationPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months, Integer grantPercentage); } | @Test public void testCreateSpendProfileSummary() { ProjectResource project = newProjectResource() .withTargetStartDate(LocalDate.of(2019, 3, 1)) .withDuration(2L) .build(); List<LocalDateResource> months = Lists.newArrayList( new LocalDateResource(1, 3, 2019), new LocalDateResource(1, 4, 2019) ); SpendProfileSummaryModel result = spendProfileTableCalculator.createSpendProfileSummary(project, TABLE_DATA, months); assertThat(result.getYears().size(), equalTo(2)); assertThat(result.getYears().get(0).getAmount(), equalTo(COLUMN_1_EXPECTED_TOTAL.toPlainString())); assertThat(result.getYears().get(1).getAmount(), equalTo(COLUMN_2_EXPECTED_TOTAL.toPlainString())); } |
SpendProfileTableCalculator { public List<BigDecimal> calculateEligibleCostPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months) { Integer startYear = new FinancialYearDate(DateUtil.asDate(project.getTargetStartDate())).getFiscalYear(); Integer endYear = new FinancialYearDate(DateUtil.asDate(project.getTargetStartDate().plusMonths(project.getDurationInMonths()))).getFiscalYear(); LinkedList<BigDecimal> eligibleCostPerYear = new LinkedList<>(); IntStream.range(startYear, endYear + 1). mapToObj( year -> { BigDecimal totalForYear = BigDecimal.ZERO; totalForYear = getEligibleCostMonthlyTotal(monthlyCost, months, year, totalForYear); return eligibleCostPerYear.add(totalForYear); } ).collect(toList()); return eligibleCostPerYear; } Map<Long, BigDecimal> calculateRowTotal(Map<Long, List<BigDecimal>> tableData); List<BigDecimal> calculateMonthlyTotals(Map<Long, List<BigDecimal>> tableData, int numberOfMonths); BigDecimal calculateTotalOfAllActualTotals(Map<Long, List<BigDecimal>> tableData); BigDecimal calculateTotalOfAllEligibleTotals(Map<Long, BigDecimal> eligibleCostData); SpendProfileSummaryModel createSpendProfileSummary(ProjectResource project, Map<Long, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyEligibleCostTotal(ProjectResource project, Map<String, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyGrantAllocationTotal(ProjectResource project,
Map<String, List<BigDecimal>> tableData,
List<LocalDateResource> months,
BigDecimal totalGrantPercentage); BigDecimal getAllocationValue(BigDecimal value, BigDecimal percentage); List<String> generateSpendProfileYears(ProjectResource project); List<BigDecimal> calculateEligibleCostPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months); List<BigDecimal> calculateGrantAllocationPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months, Integer grantPercentage); } | @Test public void testCalculateEligibleCostPerYear() { ProjectResource projectResource = newProjectResource() .withTargetStartDate(LocalDate.of(2019, 3, 1)) .withDuration(2L) .build(); LinkedList<BigDecimal> monthlyCosts = new LinkedList<>(); monthlyCosts.add(BigDecimal.valueOf(300)); monthlyCosts.add(BigDecimal.valueOf(100)); monthlyCosts.add(BigDecimal.valueOf(400)); LocalDateResource localDateResource1 = new LocalDateResource(1, 3, 2019); LocalDateResource localDateResource2 = new LocalDateResource(1, 4, 2019); LocalDateResource localDateResource3 = new LocalDateResource(1, 5, 2019); List<LocalDateResource> months = new ArrayList<>(); months.add(localDateResource1); months.add(localDateResource2); months.add(localDateResource3); List<BigDecimal> eligibleCostPerYear = spendProfileTableCalculator.calculateEligibleCostPerYear(projectResource, monthlyCosts, months); assertTrue(eligibleCostPerYear.size() == 2); assertEquals(eligibleCostPerYear.get(0), BigDecimal.valueOf(300)); assertEquals(eligibleCostPerYear.get(1), BigDecimal.valueOf(500)); } |
SpendProfileTableCalculator { public List<BigDecimal> calculateGrantAllocationPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months, Integer grantPercentage) { Integer startYear = new FinancialYearDate(DateUtil.asDate(project.getTargetStartDate())).getFiscalYear(); Integer endYear = new FinancialYearDate(DateUtil.asDate(project.getTargetStartDate().plusMonths(project.getDurationInMonths()))).getFiscalYear(); LinkedList<BigDecimal> grantAllocationPerYear = new LinkedList<>(); IntStream.range(startYear, endYear + 1). mapToObj( year -> { BigDecimal totalForYear = BigDecimal.ZERO; totalForYear = getEligibleCostMonthlyTotal(monthlyCost, months, year, totalForYear); totalForYear = totalForYear.multiply(BigDecimal.valueOf(grantPercentage)).divide(BigDecimal.valueOf(100)) .setScale(1, RoundingMode.CEILING); return grantAllocationPerYear.add(totalForYear); } ).collect(toList()); return grantAllocationPerYear; } Map<Long, BigDecimal> calculateRowTotal(Map<Long, List<BigDecimal>> tableData); List<BigDecimal> calculateMonthlyTotals(Map<Long, List<BigDecimal>> tableData, int numberOfMonths); BigDecimal calculateTotalOfAllActualTotals(Map<Long, List<BigDecimal>> tableData); BigDecimal calculateTotalOfAllEligibleTotals(Map<Long, BigDecimal> eligibleCostData); SpendProfileSummaryModel createSpendProfileSummary(ProjectResource project, Map<Long, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyEligibleCostTotal(ProjectResource project, Map<String, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyGrantAllocationTotal(ProjectResource project,
Map<String, List<BigDecimal>> tableData,
List<LocalDateResource> months,
BigDecimal totalGrantPercentage); BigDecimal getAllocationValue(BigDecimal value, BigDecimal percentage); List<String> generateSpendProfileYears(ProjectResource project); List<BigDecimal> calculateEligibleCostPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months); List<BigDecimal> calculateGrantAllocationPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months, Integer grantPercentage); } | @Test public void testCalculateGrantAllocationPerYear() { ProjectResource projectResource = newProjectResource() .withTargetStartDate(LocalDate.of(2019, 3, 1)) .withDuration(2L) .build(); LinkedList<BigDecimal> monthlyCosts = new LinkedList<>(); monthlyCosts.add(BigDecimal.valueOf(300)); monthlyCosts.add(BigDecimal.valueOf(100)); monthlyCosts.add(BigDecimal.valueOf(400)); LocalDateResource localDateResource1 = new LocalDateResource(1, 3, 2019); LocalDateResource localDateResource2 = new LocalDateResource(1, 4, 2019); LocalDateResource localDateResource3 = new LocalDateResource(1, 5, 2019); List<LocalDateResource> months = new ArrayList<>(); months.add(localDateResource1); months.add(localDateResource2); months.add(localDateResource3); List<BigDecimal> grantAllocationPerYear = spendProfileTableCalculator.calculateGrantAllocationPerYear(projectResource, monthlyCosts, months, 30); assertTrue(grantAllocationPerYear.size() == 2); assertEquals(grantAllocationPerYear.get(0), BigDecimal.valueOf(90.0)); assertEquals(grantAllocationPerYear.get(1), BigDecimal.valueOf(150.0)); } |
SpendProfileTableCalculator { public Map<String, BigDecimal> createYearlyEligibleCostTotal(ProjectResource project, Map<String, List<BigDecimal>> tableData, List<LocalDateResource> months) { Map<String, BigDecimal> yearEligibleCostTotal = new LinkedHashMap<>(); Integer startYear = new FinancialYearDate(DateUtil.asDate(project.getTargetStartDate())).getFiscalYear(); Integer endYear = new FinancialYearDate(DateUtil.asDate(project.getTargetStartDate().plusMonths(project.getDurationInMonths()))).getFiscalYear(); IntStream.range(startYear, endYear + 1). forEach( year -> { Set<String> keys = tableData.keySet(); BigDecimal totalForYear = BigDecimal.ZERO; for (String key : keys) { List<BigDecimal> values = tableData.get(key); for (int i = 0; i < values.size(); i++) { LocalDateResource month = months.get(i); FinancialYearDate financialYearDate = new FinancialYearDate(DateUtil.asDate(month.getLocalDate())); if (year == financialYearDate.getFiscalYear()) { totalForYear = totalForYear.add(values.get(i)); } } } yearEligibleCostTotal.put(String.valueOf(year), totalForYear); } ); return yearEligibleCostTotal; } Map<Long, BigDecimal> calculateRowTotal(Map<Long, List<BigDecimal>> tableData); List<BigDecimal> calculateMonthlyTotals(Map<Long, List<BigDecimal>> tableData, int numberOfMonths); BigDecimal calculateTotalOfAllActualTotals(Map<Long, List<BigDecimal>> tableData); BigDecimal calculateTotalOfAllEligibleTotals(Map<Long, BigDecimal> eligibleCostData); SpendProfileSummaryModel createSpendProfileSummary(ProjectResource project, Map<Long, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyEligibleCostTotal(ProjectResource project, Map<String, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyGrantAllocationTotal(ProjectResource project,
Map<String, List<BigDecimal>> tableData,
List<LocalDateResource> months,
BigDecimal totalGrantPercentage); BigDecimal getAllocationValue(BigDecimal value, BigDecimal percentage); List<String> generateSpendProfileYears(ProjectResource project); List<BigDecimal> calculateEligibleCostPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months); List<BigDecimal> calculateGrantAllocationPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months, Integer grantPercentage); } | @Test public void testCreateYearlyEligibleCostTotal() { ProjectResource projectResource = newProjectResource() .withTargetStartDate(LocalDate.of(2019, 3, 1)) .withDuration(2L) .build(); LinkedList<BigDecimal> monthlyCosts = new LinkedList<>(); monthlyCosts.add(BigDecimal.valueOf(300)); monthlyCosts.add(BigDecimal.valueOf(100)); monthlyCosts.add(BigDecimal.valueOf(400)); LocalDateResource localDateResource1 = new LocalDateResource(1, 3, 2019); LocalDateResource localDateResource2 = new LocalDateResource(1, 4, 2019); LocalDateResource localDateResource3 = new LocalDateResource(1, 5, 2019); List<LocalDateResource> months = new ArrayList<>(); months.add(localDateResource1); months.add(localDateResource2); months.add(localDateResource3); Map<String, BigDecimal> yearlyEligibleCostTotal = spendProfileTableCalculator.createYearlyEligibleCostTotal(projectResource, TABLE_DATA2, months); assertTrue(yearlyEligibleCostTotal.size() == 2); assertEquals(yearlyEligibleCostTotal.get("2019"), BigDecimal.valueOf(36.81)); assertEquals(yearlyEligibleCostTotal.get("2018"), BigDecimal.valueOf(50.31)); } |
SpendProfileTableCalculator { public Map<String, BigDecimal> createYearlyGrantAllocationTotal(ProjectResource project, Map<String, List<BigDecimal>> tableData, List<LocalDateResource> months, BigDecimal totalGrantPercentage) { Map<String, BigDecimal> yearGrantAllocationTotal = new LinkedHashMap<>(); Integer startYear = new FinancialYearDate(DateUtil.asDate(project.getTargetStartDate())).getFiscalYear(); Integer endYear = new FinancialYearDate(DateUtil.asDate(project.getTargetStartDate().plusMonths(project.getDurationInMonths()))).getFiscalYear(); IntStream.range(startYear, endYear + 1). forEach( year -> { Set<String> keys = tableData.keySet(); BigDecimal totalForYear = BigDecimal.ZERO; for (String key : keys) { List<BigDecimal> values = tableData.get(key); for (int i = 0; i < values.size(); i++) { LocalDateResource month = months.get(i); FinancialYearDate financialYearDate = new FinancialYearDate(DateUtil.asDate(month.getLocalDate())); if (year == financialYearDate.getFiscalYear()) { totalForYear = totalForYear.add(values.get(i)); } } } totalForYear = getAllocationValue(totalForYear, totalGrantPercentage); yearGrantAllocationTotal.put(String.valueOf(year), totalForYear); } ); return yearGrantAllocationTotal; } Map<Long, BigDecimal> calculateRowTotal(Map<Long, List<BigDecimal>> tableData); List<BigDecimal> calculateMonthlyTotals(Map<Long, List<BigDecimal>> tableData, int numberOfMonths); BigDecimal calculateTotalOfAllActualTotals(Map<Long, List<BigDecimal>> tableData); BigDecimal calculateTotalOfAllEligibleTotals(Map<Long, BigDecimal> eligibleCostData); SpendProfileSummaryModel createSpendProfileSummary(ProjectResource project, Map<Long, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyEligibleCostTotal(ProjectResource project, Map<String, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyGrantAllocationTotal(ProjectResource project,
Map<String, List<BigDecimal>> tableData,
List<LocalDateResource> months,
BigDecimal totalGrantPercentage); BigDecimal getAllocationValue(BigDecimal value, BigDecimal percentage); List<String> generateSpendProfileYears(ProjectResource project); List<BigDecimal> calculateEligibleCostPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months); List<BigDecimal> calculateGrantAllocationPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months, Integer grantPercentage); } | @Test public void testCreateYearlyGrantAllocationTotal() { ProjectResource projectResource = newProjectResource() .withTargetStartDate(LocalDate.of(2019, 3, 1)) .withDuration(2L) .build(); LinkedList<BigDecimal> monthlyCosts = new LinkedList<>(); monthlyCosts.add(BigDecimal.valueOf(300)); monthlyCosts.add(BigDecimal.valueOf(100)); monthlyCosts.add(BigDecimal.valueOf(400)); LocalDateResource localDateResource1 = new LocalDateResource(1, 3, 2019); LocalDateResource localDateResource2 = new LocalDateResource(1, 4, 2019); LocalDateResource localDateResource3 = new LocalDateResource(1, 5, 2019); List<LocalDateResource> months = new ArrayList<>(); months.add(localDateResource1); months.add(localDateResource2); months.add(localDateResource3); Map<String, BigDecimal> yearlyGrantAllocationTotal = spendProfileTableCalculator.createYearlyGrantAllocationTotal(projectResource, TABLE_DATA2, months, BigDecimal.valueOf(25)); assertTrue(yearlyGrantAllocationTotal.size() == 2); assertEquals(yearlyGrantAllocationTotal.get("2019"), BigDecimal.valueOf(9)); assertEquals(yearlyGrantAllocationTotal.get("2018"), BigDecimal.valueOf(12)); } |
KnowledgeBaseServiceImpl extends RootTransactionalService implements KnowledgeBaseService { @Override public ServiceResult<KnowledgeBaseResource> getKnowledgeBaseByName(String name) { return find(knowledgeBaseRepository.findByName(name), notFoundError(KnowledgeBase.class, singletonList(name))) .andOnSuccessReturn(knowledgeBaseMapper::mapToResource); } @Override ServiceResult<List<String>> getKnowledgeBaseNames(); @Override ServiceResult<String> getKnowledgeBaseName(long id); @Override ServiceResult<KnowledgeBaseResource> getKnowledgeBaseByName(String name); } | @Test public void getKnowledgeBaseByName() { String name = "KnowledgeBase 1"; when(knowledgeBaseRepository.findByName(name)).thenReturn(Optional.of(knowledgeBase)); when(KnowledgeBaseMapper.mapToResource(knowledgeBase)).thenReturn(knowledgeBaseResource); ServiceResult<KnowledgeBaseResource> result = service.getKnowledgeBaseByName(name); assertTrue(result.isSuccess()); assertEquals(knowledgeBase.getName(), result.getSuccess().getName()); } |
SpendProfileTableCalculator { public List<String> generateSpendProfileYears(ProjectResource project) { Integer startYear = new FinancialYearDate(DateUtil.asDate(project.getTargetStartDate())).getFiscalYear(); Integer endYear = new FinancialYearDate(DateUtil.asDate(project.getTargetStartDate().plusMonths(project.getDurationInMonths()))).getFiscalYear(); LinkedList<String> years = new LinkedList<>(); IntStream.range(startYear, endYear + 1).forEach( year -> years.add(String.valueOf(year)) ); return years; } Map<Long, BigDecimal> calculateRowTotal(Map<Long, List<BigDecimal>> tableData); List<BigDecimal> calculateMonthlyTotals(Map<Long, List<BigDecimal>> tableData, int numberOfMonths); BigDecimal calculateTotalOfAllActualTotals(Map<Long, List<BigDecimal>> tableData); BigDecimal calculateTotalOfAllEligibleTotals(Map<Long, BigDecimal> eligibleCostData); SpendProfileSummaryModel createSpendProfileSummary(ProjectResource project, Map<Long, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyEligibleCostTotal(ProjectResource project, Map<String, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyGrantAllocationTotal(ProjectResource project,
Map<String, List<BigDecimal>> tableData,
List<LocalDateResource> months,
BigDecimal totalGrantPercentage); BigDecimal getAllocationValue(BigDecimal value, BigDecimal percentage); List<String> generateSpendProfileYears(ProjectResource project); List<BigDecimal> calculateEligibleCostPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months); List<BigDecimal> calculateGrantAllocationPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months, Integer grantPercentage); } | @Test public void testGenerateSpendProfileYears() { ProjectResource projectResource = newProjectResource() .withTargetStartDate(LocalDate.of(2019, 3, 1)) .withDuration(2L) .build(); List<String> profileYears = spendProfileTableCalculator.generateSpendProfileYears(projectResource); assertTrue(profileYears.size() == 2); assertEquals(profileYears.get(0), "2018"); assertEquals(profileYears.get(1), "2019"); } |
SpendProfileTableCalculator { public BigDecimal getAllocationValue(BigDecimal value, BigDecimal percentage){ BigDecimal percent = percentage.divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP); return value.multiply(percent).setScale(0, BigDecimal.ROUND_DOWN); } Map<Long, BigDecimal> calculateRowTotal(Map<Long, List<BigDecimal>> tableData); List<BigDecimal> calculateMonthlyTotals(Map<Long, List<BigDecimal>> tableData, int numberOfMonths); BigDecimal calculateTotalOfAllActualTotals(Map<Long, List<BigDecimal>> tableData); BigDecimal calculateTotalOfAllEligibleTotals(Map<Long, BigDecimal> eligibleCostData); SpendProfileSummaryModel createSpendProfileSummary(ProjectResource project, Map<Long, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyEligibleCostTotal(ProjectResource project, Map<String, List<BigDecimal>> tableData, List<LocalDateResource> months); Map<String, BigDecimal> createYearlyGrantAllocationTotal(ProjectResource project,
Map<String, List<BigDecimal>> tableData,
List<LocalDateResource> months,
BigDecimal totalGrantPercentage); BigDecimal getAllocationValue(BigDecimal value, BigDecimal percentage); List<String> generateSpendProfileYears(ProjectResource project); List<BigDecimal> calculateEligibleCostPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months); List<BigDecimal> calculateGrantAllocationPerYear(ProjectResource project, List<BigDecimal> monthlyCost, List<LocalDateResource> months, Integer grantPercentage); } | @Test public void tesGetAllocationValue() { BigDecimal allocationValue = spendProfileTableCalculator.getAllocationValue(BigDecimal.valueOf(212153), BigDecimal.valueOf(30)); assertEquals(allocationValue, BigDecimal.valueOf(63645)); } |
TotalSpendProfileViewModel { public boolean isKtpCompetition() { return ktpCompetition; } TotalSpendProfileViewModel(ProjectResource project, TotalProjectSpendProfileTableViewModel table,
SpendProfileSummaryModel summary, boolean ktpCompetition); ProjectResource getProject(); TotalProjectSpendProfileTableViewModel getTable(); SpendProfileSummaryModel getSummary(); boolean isIncludeFinancialYearTable(); boolean isKtpCompetition(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | @Test public void testKtpCompetition() { CompetitionResource competitionResource = CompetitionResourceBuilder.newCompetitionResource() .withFundingType(FundingType.KTP).build(); ProjectResource projectResource = ProjectResourceBuilder.newProjectResource().build(); TotalSpendProfileViewModel viewModel = new TotalSpendProfileViewModel(projectResource, null, null, competitionResource.isKtp()); assertTrue(viewModel.isKtpCompetition()); }
@Test public void testNonKtpCompetition() { CompetitionResource competitionResource = CompetitionResourceBuilder.newCompetitionResource() .withFundingType(FundingType.GRANT).build(); ProjectResource projectResource = ProjectResourceBuilder.newProjectResource().build(); TotalSpendProfileViewModel viewModel = new TotalSpendProfileViewModel(projectResource, null, null, competitionResource.isKtp()); assertFalse(viewModel.isKtpCompetition()); } |
ProjectSpendProfileViewModel { public boolean isKtpCompetition() { return ktpCompetition; } ProjectSpendProfileViewModel(ProjectResource project, OrganisationResource organisationResource, SpendProfileTableResource table,
SpendProfileSummaryModel summary, Boolean markedAsComplete,
Map<Long, BigDecimal> categoryToActualTotal, List<BigDecimal> totalForEachMonth,
BigDecimal totalOfAllActualTotals, BigDecimal totalOfAllEligibleTotals, boolean submitted,
Map<String, List<Map<Long, List<BigDecimal>>>> costCategoryGroupMap,
Map<Long, CostCategoryResource> costCategoryResourceMap, Boolean usingJesFinances, boolean userPartOfThisOrganisation,
boolean isProjectManager, boolean approved, boolean leadPartner, boolean ktpCompetition); Long getProjectId(); String getProjectName(); String getOrganisationName(); LocalDate getTargetProjectStartDate(); Long getDurationInMonths(); SpendProfileSummaryModel getSummary(); SpendProfileTableResource getTable(); void setProjectId(Long projectId); void setProjectName(String projectName); void setTargetProjectStartDate(LocalDate targetProjectStartDate); void setDurationInMonths(Long durationInMonths); void setSummary(SpendProfileSummaryModel summary); void setTable(SpendProfileTableResource table); Boolean isMarkedAsComplete(); void setMarkedAsComplete(Boolean markedAsComplete); Long getOrganisationId(); void setOrganisationId(Long organisationId); Map<Long, BigDecimal> getCategoryToActualTotal(); List<BigDecimal> getTotalForEachMonth(); BigDecimal getTotalOfAllActualTotals(); BigDecimal getTotalOfAllEligibleTotals(); List<ObjectError> getObjectErrors(); void setObjectErrors(List<ObjectError> objectErrors); Boolean getMarkedAsComplete(); boolean isApproved(); void setCategoryToActualTotal(Map<Long, BigDecimal> categoryToActualTotal); void setTotalForEachMonth(List<BigDecimal> totalForEachMonth); void setTotalOfAllActualTotals(BigDecimal totalOfAllActualTotals); void setTotalOfAllEligibleTotals(BigDecimal totalOfAllEligibleTotals); Boolean getUsingJesFinances(); void setUsingJesFinances(Boolean usingJesFinances); Map<Long, CostCategoryResource> getCostCategoryResourceMap(); void setCostCategoryResourceMap(Map<Long, CostCategoryResource> costCategoryResourceMap); boolean isSubmitted(); boolean isUserPartOfThisOrganisation(); boolean isProjectManager(); Long getApplicationId(); boolean isLeadPartner(); void setLeadPartner(boolean leadPartner); boolean isIncludeFinancialYearTable(); boolean isKtpCompetition(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | @Test public void testKtpCompetition() { CompetitionResource competitionResource = CompetitionResourceBuilder.newCompetitionResource() .withFundingType(FundingType.KTP).build(); ProjectResource projectResource = ProjectResourceBuilder.newProjectResource().build(); OrganisationResource organisationResource = OrganisationResourceBuilder.newOrganisationResource().build(); ProjectSpendProfileViewModel viewModel = new ProjectSpendProfileViewModel(projectResource, organisationResource, null, null, null, null, null, null, null, false, null, null, null, false, false, false, false, competitionResource.isKtp()); assertTrue(viewModel.isKtpCompetition()); }
@Test public void testNonKtpCompetition() { CompetitionResource competitionResource = CompetitionResourceBuilder.newCompetitionResource() .withFundingType(FundingType.GRANT).build(); ProjectResource projectResource = ProjectResourceBuilder.newProjectResource().build(); OrganisationResource organisationResource = OrganisationResourceBuilder.newOrganisationResource().build(); ProjectSpendProfileViewModel viewModel = new ProjectSpendProfileViewModel(projectResource, organisationResource, null, null, null, null, null, null, null, false, null, null, null, false, false, false, false, competitionResource.isKtp()); assertFalse(viewModel.isKtpCompetition()); } |
ProjectSpendProfileController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION')") @PostMapping("/edit") public String saveSpendProfile(Model model, @ModelAttribute(FORM_ATTR_NAME) SpendProfileForm form, @SuppressWarnings("unused") BindingResult bindingResult, ValidationHandler validationHandler, @P("projectId")@PathVariable("projectId") final Long projectId, @PathVariable("organisationId") final Long organisationId, UserResource loggedInUser) { Supplier<String> failureView = () -> { SpendProfileTableResource updatedTable = form.getTable(); SpendProfileTableResource originalTableWithUpdatedCosts = spendProfileService.getSpendProfileTable(projectId, organisationId); originalTableWithUpdatedCosts.setMonthlyCostsPerCategoryMap(updatedTable.getMonthlyCostsPerCategoryMap()); ProjectResource project = projectService.getById(projectId); return doEditSpendProfile(model, form, organisationId, loggedInUser, project, originalTableWithUpdatedCosts); }; spendProfileCostValidator.validate(form.getTable(), bindingResult); return validationHandler.failNowOrSucceedWith(failureView, () -> { SpendProfileTableResource spendProfileTableResource = spendProfileService.getSpendProfileTable(projectId, organisationId); spendProfileTableResource.setMonthlyCostsPerCategoryMap(form.getTable().getMonthlyCostsPerCategoryMap()); ServiceResult<Void> result = spendProfileService.saveSpendProfile(projectId, organisationId, spendProfileTableResource); return validationHandler.addAnyErrors(result).failNowOrSucceedWith(failureView, () -> saveSpendProfileSuccessView(projectId, organisationId, loggedInUser.getId())); }); } @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION')") @GetMapping String viewSpendProfile(Model model,
@P("projectId")@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION')") @GetMapping("/review") String reviewSpendProfilePage(Model model,
@P("projectId")@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId,
UserResource loggedInUser); @PreAuthorize("hasPermission(new org.innovateuk.ifs.project.resource.ProjectOrganisationCompositeId(#projectId, #organisationId), 'EDIT_SPEND_PROFILE_SECTION')") @GetMapping("/edit") String editSpendProfile(Model model,
@ModelAttribute(name = FORM_ATTR_NAME, binding = false) SpendProfileForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
@P("projectId")@PathVariable("projectId") final Long projectId,
@P("organisationId")@PathVariable("organisationId") final Long organisationId,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION')") @PostMapping("/edit") String saveSpendProfile(Model model,
@ModelAttribute(FORM_ATTR_NAME) SpendProfileForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
@P("projectId")@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION') && hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'MARK_SPEND_PROFILE_INCOMPLETE') && hasPermission(#projectOrganisationCompositeId, 'IS_NOT_FROM_OWN_ORGANISATION')") @PostMapping("/incomplete") String markAsActionRequiredSpendProfile(Model model,
@ModelAttribute(FORM_ATTR_NAME) SpendProfileForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
@P("projectId")@PathVariable("projectId") final Long projectId,
@P("organisationId")@PathVariable("organisationId") final Long organisationId,
ProjectOrganisationCompositeId projectOrganisationCompositeId,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION')") @PostMapping("/complete") String markAsCompleteSpendProfile(Model model,
@P("projectId")@PathVariable("projectId") final Long projectId,
@P("organisationId")@PathVariable("organisationId") final Long organisationId,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION')") @GetMapping("/confirm") String viewConfirmSpendProfilePage(@P("projectId")@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION') && hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'MARK_SPEND_PROFILE_INCOMPLETE') && hasPermission(#projectOrganisationCompositeId, 'IS_NOT_FROM_OWN_ORGANISATION')") @GetMapping("/incomplete") String viewConfirmEditSpendProfilePage(@P("projectId")@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId,
ProjectOrganisationCompositeId projectOrganisationCompositeId,
Model model,
UserResource loggedInUser); } | @Test public void saveSpendProfileWhenErrorWhilstSaving() throws Exception { long projectId = 1L; long organisationId = 2L; long competitionId = 3L; ProjectResource projectResource = newProjectResource() .withName("projectName1") .withTargetStartDate(LocalDate.of(2018, 3, 1)) .withDuration(3L) .withCompetition(competitionId) .build(); CompetitionResource competition = newCompetitionResource() .withIncludeJesForm(true) .withFundingType(FundingType.GRANT) .build(); List<ProjectUserResource> projectUsers = newProjectUserResource() .withUser(1L) .withOrganisation(1L) .withRole(PARTNER) .build(1); OrganisationResource organisation = newOrganisationResource().withId(organisationId) .withOrganisationType(OrganisationTypeEnum.BUSINESS.getId()) .withOrganisationTypeName("BUSINESS") .build(); SpendProfileTableResource table = buildSpendProfileTableResource(projectResource); when(spendProfileService.getSpendProfileTable(projectId, organisationId)).thenReturn(table); List<Error> incorrectCosts = new ArrayList<>(); incorrectCosts.add(new Error(SPEND_PROFILE_TOTAL_FOR_ALL_MONTHS_DOES_NOT_MATCH_ELIGIBLE_TOTAL_FOR_SPECIFIED_CATEGORY, asList("Labour", 1), HttpStatus.BAD_REQUEST)); when(spendProfileService.saveSpendProfile(projectId, organisationId, table)).thenReturn(serviceFailure(incorrectCosts)); when(projectService.getById(projectId)).thenReturn(projectResource); when(organisationRestService.getOrganisationById(organisationId)).thenReturn(restSuccess(organisation)); when(projectService.getProjectUsersForProject(projectResource.getId())).thenReturn(projectUsers); when(competitionRestService.getCompetitionById(competitionId)).thenReturn(restSuccess(competition)); ProjectTeamStatusResource teamStatus = buildProjectTeamStatusResource(); when(statusService.getProjectTeamStatus(projectResource.getId(), Optional.empty())).thenReturn(teamStatus); MvcResult result = mockMvc.perform(post("/project/{projectId}/partner-organisation/{organisationId}/spend-profile/edit", projectId, organisationId) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("table.markedAsComplete", "true") .param("table.monthlyCostsPerCategoryMap[1][0]", "10") .param("table.monthlyCostsPerCategoryMap[1][1]", "10") .param("table.monthlyCostsPerCategoryMap[1][2]", "10") .param("table.monthlyCostsPerCategoryMap[2][0]", "10") .param("table.monthlyCostsPerCategoryMap[2][1]", "10") .param("table.monthlyCostsPerCategoryMap[2][2]", "10") .param("table.monthlyCostsPerCategoryMap[3][0]", "10") .param("table.monthlyCostsPerCategoryMap[3][1]", "10") .param("table.monthlyCostsPerCategoryMap[3][2]", "10") ) .andExpect(view().name("project/spend-profile")).andReturn(); SpendProfileForm form = (SpendProfileForm) result.getModelAndView().getModel().get("form"); assertEquals(1, form.getObjectErrors().size()); verify(projectService).getById(projectId); verify(spendProfileService, times(2)).getSpendProfileTable(projectId, organisationId); verify(organisationRestService).getOrganisationById(organisationId); verify(projectService, times(1)).getProjectUsersForProject(projectResource.getId()); }
@Test public void saveSpendProfileSuccess() throws Exception { long projectId = 1L; long organisationId = 1L; SpendProfileTableResource table = new SpendProfileTableResource(); when(spendProfileService.getSpendProfileTable(projectId, organisationId)).thenReturn(table); when(spendProfileService.saveSpendProfile(projectId, organisationId, table)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{projectId}/partner-organisation/{organisationId}/spend-profile/edit", projectId, organisationId) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("table.markedAsComplete", "true") ) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/project/" + projectId + "/partner-organisation/" + organisationId + "/spend-profile")); }
@Test public void saveSpendProfileSuccessLeadPartner() throws Exception { long projectId = 1L; long organisationId = 1L; SpendProfileTableResource table = new SpendProfileTableResource(); when(spendProfileService.getSpendProfileTable(projectId, organisationId)).thenReturn(table); when(spendProfileService.saveSpendProfile(projectId, organisationId, table)).thenReturn(serviceSuccess()); when(projectService.isUserLeadPartner(eq(projectId),anyLong())).thenReturn(true); mockMvc.perform(post("/project/{projectId}/partner-organisation/{organisationId}/spend-profile/edit", projectId, organisationId) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("table.markedAsComplete", "true") ) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/project/" + projectId + "/partner-organisation/" + organisationId + "/spend-profile/review")); }
@Test public void saveSpendProfileWithMissingTableEntries() throws Exception { Long projectId = 1L; Long organisationId = 1L; Long competitionId = 1L; ProjectResource projectResource = newProjectResource() .withName("projectName1") .withTargetStartDate(LocalDate.of(2018, 3, 1)) .withDuration(3L) .withCompetition(competitionId) .build(); CompetitionResource competition = newCompetitionResource() .withIncludeJesForm(true) .withFundingType(FundingType.GRANT) .build(); List<ProjectUserResource> projectUsers = newProjectUserResource() .withUser(1L) .withOrganisation(1L) .withRole(PARTNER) .build(1); OrganisationResource organisation = newOrganisationResource().withId(organisationId) .withOrganisationType(OrganisationTypeEnum.BUSINESS.getId()) .withOrganisationTypeName("BUSINESS") .build(); SpendProfileTableResource table = buildSpendProfileTableResource(projectResource); when(spendProfileService.getSpendProfileTable(projectId, organisationId)).thenReturn(table); List<Error> incorrectCosts = new ArrayList<>(); incorrectCosts.add(new Error(SPEND_PROFILE_TOTAL_FOR_ALL_MONTHS_DOES_NOT_MATCH_ELIGIBLE_TOTAL_FOR_SPECIFIED_CATEGORY, asList("Labour", 1), HttpStatus.BAD_REQUEST)); when(spendProfileService.saveSpendProfile(projectId, organisationId, table)).thenReturn(serviceFailure(incorrectCosts)); when(projectService.getById(projectId)).thenReturn(projectResource); when(organisationRestService.getOrganisationById(organisationId)).thenReturn(restSuccess(organisation)); when(projectService.getProjectUsersForProject(projectResource.getId())).thenReturn(projectUsers); when(competitionRestService.getCompetitionById(competitionId)).thenReturn(restSuccess(competition)); ProjectTeamStatusResource teamStatus = buildProjectTeamStatusResource(); when(statusService.getProjectTeamStatus(projectResource.getId(), Optional.empty())).thenReturn(teamStatus); MvcResult result = mockMvc.perform(post("/project/{projectId}/partner-organisation/{organisationId}/spend-profile/edit", projectId, organisationId) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("table.markedAsComplete", "true") .param("table.monthlyCostsPerCategoryMap[1][0]", "a") .param("table.monthlyCostsPerCategoryMap[1][1]", "10") .param("table.monthlyCostsPerCategoryMap[1][2]", "10") .param("table.monthlyCostsPerCategoryMap[2][0]", "10") .param("table.monthlyCostsPerCategoryMap[2][1]", "10") .param("table.monthlyCostsPerCategoryMap[2][2]", "10") .param("table.monthlyCostsPerCategoryMap[3][0]", "10") .param("table.monthlyCostsPerCategoryMap[3][1]", "10") .param("table.monthlyCostsPerCategoryMap[3][2]", "10") ) .andExpect(view().name("project/spend-profile")).andReturn(); SpendProfileForm form = (SpendProfileForm) result.getModelAndView().getModel().get("form"); assertEquals(1, form.getObjectErrors().size()); verify(projectService).getById(projectId); verify(spendProfileService).getSpendProfileTable(projectId, organisationId); verify(organisationRestService).getOrganisationById(organisationId); verify(projectService, times(1)).getProjectUsersForProject(projectResource.getId()); } |
ProjectSpendProfileController { private String markSpendProfileComplete(Model model, final Long projectId, final Long organisationId, final String successView, final UserResource loggedInUser) { ServiceResult<Void> result = spendProfileService.markSpendProfileComplete(projectId, organisationId); if (result.isFailure()) { ProjectSpendProfileViewModel spendProfileViewModel = buildSpendProfileViewModel(projectId, organisationId, loggedInUser); spendProfileViewModel.setObjectErrors(Collections.singletonList(new ObjectError(SPEND_PROFILE_CANNOT_MARK_AS_COMPLETE_BECAUSE_SPEND_HIGHER_THAN_ELIGIBLE.getErrorKey(), "Cannot mark as complete, because totals more than eligible"))); model.addAttribute("model", spendProfileViewModel); return BASE_DIR + "/spend-profile"; } else { return successView; } } @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION')") @GetMapping String viewSpendProfile(Model model,
@P("projectId")@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION')") @GetMapping("/review") String reviewSpendProfilePage(Model model,
@P("projectId")@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId,
UserResource loggedInUser); @PreAuthorize("hasPermission(new org.innovateuk.ifs.project.resource.ProjectOrganisationCompositeId(#projectId, #organisationId), 'EDIT_SPEND_PROFILE_SECTION')") @GetMapping("/edit") String editSpendProfile(Model model,
@ModelAttribute(name = FORM_ATTR_NAME, binding = false) SpendProfileForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
@P("projectId")@PathVariable("projectId") final Long projectId,
@P("organisationId")@PathVariable("organisationId") final Long organisationId,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION')") @PostMapping("/edit") String saveSpendProfile(Model model,
@ModelAttribute(FORM_ATTR_NAME) SpendProfileForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
@P("projectId")@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION') && hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'MARK_SPEND_PROFILE_INCOMPLETE') && hasPermission(#projectOrganisationCompositeId, 'IS_NOT_FROM_OWN_ORGANISATION')") @PostMapping("/incomplete") String markAsActionRequiredSpendProfile(Model model,
@ModelAttribute(FORM_ATTR_NAME) SpendProfileForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
@P("projectId")@PathVariable("projectId") final Long projectId,
@P("organisationId")@PathVariable("organisationId") final Long organisationId,
ProjectOrganisationCompositeId projectOrganisationCompositeId,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION')") @PostMapping("/complete") String markAsCompleteSpendProfile(Model model,
@P("projectId")@PathVariable("projectId") final Long projectId,
@P("organisationId")@PathVariable("organisationId") final Long organisationId,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION')") @GetMapping("/confirm") String viewConfirmSpendProfilePage(@P("projectId")@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION') && hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'MARK_SPEND_PROFILE_INCOMPLETE') && hasPermission(#projectOrganisationCompositeId, 'IS_NOT_FROM_OWN_ORGANISATION')") @GetMapping("/incomplete") String viewConfirmEditSpendProfilePage(@P("projectId")@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId,
ProjectOrganisationCompositeId projectOrganisationCompositeId,
Model model,
UserResource loggedInUser); } | @Test public void markAsCompleteSpendProfileWhenSpendHigherThanEligible() throws Exception { long organisationId = 1L; long projectId = 2L; long competitionId = 1L; ProjectResource projectResource = newProjectResource() .withName("projectName1") .withTargetStartDate(LocalDate.of(2018, 3, 1)) .withDuration(3L) .withId(projectId) .withCompetition(competitionId) .build(); CompetitionResource competition = newCompetitionResource() .withIncludeJesForm(true) .withFundingType(FundingType.GRANT) .build(); SpendProfileTableResource table = buildSpendProfileTableResource(projectResource); ProjectTeamStatusResource teamStatus = buildProjectTeamStatusResource(); PartnerOrganisationResource partnerOrganisationResource = new PartnerOrganisationResource(); partnerOrganisationResource.setOrganisation(organisationId); partnerOrganisationResource.setLeadOrganisation(false); when(projectService.getById(projectResource.getId())).thenReturn(projectResource); when(spendProfileService.getSpendProfileTable(projectResource.getId(), organisationId)).thenReturn(table); when(projectService.getLeadPartners(projectResource.getId())).thenReturn(Collections.emptyList()); when(statusService.getProjectTeamStatus(projectResource.getId(), Optional.empty())).thenReturn(teamStatus); when(spendProfileService.markSpendProfileComplete(projectResource.getId(), organisationId)).thenReturn(serviceFailure(SPEND_PROFILE_CANNOT_MARK_AS_COMPLETE_BECAUSE_SPEND_HIGHER_THAN_ELIGIBLE)); when(competitionRestService.getCompetitionById(competitionId)).thenReturn(restSuccess(competition)); ProjectSpendProfileViewModel expectedViewModel = buildExpectedProjectSpendProfileViewModel(organisationId, projectResource, table, competition); expectedViewModel.setObjectErrors(singletonList(new ObjectError(SPEND_PROFILE_CANNOT_MARK_AS_COMPLETE_BECAUSE_SPEND_HIGHER_THAN_ELIGIBLE.getErrorKey(), "Cannot mark as complete, because totals more than eligible"))); mockMvc.perform(post("/project/{projectId}/partner-organisation/{organisationId}/spend-profile/complete", projectResource.getId(), organisationId)) .andExpect(status().isOk()) .andExpect(model().attribute("model", expectedViewModel)) .andExpect(view().name("project/spend-profile")); verify(spendProfileService).markSpendProfileComplete(2L, 1L); }
@Test public void markAsCompleteSpendProfileSuccess() throws Exception { long projectId = 1L; long organisationId = 2L; when(spendProfileService.markSpendProfileComplete(projectId, organisationId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{projectId}/partner-organisation/{organisationId}/spend-profile/complete", projectId, organisationId)) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/project/" + projectId + "/partner-organisation/" + organisationId + "/spend-profile")); verify(spendProfileService).markSpendProfileComplete(1L, 2L); } |
SectionPermissionRules extends BasePermissionRules { @PermissionRule(value = "READ", description = "everyone can read sections") public boolean userCanReadSection(SectionResource section, UserResource user) { return true; } @PermissionRule(value = "READ", description = "everyone can read sections") boolean userCanReadSection(SectionResource section, UserResource user); @PermissionRule(value = "UPDATE", description = "no one can update sections yet") boolean userCanUpdateSection(SectionResource section, UserResource user); } | @Test public void userCanReadSection() { SectionResource section = SectionResourceBuilder.newSectionResource().build(); UserResource user = UserResourceBuilder.newUserResource().build(); assertTrue(rules.userCanReadSection(section, user)); } |
ProjectSpendProfileController { private ServiceResult<Void> markSpendProfileIncomplete(final Long projectId, final Long organisationId) { return spendProfileService.markSpendProfileIncomplete(projectId, organisationId); } @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION')") @GetMapping String viewSpendProfile(Model model,
@P("projectId")@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION')") @GetMapping("/review") String reviewSpendProfilePage(Model model,
@P("projectId")@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId,
UserResource loggedInUser); @PreAuthorize("hasPermission(new org.innovateuk.ifs.project.resource.ProjectOrganisationCompositeId(#projectId, #organisationId), 'EDIT_SPEND_PROFILE_SECTION')") @GetMapping("/edit") String editSpendProfile(Model model,
@ModelAttribute(name = FORM_ATTR_NAME, binding = false) SpendProfileForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
@P("projectId")@PathVariable("projectId") final Long projectId,
@P("organisationId")@PathVariable("organisationId") final Long organisationId,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION')") @PostMapping("/edit") String saveSpendProfile(Model model,
@ModelAttribute(FORM_ATTR_NAME) SpendProfileForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
@P("projectId")@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION') && hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'MARK_SPEND_PROFILE_INCOMPLETE') && hasPermission(#projectOrganisationCompositeId, 'IS_NOT_FROM_OWN_ORGANISATION')") @PostMapping("/incomplete") String markAsActionRequiredSpendProfile(Model model,
@ModelAttribute(FORM_ATTR_NAME) SpendProfileForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
@P("projectId")@PathVariable("projectId") final Long projectId,
@P("organisationId")@PathVariable("organisationId") final Long organisationId,
ProjectOrganisationCompositeId projectOrganisationCompositeId,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION')") @PostMapping("/complete") String markAsCompleteSpendProfile(Model model,
@P("projectId")@PathVariable("projectId") final Long projectId,
@P("organisationId")@PathVariable("organisationId") final Long organisationId,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION')") @GetMapping("/confirm") String viewConfirmSpendProfilePage(@P("projectId")@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_SPEND_PROFILE_SECTION') && hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'MARK_SPEND_PROFILE_INCOMPLETE') && hasPermission(#projectOrganisationCompositeId, 'IS_NOT_FROM_OWN_ORGANISATION')") @GetMapping("/incomplete") String viewConfirmEditSpendProfilePage(@P("projectId")@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId,
ProjectOrganisationCompositeId projectOrganisationCompositeId,
Model model,
UserResource loggedInUser); } | @Test public void markAsIncompleteSpendProfileSuccess() throws Exception { long projectId = 1L; long organisationId = 2L; when(spendProfileService.markSpendProfileIncomplete(projectId, organisationId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{projectId}/partner-organisation/{organisationId}/spend-profile/incomplete", projectId, organisationId) ) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/project/" + projectId + "/partner-organisation/" + organisationId + "/spend-profile")); verify(spendProfileService).markSpendProfileIncomplete(1L, 2L); }
@Test public void partnerCannotEditAfterSubmission() throws Exception { Long projectId = 1L; Long organisationId = 2L; ProjectResource projectResource = newProjectResource() .withName("projectName1") .withTargetStartDate(LocalDate.of(2018, 3, 1)) .withDuration(3L) .withId(projectId) .build(); OrganisationResource organisationResource = newOrganisationResource().build(); ProjectTeamStatusResource teamStatus = buildProjectTeamStatusResource(); SpendProfileTableResource table = buildSpendProfileTableResource(projectResource); table.setMarkedAsComplete(true); when(projectService.getById(projectResource.getId())).thenReturn(projectResource); when(spendProfileService.getSpendProfileTable(projectResource.getId(), organisationId)).thenReturn(table); when(organisationRestService.getOrganisationById(organisationId)).thenReturn(restSuccess(organisationResource)); PartnerOrganisationResource partnerOrganisationResource = new PartnerOrganisationResource(); partnerOrganisationResource.setOrganisation(organisationId); partnerOrganisationResource.setLeadOrganisation(false); when(statusService.getProjectTeamStatus(projectResource.getId(), Optional.empty())).thenReturn(teamStatus); when(spendProfileService.markSpendProfileIncomplete(projectId, organisationId)).thenReturn(serviceFailure(GENERAL_SPRING_SECURITY_FORBIDDEN_ACTION)); SpendProfileForm expectedForm = new SpendProfileForm(); expectedForm.setTable(table); mockMvc.perform(get("/project/{projectId}/partner-organisation/{organisationId}/spend-profile/edit", projectResource.getId(), organisationId) ) .andExpect(status().is3xxRedirection()) .andExpect(model().attribute("form", expectedForm)) .andExpect(view().name("redirect:/project/1/partner-organisation/2/spend-profile")); verify(spendProfileService).markSpendProfileIncomplete(1L, 2L); } |
ProjectUKCorrespondenceAddressController extends AddressLookupBaseController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_ADDRESS_PAGE')") @GetMapping("/{projectId}/details/project-address/UK") public String viewAddress(@PathVariable("projectId") final Long projectId, Model model, @ModelAttribute(name = FORM_ATTR_NAME, binding = false) ProjectDetailsAddressForm form) { ProjectResource project = projectService.getById(projectId); ProjectDetailsAddressViewModel projectDetailsAddressViewModel = loadDataIntoModel(project); if (project.getAddress() != null) { form.getAddressForm().editAddress(project.getAddress()); } model.addAttribute("model", projectDetailsAddressViewModel); return "project/details-address"; } @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_ADDRESS_PAGE')") @GetMapping("/{projectId}/details/project-address/UK") String viewAddress(@PathVariable("projectId") final Long projectId,
Model model,
@ModelAttribute(name = FORM_ATTR_NAME, binding = false) ProjectDetailsAddressForm form); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_ADDRESS_PAGE')") @PostMapping("/{projectId}/details/project-address/UK") String updateAddress(@PathVariable("projectId") final Long projectId,
Model model,
@Valid @ModelAttribute(FORM_ATTR_NAME) ProjectDetailsAddressForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_ADDRESS_PAGE')") @PostMapping(value = "/{projectId}/details/project-address/UK", params = FORM_ACTION_PARAMETER) String addressFormAction(@PathVariable("projectId") Long projectId,
Model model,
@ModelAttribute(FORM_ATTR_NAME) ProjectDetailsAddressForm form,
BindingResult bindingResult,
ValidationHandler validationHandler); } | @Test public void viewAddress() throws Exception { OrganisationResource organisationResource = newOrganisationResource().build(); AddressResource addressResource = newAddressResource().build(); ApplicationResource applicationResource = newApplicationResource().build(); ProjectResource project = newProjectResource().withApplication(applicationResource).withAddress(addressResource).build(); when(projectService.getById(project.getId())).thenReturn(project); when(projectService.getLeadOrganisation(project.getId())).thenReturn(organisationResource); when(organisationRestService.getOrganisationById(organisationResource.getId())).thenReturn(restSuccess(organisationResource)); MvcResult result = mockMvc.perform(get("/project/{id}/details/project-address/UK", project.getId())). andExpect(status().isOk()). andExpect(view().name("project/details-address")). andExpect(model().hasNoErrors()). andReturn(); Map<String, Object> model = result.getModelAndView().getModel(); ProjectDetailsAddressViewModel viewModel = (ProjectDetailsAddressViewModel) model.get("model"); assertEquals(project.getId(), viewModel.getProjectId()); assertEquals(project.getName(), viewModel.getProjectName()); assertEquals(project.getApplication(), (long) viewModel.getApplicationId()); ProjectDetailsAddressForm form = (ProjectDetailsAddressForm) model.get(FORM_ATTR_NAME); assertTrue(form.getAddressForm().isManualAddressEntry()); assertEquals(form.getAddressForm().getManualAddress().getPostcode(), addressResource.getPostcode()); } |
ProjectUKCorrespondenceAddressController extends AddressLookupBaseController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_ADDRESS_PAGE')") @PostMapping("/{projectId}/details/project-address/UK") public String updateAddress(@PathVariable("projectId") final Long projectId, Model model, @Valid @ModelAttribute(FORM_ATTR_NAME) ProjectDetailsAddressForm form, @SuppressWarnings("unused") BindingResult bindingResult, ValidationHandler validationHandler) { ProjectResource projectResource = projectService.getById(projectId); if (validationHandler.hasErrors()) { return viewCurrentAddressForm(model, form, projectResource); } projectResource.setAddress(form.getAddressForm().getSelectedAddress(this::searchPostcode)); OrganisationResource leadOrganisation = projectService.getLeadOrganisation(projectResource.getId()); ServiceResult<Void> updateResult = projectDetailsService.updateAddress(projectId, projectResource.getAddress()); return updateResult.handleSuccessOrFailure( failure -> { validationHandler.addAnyErrors(failure, asGlobalErrors()); return viewAddress(projectId, model, form); }, success -> redirectToProjectDetails(projectId)); } @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_ADDRESS_PAGE')") @GetMapping("/{projectId}/details/project-address/UK") String viewAddress(@PathVariable("projectId") final Long projectId,
Model model,
@ModelAttribute(name = FORM_ATTR_NAME, binding = false) ProjectDetailsAddressForm form); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_ADDRESS_PAGE')") @PostMapping("/{projectId}/details/project-address/UK") String updateAddress(@PathVariable("projectId") final Long projectId,
Model model,
@Valid @ModelAttribute(FORM_ATTR_NAME) ProjectDetailsAddressForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_ADDRESS_PAGE')") @PostMapping(value = "/{projectId}/details/project-address/UK", params = FORM_ACTION_PARAMETER) String addressFormAction(@PathVariable("projectId") Long projectId,
Model model,
@ModelAttribute(FORM_ATTR_NAME) ProjectDetailsAddressForm form,
BindingResult bindingResult,
ValidationHandler validationHandler); } | @Test public void updateProjectAddressAddNewManually() throws Exception { OrganisationResource leadOrganisation = newOrganisationResource().build(); AddressResource addressResource = newAddressResource(). withAddressLine1("Address Line 1"). withAddressLine2(). withAddressLine3(). withTown("Sheffield"). withCounty(). withPostcode("S1 2LB"). build(); CompetitionResource competitionResource = newCompetitionResource().build(); ApplicationResource applicationResource = newApplicationResource().withCompetition(competitionResource.getId()).build(); ProjectResource project = newProjectResource().withApplication(applicationResource).withAddress(addressResource).build(); when(projectService.getById(project.getId())).thenReturn(project); when(projectService.getLeadOrganisation(project.getId())).thenReturn(leadOrganisation); when(projectDetailsService.updateAddress(project.getId(), addressResource)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{id}/details/project-address/UK", project.getId()). contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("addressForm.addressType", AddressForm.AddressType.MANUAL_ENTRY.name()) .param("addressForm.manualAddress.addressLine1", addressResource.getAddressLine1()) .param("addressForm.manualAddress.town", addressResource.getTown ()) .param("addressForm.manualAddress.postcode", addressResource.getPostcode())) .andExpect(redirectedUrl("/project/" + project.getId() + "/details")) .andExpect(model().attributeDoesNotExist("readOnlyView")) .andReturn(); } |
ProjectInternationalCorrespondenceAddressController extends AddressLookupBaseController { @GetMapping public String viewAddress(@PathVariable("projectId") final Long projectId, Model model, @ModelAttribute(name = FORM_ATTR_NAME, binding = false) ProjectInternationalCorrespondenceAddressForm form) { ProjectResource project = projectService.getById(projectId); if(project.getAddress() != null) { form.populate(project.getAddress()); } model.addAttribute("model", new ProjectInternationalCorrespondenceAddressViewModel(project)); return "project/international-address"; } @GetMapping String viewAddress(@PathVariable("projectId") final Long projectId,
Model model,
@ModelAttribute(name = FORM_ATTR_NAME, binding = false) ProjectInternationalCorrespondenceAddressForm form); @PostMapping String updateAddress(@PathVariable("projectId") final Long projectId,
@Valid @ModelAttribute(FORM_ATTR_NAME) ProjectInternationalCorrespondenceAddressForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
Model model); } | @Test public void viewAddress() throws Exception { when(projectService.getById(projectId)).thenReturn(project); MvcResult result = mockMvc.perform(get(url, project.getId())) .andExpect(status().isOk()) .andExpect(view().name("project/international-address")) .andExpect(model().hasNoErrors()) .andReturn(); Map<String, Object> model = result.getModelAndView().getModel(); ProjectInternationalCorrespondenceAddressViewModel viewModel = (ProjectInternationalCorrespondenceAddressViewModel) model.get("model"); assertEquals(project.getId(), viewModel.getProjectId()); assertEquals(project.getName(), viewModel.getProjectName()); ProjectInternationalCorrespondenceAddressForm form = (ProjectInternationalCorrespondenceAddressForm) model.get("form"); assertEquals(project.getAddress().getCountry(), form.getCountry()); assertEquals(project.getAddress().getAddressLine1(), form.getAddressLine1()); } |
ProjectInternationalCorrespondenceAddressController extends AddressLookupBaseController { @PostMapping public String updateAddress(@PathVariable("projectId") final Long projectId, @Valid @ModelAttribute(FORM_ATTR_NAME) ProjectInternationalCorrespondenceAddressForm form, @SuppressWarnings("unused") BindingResult bindingResult, ValidationHandler validationHandler, Model model) { ProjectResource projectResource = projectService.getById(projectId); Supplier<String> failureView = () -> viewCurrentAddressForm(model, projectResource); return validationHandler.failNowOrSucceedWith(failureView, () ->{ ServiceResult<Void> updateResult = projectDetailsService.updateAddress(projectId, createAddressResource(form)); return updateResult.handleSuccessOrFailure( failure -> { validationHandler.addAnyErrors(failure, asGlobalErrors()); return viewAddress(projectId, model, form); }, success -> redirectToProjectDetails(projectId)); }); } @GetMapping String viewAddress(@PathVariable("projectId") final Long projectId,
Model model,
@ModelAttribute(name = FORM_ATTR_NAME, binding = false) ProjectInternationalCorrespondenceAddressForm form); @PostMapping String updateAddress(@PathVariable("projectId") final Long projectId,
@Valid @ModelAttribute(FORM_ATTR_NAME) ProjectInternationalCorrespondenceAddressForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
Model model); } | @Test public void updateAddress() throws Exception { when(projectService.getById(projectId)).thenReturn(project); when(projectDetailsService.updateAddress(eq(projectId), isA(AddressResource.class))).thenReturn(serviceSuccess()); mockMvc.perform(post(url, project.getId()) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("addressLine1", addressResource.getAddressLine1()) .param("addressLine2", addressResource.getAddressLine2()) .param("town", addressResource.getTown()) .param("country", addressResource.getCountry()) .param("zipCode", addressResource.getPostcode())) .andExpect(redirectedUrl("/project/" + projectId + "/details")) .andReturn(); } |
ProjectFinanceChecksOverviewController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @GetMapping public String viewOverview(Model model, @P("projectId")@PathVariable("projectId") final Long projectId, UserResource loggedInUser) { Long organisationId = projectService.getOrganisationIdFromUser(projectId, loggedInUser); ProjectResource project = projectService.getById(projectId); FinanceCheckOverviewViewModel financeCheckOverviewViewModel = buildFinanceCheckOverviewViewModel(project); model.addAttribute("model", financeCheckOverviewViewModel); model.addAttribute("organisation", organisationId); model.addAttribute("project", project); return "project/finance-checks-overview"; } ProjectFinanceChecksOverviewController(); @Autowired ProjectFinanceChecksOverviewController(PartnerOrganisationRestService partnerOrganisationRestService, FinanceCheckService financeCheckService, ProjectFinanceService financeService, ProjectService projectService, CompetitionRestService competitionRestService); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @GetMapping String viewOverview(Model model, @P("projectId")@PathVariable("projectId") final Long projectId, UserResource loggedInUser); static final String PROJECT_FINANCE_CHECKS_BASE_URL; } | @Test public void viewOverview() throws Exception { CompetitionResource competition = newCompetitionResource().withFundingType(GRANT).withFinanceRowTypes(singletonList(FinanceRowType.FINANCE)).build(); ApplicationResource application = newApplicationResource().withId(123L).withCompetition(competition.getId()).build(); ProjectResource project = newProjectResource().withId(1L).withName("Project1").withApplication(application).withCompetition(competition.getId()).build(); OrganisationResource industrialOrganisation = newOrganisationResource() .withId(2L) .withName("Industrial Org") .withCompaniesHouseNumber("123456789") .withOrganisationTypeName(OrganisationTypeEnum.BUSINESS.name()) .withOrganisationType(OrganisationTypeEnum.BUSINESS.getId()) .build(); FinanceCheckEligibilityResource eligibilityOverview = newFinanceCheckEligibilityResource().build(); PartnerOrganisationResource partnerOrganisationResource = new PartnerOrganisationResource(); partnerOrganisationResource.setOrganisation(industrialOrganisation.getId()); partnerOrganisationResource.setLeadOrganisation(false); when(projectService.getOrganisationIdFromUser(project.getId(), loggedInUser)).thenReturn(industrialOrganisation.getId()); when(projectService.getById(project.getId())).thenReturn(project); when(partnerOrganisationRestService.getProjectPartnerOrganisations(project.getId())).thenReturn(restSuccess(singletonList(partnerOrganisationResource))); when(financeCheckServiceMock.getFinanceCheckEligibilityDetails(project.getId(), industrialOrganisation.getId())).thenReturn(eligibilityOverview); when(competitionRestService.getCompetitionById(competition.getId())).thenReturn(restSuccess(competition)); mockMvc.perform(get(PROJECT_FINANCE_CHECKS_BASE_URL, project.getId())) .andExpect(status().isOk()) .andExpect(view().name("project/finance-checks-overview")) .andReturn(); } |
ProjectFinanceChecksController { private boolean isApproved(final ProjectOrganisationCompositeId compositeId) { Optional<ProjectPartnerStatusResource> organisationStatus = statusService.getProjectTeamStatus(compositeId.getProjectId(), Optional.empty()).getPartnerStatusForOrganisation(compositeId.getOrganisationId()); return COMPLETE.equals(organisationStatus.map(ProjectPartnerStatusResource::getFinanceChecksStatus).orElse(null)); } @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @GetMapping String viewFinanceChecks(Model model, @PathVariable final long projectId,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @GetMapping("/{queryId}/new-response") String viewNewResponse(@PathVariable long projectId,
@PathVariable Long queryId,
Model model,
HttpServletRequest request,
HttpServletResponse response,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @PostMapping("/{queryId}/new-response") String saveResponse(Model model,
@PathVariable final long projectId,
@PathVariable final Long queryId,
@Valid @ModelAttribute(FORM_ATTR) final FinanceChecksQueryResponseForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
UserResource loggedInUser,
HttpServletRequest request,
HttpServletResponse response); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @PostMapping(value = "/{queryId}/new-response", params = "uploadAttachment") String saveNewResponseAttachment(Model model,
@PathVariable("projectId") final long projectId,
@PathVariable Long queryId,
@ModelAttribute(FORM_ATTR) FinanceChecksQueryResponseForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
HttpServletRequest request,
HttpServletResponse response,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @GetMapping("/{queryId}/new-response/attachment/{attachmentId}") @ResponseBody ResponseEntity<ByteArrayResource> downloadResponseAttachment(@PathVariable long projectId,
@PathVariable Long queryId,
@PathVariable long attachmentId,
UserResource loggedInUser,
HttpServletRequest request); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @GetMapping("/attachment/{attachmentId}") @ResponseBody ResponseEntity<ByteArrayResource> downloadAttachment(@PathVariable Long projectId, @PathVariable long attachmentId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @PostMapping(value = "/{queryId}/new-response", params = "removeAttachment") String removeAttachment(@PathVariable long projectId,
@PathVariable Long queryId,
@RequestParam(value = "removeAttachment") final Long attachmentId,
@ModelAttribute(FORM_ATTR) FinanceChecksQueryResponseForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
UserResource loggedInUser,
HttpServletRequest request,
HttpServletResponse response,
Model model); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @GetMapping("/{queryId}/new-response/cancel") String cancelNewForm(@PathVariable long projectId,
@PathVariable Long queryId,
HttpServletRequest request,
HttpServletResponse response,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @GetMapping("/eligibility") String viewExternalEligibilityPage(@PathVariable final long projectId,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @GetMapping("/eligibility/changes") String viewExternalEligibilityChanges(@PathVariable final long projectId,
Model model,
UserResource loggedInUser); } | @Test public void viewFinanceChecksLandingPage() throws Exception { long projectId = 123L; long organisationId = 234L; String projectName = "Name"; ProjectPartnerStatusResource statusResource = newProjectPartnerStatusResource().withProjectDetailsStatus(ProjectActivityStates.COMPLETE) .withFinanceContactStatus(ProjectActivityStates.COMPLETE).withOrganisationId(organisationId).build(); ProjectTeamStatusResource expectedProjectTeamStatusResource = newProjectTeamStatusResource().withPartnerStatuses(Collections.singletonList(statusResource)).build(); ProjectResource project = newProjectResource().withId(projectId).withName(projectName).withApplication(application).withCompetition(competitionId).build(); OrganisationResource partnerOrganisation = newOrganisationResource().withId(organisationId).withOrganisationType(OrganisationTypeEnum.BUSINESS.getId()).build(); ProjectFinanceResource projectFinanceResource = newProjectFinanceResource().build(); when(projectService.getById(projectId)).thenReturn(project); when(organisationRestService.getOrganisationById(organisationId)).thenReturn(restSuccess(partnerOrganisation)); when(statusService.getProjectTeamStatus(projectId, Optional.empty())).thenReturn(expectedProjectTeamStatusResource); when(projectFinanceService.getProjectFinance(projectId, organisationId)).thenReturn(projectFinanceResource); when(financeCheckServiceMock.getQueries(any())).thenReturn(ServiceResult.serviceSuccess(emptyList())); when(projectService.getOrganisationIdFromUser(project.getId(), loggedInUser)).thenReturn(organisationId); MvcResult result = mockMvc.perform(get("/project/123/finance-checks")). andExpect(view().name("project/finance-checks")). andReturn(); ProjectFinanceChecksViewModel model = (ProjectFinanceChecksViewModel) result.getModelAndView().getModel().get("model"); assertEquals(model.getProjectId(), project.getId()); assertEquals(model.getOrganisationId(), partnerOrganisation.getId()); assertEquals(model.getProjectName(), projectName); assertFalse(model.isApproved()); }
@Test public void viewFinanceChecksLandingPageApproved() throws Exception { long projectId = 123L; long organisationId = 234L; String projectName = "Name"; ProjectPartnerStatusResource statusResource = newProjectPartnerStatusResource().withProjectDetailsStatus(ProjectActivityStates.COMPLETE) .withFinanceContactStatus(ProjectActivityStates.COMPLETE).withFinanceChecksStatus(ProjectActivityStates.COMPLETE).withOrganisationId(organisationId).build(); ProjectTeamStatusResource expectedProjectTeamStatusResource = newProjectTeamStatusResource().withPartnerStatuses(Collections.singletonList(statusResource)).build(); ProjectResource project = newProjectResource().withId(projectId).withName(projectName).withApplication(application).withCompetition(competitionId).build(); OrganisationResource partnerOrganisation = newOrganisationResource().withId(organisationId).withOrganisationType(OrganisationTypeEnum.BUSINESS.getId()).build(); ProjectFinanceResource projectFinanceResource = newProjectFinanceResource().build(); when(projectService.getById(projectId)).thenReturn(project); when(organisationRestService.getOrganisationById(organisationId)).thenReturn(restSuccess(partnerOrganisation)); when(statusService.getProjectTeamStatus(projectId, Optional.empty())).thenReturn(expectedProjectTeamStatusResource); when(projectFinanceService.getProjectFinance(projectId, organisationId)).thenReturn(projectFinanceResource); when(financeCheckServiceMock.getQueries(projectFinanceResource.getId())).thenReturn(ServiceResult.serviceSuccess(Collections.singletonList(sampleQuery()))); when(projectService.getOrganisationIdFromUser(project.getId(), loggedInUser)).thenReturn(organisationId); MvcResult result = mockMvc.perform(get("/project/123/finance-checks")). andExpect(view().name("project/finance-checks")). andReturn(); ProjectFinanceChecksViewModel model = (ProjectFinanceChecksViewModel) result.getModelAndView().getModel().get("model"); assertEquals(model.getProjectId(), project.getId()); assertEquals(model.getOrganisationId(), partnerOrganisation.getId()); assertEquals(model.getProjectName(), projectName); assertTrue(model.isApproved()); } |
SectionPermissionRules extends BasePermissionRules { @PermissionRule(value = "UPDATE", description = "no one can update sections yet") public boolean userCanUpdateSection(SectionResource section, UserResource user) { return false; } @PermissionRule(value = "READ", description = "everyone can read sections") boolean userCanReadSection(SectionResource section, UserResource user); @PermissionRule(value = "UPDATE", description = "no one can update sections yet") boolean userCanUpdateSection(SectionResource section, UserResource user); } | @Test public void userCanUpdateSection() { SectionResource section = SectionResourceBuilder.newSectionResource().build(); UserResource user = UserResourceBuilder.newUserResource().build(); assertFalse(rules.userCanUpdateSection(section, user)); } |
ProjectFinanceChecksController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @GetMapping("/eligibility") public String viewExternalEligibilityPage(@PathVariable final long projectId, Model model, UserResource loggedInUser) { ProjectResource project = projectService.getById(projectId); Long organisationId = projectService.getOrganisationIdFromUser(projectId, loggedInUser); ApplicationResource application = applicationService.getById(project.getApplication()); OrganisationResource organisation = organisationRestService.getOrganisationById(organisationId).getSuccess(); OrganisationResource leadOrganisation = projectService.getLeadOrganisation(projectId); boolean isLeadPartnerOrganisation = leadOrganisation.getId().equals(organisation.getId()); return doViewEligibility(application, project, isLeadPartnerOrganisation, organisation, model); } @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @GetMapping String viewFinanceChecks(Model model, @PathVariable final long projectId,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @GetMapping("/{queryId}/new-response") String viewNewResponse(@PathVariable long projectId,
@PathVariable Long queryId,
Model model,
HttpServletRequest request,
HttpServletResponse response,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @PostMapping("/{queryId}/new-response") String saveResponse(Model model,
@PathVariable final long projectId,
@PathVariable final Long queryId,
@Valid @ModelAttribute(FORM_ATTR) final FinanceChecksQueryResponseForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
UserResource loggedInUser,
HttpServletRequest request,
HttpServletResponse response); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @PostMapping(value = "/{queryId}/new-response", params = "uploadAttachment") String saveNewResponseAttachment(Model model,
@PathVariable("projectId") final long projectId,
@PathVariable Long queryId,
@ModelAttribute(FORM_ATTR) FinanceChecksQueryResponseForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
ValidationHandler validationHandler,
HttpServletRequest request,
HttpServletResponse response,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @GetMapping("/{queryId}/new-response/attachment/{attachmentId}") @ResponseBody ResponseEntity<ByteArrayResource> downloadResponseAttachment(@PathVariable long projectId,
@PathVariable Long queryId,
@PathVariable long attachmentId,
UserResource loggedInUser,
HttpServletRequest request); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @GetMapping("/attachment/{attachmentId}") @ResponseBody ResponseEntity<ByteArrayResource> downloadAttachment(@PathVariable Long projectId, @PathVariable long attachmentId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @PostMapping(value = "/{queryId}/new-response", params = "removeAttachment") String removeAttachment(@PathVariable long projectId,
@PathVariable Long queryId,
@RequestParam(value = "removeAttachment") final Long attachmentId,
@ModelAttribute(FORM_ATTR) FinanceChecksQueryResponseForm form,
@SuppressWarnings("unused") BindingResult bindingResult,
UserResource loggedInUser,
HttpServletRequest request,
HttpServletResponse response,
Model model); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @GetMapping("/{queryId}/new-response/cancel") String cancelNewForm(@PathVariable long projectId,
@PathVariable Long queryId,
HttpServletRequest request,
HttpServletResponse response,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @GetMapping("/eligibility") String viewExternalEligibilityPage(@PathVariable final long projectId,
Model model,
UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL')") @GetMapping("/eligibility/changes") String viewExternalEligibilityChanges(@PathVariable final long projectId,
Model model,
UserResource loggedInUser); } | @Test public void viewExternalEligibilityPage() throws Exception { EligibilityResource eligibility = new EligibilityResource(EligibilityState.APPROVED, EligibilityRagStatus.GREEN); setUpViewEligibilityMocking(eligibility); when(projectService.getLeadOrganisation(project.getId())).thenReturn(industrialOrganisation); when(projectService.getOrganisationIdFromUser(project.getId(), loggedInUser)).thenReturn(industrialOrganisation.getId()); when(projectFinanceRestService.getFinanceTotals(project.getId())).thenReturn(restSuccess(emptyList())); when(formPopulator.populateForm(project.getId(), industrialOrganisation.getId())).thenReturn(new YourProjectCostsForm()); MvcResult result = mockMvc.perform(get("/project/" + project.getId() + "/finance-checks/eligibility")). andExpect(status().isOk()). andExpect(view().name("project/financecheck/eligibility")). andExpect(model().attribute("model", instanceOf(FinanceChecksProjectCostsViewModel.class))). andReturn(); assertReadOnlyViewEligibilityDetails(result); } |
ErrorControllerAdvice { protected ModelAndView createErrorModelAndViewWithStatus(Exception e, HttpServletRequest req, List<Object> arguments, HttpStatus status) { return createErrorModelAndViewWithStatusAndView(e, req, arguments, status, "error"); } ErrorControllerAdvice(); ErrorControllerAdvice(Environment env, MessageSource messageSource); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = {AutoSaveElementException.class}) @ResponseBody ObjectNode jsonAutosaveResponseHandler(AutoSaveElementException e); @ResponseStatus(HttpStatus.ALREADY_REPORTED) // 208 @ExceptionHandler(value = InvalidURLException.class) ModelAndView invalidUrlErrorHandler(HttpServletRequest req, InvalidURLException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = IncorrectArgumentTypeException.class) ModelAndView incorrectArgumentTypeErrorHandler(HttpServletRequest req, IncorrectArgumentTypeException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = ForbiddenActionException.class) ModelAndView forbiddenActionException(HttpServletRequest req, ForbiddenActionException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = AccessDeniedException.class) ModelAndView accessDeniedException(HttpServletRequest req, AccessDeniedException e); @ResponseStatus(value= HttpStatus.NOT_FOUND) // 404 @ExceptionHandler(value = ObjectNotFoundException.class) ModelAndView objectNotFoundHandler(HttpServletRequest req, ObjectNotFoundException e); @ResponseStatus(value= HttpStatus.NOT_FOUND) // 404 @ExceptionHandler(value = MethodArgumentTypeMismatchException.class) ModelAndView methodArgumentMismatchHandler(HttpServletRequest req, MethodArgumentTypeMismatchException e); @ResponseStatus(value= HttpStatus.NOT_FOUND) // 404 @ExceptionHandler(value = IncorrectStateForPageException.class) ModelAndView incorrectStateForPageHandler(HttpServletRequest req, IncorrectStateForPageException e); @ResponseStatus(value= HttpStatus.METHOD_NOT_ALLOWED) // 405 @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class) ModelAndView httpRequestMethodNotSupportedHandler(HttpServletRequest req, HttpRequestMethodNotSupportedException e); @ResponseStatus(value = HttpStatus.CONFLICT) // 409 @ExceptionHandler(value = FileAlreadyLinkedToFormInputResponseException.class) ModelAndView fileAlreadyLinkedToFormInputResponse(HttpServletRequest req, FileAlreadyLinkedToFormInputResponseException e); @ResponseStatus(value= HttpStatus.LENGTH_REQUIRED) // 411 @ExceptionHandler(value = LengthRequiredException.class) ModelAndView lengthRequiredErrorHandler(HttpServletRequest req, LengthRequiredException e); @ResponseStatus(value= HttpStatus.PAYLOAD_TOO_LARGE) // 413 @ExceptionHandler(value = {MaxUploadSizeExceededException.class, MultipartException.class, PayloadTooLargeException.class}) ModelAndView payloadTooLargeErrorHandler(HttpServletRequest req, MultipartException e); @ResponseStatus(value= HttpStatus.UNSUPPORTED_MEDIA_TYPE) // 415 @ExceptionHandler(value = UnsupportedMediaTypeException.class) ModelAndView unsupportedMediaTypeErrorHandler(HttpServletRequest req, UnsupportedMediaTypeException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToCreateFileException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToCreateFileException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToCreateFoldersException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToCreateFoldersException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToSendNotificationException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToSendNotificationException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToUpdateFileException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToUpdateFileException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToDeleteFileException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToDeleteFileException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToRenderNotificationTemplateException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToRenderNotificationTemplateException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = {GeneralUnexpectedErrorException.class, Exception.class}) ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e); @ResponseStatus(value= HttpStatus.SERVICE_UNAVAILABLE) //503 @ExceptionHandler(value = {ServiceUnavailableException.class}) ModelAndView defaultErrorHandler(HttpServletRequest req, ServiceUnavailableException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = FileAwaitingVirusScanException.class) ModelAndView fileAwaitingScanning(HttpServletRequest req, FileAwaitingVirusScanException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = FileQuarantinedException.class) ModelAndView fileQuarantined(HttpServletRequest req, FileQuarantinedException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = RegistrationTokenExpiredException.class) ModelAndView registrationTokenExpired(HttpServletRequest req, RegistrationTokenExpiredException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = UnableToAcceptInviteException.class) ModelAndView unableToAcceptInviteException(HttpServletRequest req, UnableToAcceptInviteException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = InviteClosedException.class) ModelAndView inviteClosedException(HttpServletRequest req, InviteClosedException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = InviteExpiredException.class) ModelAndView inviteClosedException(HttpServletRequest req, InviteExpiredException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = InviteAlreadySentException.class) ModelAndView inviteClosedException(HttpServletRequest req, InviteAlreadySentException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = ApplicationAssessorAssignException.class) ModelAndView applicationAssessorAssignException(HttpServletRequest req, ApplicationAssessorAssignException e); @ResponseStatus(HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = AssessmentWithdrawnException.class) ModelAndView assessmentWithdrawnException(HttpServletRequest req, AssessmentWithdrawnException e); @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(value = CompetitionFeedbackCantSendException.class) ModelAndView competitionFeedbackCantSendException(HttpServletRequest req, CompetitionFeedbackCantSendException e); static final String URL_HASH_INVALID_TEMPLATE; } | @Test public void createErrorModelAndViewWithStatus() { Exception exception = new IFSRuntimeException(); List<Object> arguments = asList("arg 1", "arg 2"); httpServletRequest.setRequestURI("/test.html"); when(messageSource.getMessage("error.title.status.500", null, Locale.ENGLISH)).thenReturn("sample title"); when(messageSource.getMessage("org.innovateuk.ifs.commons.exception.IFSRuntimeException", arguments.toArray(), Locale.ENGLISH)).thenReturn("sample error message"); when(env.acceptsProfiles("debug")).thenReturn(true); ModelAndView mav = errorControllerAdvice.createErrorModelAndViewWithStatus(exception, httpServletRequest, arguments, INTERNAL_SERVER_ERROR); ModelMap modelMap = mav.getModelMap(); assertEquals("error", mav.getViewName()); assertEquals("sample title", modelMap.get("title")); assertNull(modelMap.get("messageForUser")); assertEquals("internal_server_error", modelMap.get("errorMessageClass")); assertEquals("http: assertEquals("/", modelMap.get("userDashboardLink")); assertEquals("http: assertEquals(exception, modelMap.get("exception")); assertEquals(ExceptionUtils.getStackTrace(exception), modelMap.get("stacktrace")); assertEquals("sample error message", modelMap.get("message")); } |
ErrorControllerAdvice { protected ModelAndView createErrorModelAndViewWithStatusAndView(Exception e, HttpServletRequest req, List<Object> arguments, HttpStatus status, String viewTemplate) { return createModelAndView(e, req, arguments, status, true, "error.title.status." + status.value(), null, viewTemplate); } ErrorControllerAdvice(); ErrorControllerAdvice(Environment env, MessageSource messageSource); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = {AutoSaveElementException.class}) @ResponseBody ObjectNode jsonAutosaveResponseHandler(AutoSaveElementException e); @ResponseStatus(HttpStatus.ALREADY_REPORTED) // 208 @ExceptionHandler(value = InvalidURLException.class) ModelAndView invalidUrlErrorHandler(HttpServletRequest req, InvalidURLException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = IncorrectArgumentTypeException.class) ModelAndView incorrectArgumentTypeErrorHandler(HttpServletRequest req, IncorrectArgumentTypeException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = ForbiddenActionException.class) ModelAndView forbiddenActionException(HttpServletRequest req, ForbiddenActionException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = AccessDeniedException.class) ModelAndView accessDeniedException(HttpServletRequest req, AccessDeniedException e); @ResponseStatus(value= HttpStatus.NOT_FOUND) // 404 @ExceptionHandler(value = ObjectNotFoundException.class) ModelAndView objectNotFoundHandler(HttpServletRequest req, ObjectNotFoundException e); @ResponseStatus(value= HttpStatus.NOT_FOUND) // 404 @ExceptionHandler(value = MethodArgumentTypeMismatchException.class) ModelAndView methodArgumentMismatchHandler(HttpServletRequest req, MethodArgumentTypeMismatchException e); @ResponseStatus(value= HttpStatus.NOT_FOUND) // 404 @ExceptionHandler(value = IncorrectStateForPageException.class) ModelAndView incorrectStateForPageHandler(HttpServletRequest req, IncorrectStateForPageException e); @ResponseStatus(value= HttpStatus.METHOD_NOT_ALLOWED) // 405 @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class) ModelAndView httpRequestMethodNotSupportedHandler(HttpServletRequest req, HttpRequestMethodNotSupportedException e); @ResponseStatus(value = HttpStatus.CONFLICT) // 409 @ExceptionHandler(value = FileAlreadyLinkedToFormInputResponseException.class) ModelAndView fileAlreadyLinkedToFormInputResponse(HttpServletRequest req, FileAlreadyLinkedToFormInputResponseException e); @ResponseStatus(value= HttpStatus.LENGTH_REQUIRED) // 411 @ExceptionHandler(value = LengthRequiredException.class) ModelAndView lengthRequiredErrorHandler(HttpServletRequest req, LengthRequiredException e); @ResponseStatus(value= HttpStatus.PAYLOAD_TOO_LARGE) // 413 @ExceptionHandler(value = {MaxUploadSizeExceededException.class, MultipartException.class, PayloadTooLargeException.class}) ModelAndView payloadTooLargeErrorHandler(HttpServletRequest req, MultipartException e); @ResponseStatus(value= HttpStatus.UNSUPPORTED_MEDIA_TYPE) // 415 @ExceptionHandler(value = UnsupportedMediaTypeException.class) ModelAndView unsupportedMediaTypeErrorHandler(HttpServletRequest req, UnsupportedMediaTypeException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToCreateFileException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToCreateFileException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToCreateFoldersException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToCreateFoldersException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToSendNotificationException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToSendNotificationException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToUpdateFileException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToUpdateFileException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToDeleteFileException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToDeleteFileException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToRenderNotificationTemplateException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToRenderNotificationTemplateException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = {GeneralUnexpectedErrorException.class, Exception.class}) ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e); @ResponseStatus(value= HttpStatus.SERVICE_UNAVAILABLE) //503 @ExceptionHandler(value = {ServiceUnavailableException.class}) ModelAndView defaultErrorHandler(HttpServletRequest req, ServiceUnavailableException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = FileAwaitingVirusScanException.class) ModelAndView fileAwaitingScanning(HttpServletRequest req, FileAwaitingVirusScanException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = FileQuarantinedException.class) ModelAndView fileQuarantined(HttpServletRequest req, FileQuarantinedException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = RegistrationTokenExpiredException.class) ModelAndView registrationTokenExpired(HttpServletRequest req, RegistrationTokenExpiredException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = UnableToAcceptInviteException.class) ModelAndView unableToAcceptInviteException(HttpServletRequest req, UnableToAcceptInviteException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = InviteClosedException.class) ModelAndView inviteClosedException(HttpServletRequest req, InviteClosedException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = InviteExpiredException.class) ModelAndView inviteClosedException(HttpServletRequest req, InviteExpiredException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = InviteAlreadySentException.class) ModelAndView inviteClosedException(HttpServletRequest req, InviteAlreadySentException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = ApplicationAssessorAssignException.class) ModelAndView applicationAssessorAssignException(HttpServletRequest req, ApplicationAssessorAssignException e); @ResponseStatus(HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = AssessmentWithdrawnException.class) ModelAndView assessmentWithdrawnException(HttpServletRequest req, AssessmentWithdrawnException e); @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(value = CompetitionFeedbackCantSendException.class) ModelAndView competitionFeedbackCantSendException(HttpServletRequest req, CompetitionFeedbackCantSendException e); static final String URL_HASH_INVALID_TEMPLATE; } | @Test public void createErrorModelAndViewWithStatusAndView() { Exception exception = new IFSRuntimeException(); List<Object> arguments = asList("arg 1", "arg 2"); httpServletRequest.setRequestURI("/test.html"); when(messageSource.getMessage("error.title.status.500", null, Locale.ENGLISH)).thenReturn("sample title"); when(messageSource.getMessage("org.innovateuk.ifs.commons.exception.IFSRuntimeException", arguments.toArray(), Locale.ENGLISH)).thenReturn("sample error message"); when(env.acceptsProfiles("debug")).thenReturn(true); ModelAndView mav = errorControllerAdvice.createErrorModelAndViewWithStatusAndView(exception, httpServletRequest, arguments, INTERNAL_SERVER_ERROR, "other-error-view"); ModelMap modelMap = mav.getModelMap(); assertEquals("other-error-view", mav.getViewName()); assertEquals("sample title", modelMap.get("title")); assertNull(modelMap.get("messageForUser")); assertEquals("internal_server_error", modelMap.get("errorMessageClass")); assertEquals("http: assertEquals("/", modelMap.get("userDashboardLink")); assertEquals("http: assertEquals(exception, modelMap.get("exception")); assertEquals(ExceptionUtils.getStackTrace(exception), modelMap.get("stacktrace")); assertEquals("sample error message", modelMap.get("message")); }
@Test public void createErrorModelAndViewWithStatusAndView_withoutDebug() { Exception exception = new IFSRuntimeException(); List<Object> arguments = asList("arg 1", "arg 2"); httpServletRequest.setRequestURI("/test.html"); when(messageSource.getMessage("error.title.status.500", null, Locale.ENGLISH)).thenReturn("sample title"); when(env.acceptsProfiles("debug")).thenReturn(false); ModelAndView mav = errorControllerAdvice.createErrorModelAndViewWithStatusAndView(exception, httpServletRequest, arguments, INTERNAL_SERVER_ERROR, "other-error-view"); ModelMap modelMap = mav.getModelMap(); assertEquals("other-error-view", mav.getViewName()); assertEquals("sample title", modelMap.get("title")); assertNull(modelMap.get("messageForUser")); assertEquals("internal_server_error", modelMap.get("errorMessageClass")); assertEquals("http: assertEquals("/", modelMap.get("userDashboardLink")); assertEquals("http: assertEquals(exception, modelMap.get("exception")); assertNull(modelMap.get("stacktrace")); assertNull(modelMap.get("message")); } |
ErrorControllerAdvice { protected ModelAndView createErrorModelAndViewWithTitleAndMessage(Exception e, HttpServletRequest req, List<Object> arguments, HttpStatus status, String titleKey, String messageKey) { return createModelAndView(e, req, arguments, status, false, titleKey, messageKey, "title-and-message-error"); } ErrorControllerAdvice(); ErrorControllerAdvice(Environment env, MessageSource messageSource); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = {AutoSaveElementException.class}) @ResponseBody ObjectNode jsonAutosaveResponseHandler(AutoSaveElementException e); @ResponseStatus(HttpStatus.ALREADY_REPORTED) // 208 @ExceptionHandler(value = InvalidURLException.class) ModelAndView invalidUrlErrorHandler(HttpServletRequest req, InvalidURLException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = IncorrectArgumentTypeException.class) ModelAndView incorrectArgumentTypeErrorHandler(HttpServletRequest req, IncorrectArgumentTypeException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = ForbiddenActionException.class) ModelAndView forbiddenActionException(HttpServletRequest req, ForbiddenActionException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = AccessDeniedException.class) ModelAndView accessDeniedException(HttpServletRequest req, AccessDeniedException e); @ResponseStatus(value= HttpStatus.NOT_FOUND) // 404 @ExceptionHandler(value = ObjectNotFoundException.class) ModelAndView objectNotFoundHandler(HttpServletRequest req, ObjectNotFoundException e); @ResponseStatus(value= HttpStatus.NOT_FOUND) // 404 @ExceptionHandler(value = MethodArgumentTypeMismatchException.class) ModelAndView methodArgumentMismatchHandler(HttpServletRequest req, MethodArgumentTypeMismatchException e); @ResponseStatus(value= HttpStatus.NOT_FOUND) // 404 @ExceptionHandler(value = IncorrectStateForPageException.class) ModelAndView incorrectStateForPageHandler(HttpServletRequest req, IncorrectStateForPageException e); @ResponseStatus(value= HttpStatus.METHOD_NOT_ALLOWED) // 405 @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class) ModelAndView httpRequestMethodNotSupportedHandler(HttpServletRequest req, HttpRequestMethodNotSupportedException e); @ResponseStatus(value = HttpStatus.CONFLICT) // 409 @ExceptionHandler(value = FileAlreadyLinkedToFormInputResponseException.class) ModelAndView fileAlreadyLinkedToFormInputResponse(HttpServletRequest req, FileAlreadyLinkedToFormInputResponseException e); @ResponseStatus(value= HttpStatus.LENGTH_REQUIRED) // 411 @ExceptionHandler(value = LengthRequiredException.class) ModelAndView lengthRequiredErrorHandler(HttpServletRequest req, LengthRequiredException e); @ResponseStatus(value= HttpStatus.PAYLOAD_TOO_LARGE) // 413 @ExceptionHandler(value = {MaxUploadSizeExceededException.class, MultipartException.class, PayloadTooLargeException.class}) ModelAndView payloadTooLargeErrorHandler(HttpServletRequest req, MultipartException e); @ResponseStatus(value= HttpStatus.UNSUPPORTED_MEDIA_TYPE) // 415 @ExceptionHandler(value = UnsupportedMediaTypeException.class) ModelAndView unsupportedMediaTypeErrorHandler(HttpServletRequest req, UnsupportedMediaTypeException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToCreateFileException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToCreateFileException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToCreateFoldersException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToCreateFoldersException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToSendNotificationException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToSendNotificationException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToUpdateFileException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToUpdateFileException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToDeleteFileException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToDeleteFileException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToRenderNotificationTemplateException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToRenderNotificationTemplateException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = {GeneralUnexpectedErrorException.class, Exception.class}) ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e); @ResponseStatus(value= HttpStatus.SERVICE_UNAVAILABLE) //503 @ExceptionHandler(value = {ServiceUnavailableException.class}) ModelAndView defaultErrorHandler(HttpServletRequest req, ServiceUnavailableException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = FileAwaitingVirusScanException.class) ModelAndView fileAwaitingScanning(HttpServletRequest req, FileAwaitingVirusScanException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = FileQuarantinedException.class) ModelAndView fileQuarantined(HttpServletRequest req, FileQuarantinedException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = RegistrationTokenExpiredException.class) ModelAndView registrationTokenExpired(HttpServletRequest req, RegistrationTokenExpiredException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = UnableToAcceptInviteException.class) ModelAndView unableToAcceptInviteException(HttpServletRequest req, UnableToAcceptInviteException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = InviteClosedException.class) ModelAndView inviteClosedException(HttpServletRequest req, InviteClosedException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = InviteExpiredException.class) ModelAndView inviteClosedException(HttpServletRequest req, InviteExpiredException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = InviteAlreadySentException.class) ModelAndView inviteClosedException(HttpServletRequest req, InviteAlreadySentException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = ApplicationAssessorAssignException.class) ModelAndView applicationAssessorAssignException(HttpServletRequest req, ApplicationAssessorAssignException e); @ResponseStatus(HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = AssessmentWithdrawnException.class) ModelAndView assessmentWithdrawnException(HttpServletRequest req, AssessmentWithdrawnException e); @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(value = CompetitionFeedbackCantSendException.class) ModelAndView competitionFeedbackCantSendException(HttpServletRequest req, CompetitionFeedbackCantSendException e); static final String URL_HASH_INVALID_TEMPLATE; } | @Test public void createErrorModelAndViewWithTitleAndMessage() { Exception exception = new IFSRuntimeException(); List<Object> arguments = asList("arg 1", "arg 2"); httpServletRequest.setRequestURI("/test.html"); when(messageSource.getMessage("sample.title.key", null, Locale.ENGLISH)).thenReturn("sample title"); when(messageSource.getMessage("sample.message.key", arguments.toArray(), Locale.ENGLISH)).thenReturn("sample user message"); when(messageSource.getMessage("org.innovateuk.ifs.commons.exception.IFSRuntimeException", arguments.toArray(), Locale.ENGLISH)).thenReturn("sample error message"); when(env.acceptsProfiles("debug")).thenReturn(true); ModelAndView mav = errorControllerAdvice.createErrorModelAndViewWithTitleAndMessage(exception, httpServletRequest, arguments, INTERNAL_SERVER_ERROR, "sample.title.key", "sample.message.key"); ModelMap modelMap = mav.getModelMap(); assertEquals("title-and-message-error", mav.getViewName()); assertEquals("sample title", modelMap.get("title")); assertEquals("sample user message", modelMap.get("messageForUser")); assertEquals("internal_server_error", modelMap.get("errorMessageClass")); assertNull(modelMap.get("url")); assertEquals("/", modelMap.get("userDashboardLink")); assertEquals("http: assertEquals(exception, modelMap.get("exception")); assertEquals(ExceptionUtils.getStackTrace(exception), modelMap.get("stacktrace")); assertEquals("sample error message", modelMap.get("message")); } |
ErrorControllerAdvice { protected ModelAndView createErrorModelAndViewWithUrlTitleAndMessage(Exception e, HttpServletRequest req, List<Object> arguments, HttpStatus status, String titleKey, String messageKey) { return createModelAndView(e, req, arguments, status, true, titleKey, messageKey, "title-and-message-error"); } ErrorControllerAdvice(); ErrorControllerAdvice(Environment env, MessageSource messageSource); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = {AutoSaveElementException.class}) @ResponseBody ObjectNode jsonAutosaveResponseHandler(AutoSaveElementException e); @ResponseStatus(HttpStatus.ALREADY_REPORTED) // 208 @ExceptionHandler(value = InvalidURLException.class) ModelAndView invalidUrlErrorHandler(HttpServletRequest req, InvalidURLException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = IncorrectArgumentTypeException.class) ModelAndView incorrectArgumentTypeErrorHandler(HttpServletRequest req, IncorrectArgumentTypeException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = ForbiddenActionException.class) ModelAndView forbiddenActionException(HttpServletRequest req, ForbiddenActionException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = AccessDeniedException.class) ModelAndView accessDeniedException(HttpServletRequest req, AccessDeniedException e); @ResponseStatus(value= HttpStatus.NOT_FOUND) // 404 @ExceptionHandler(value = ObjectNotFoundException.class) ModelAndView objectNotFoundHandler(HttpServletRequest req, ObjectNotFoundException e); @ResponseStatus(value= HttpStatus.NOT_FOUND) // 404 @ExceptionHandler(value = MethodArgumentTypeMismatchException.class) ModelAndView methodArgumentMismatchHandler(HttpServletRequest req, MethodArgumentTypeMismatchException e); @ResponseStatus(value= HttpStatus.NOT_FOUND) // 404 @ExceptionHandler(value = IncorrectStateForPageException.class) ModelAndView incorrectStateForPageHandler(HttpServletRequest req, IncorrectStateForPageException e); @ResponseStatus(value= HttpStatus.METHOD_NOT_ALLOWED) // 405 @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class) ModelAndView httpRequestMethodNotSupportedHandler(HttpServletRequest req, HttpRequestMethodNotSupportedException e); @ResponseStatus(value = HttpStatus.CONFLICT) // 409 @ExceptionHandler(value = FileAlreadyLinkedToFormInputResponseException.class) ModelAndView fileAlreadyLinkedToFormInputResponse(HttpServletRequest req, FileAlreadyLinkedToFormInputResponseException e); @ResponseStatus(value= HttpStatus.LENGTH_REQUIRED) // 411 @ExceptionHandler(value = LengthRequiredException.class) ModelAndView lengthRequiredErrorHandler(HttpServletRequest req, LengthRequiredException e); @ResponseStatus(value= HttpStatus.PAYLOAD_TOO_LARGE) // 413 @ExceptionHandler(value = {MaxUploadSizeExceededException.class, MultipartException.class, PayloadTooLargeException.class}) ModelAndView payloadTooLargeErrorHandler(HttpServletRequest req, MultipartException e); @ResponseStatus(value= HttpStatus.UNSUPPORTED_MEDIA_TYPE) // 415 @ExceptionHandler(value = UnsupportedMediaTypeException.class) ModelAndView unsupportedMediaTypeErrorHandler(HttpServletRequest req, UnsupportedMediaTypeException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToCreateFileException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToCreateFileException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToCreateFoldersException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToCreateFoldersException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToSendNotificationException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToSendNotificationException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToUpdateFileException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToUpdateFileException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToDeleteFileException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToDeleteFileException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToRenderNotificationTemplateException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToRenderNotificationTemplateException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = {GeneralUnexpectedErrorException.class, Exception.class}) ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e); @ResponseStatus(value= HttpStatus.SERVICE_UNAVAILABLE) //503 @ExceptionHandler(value = {ServiceUnavailableException.class}) ModelAndView defaultErrorHandler(HttpServletRequest req, ServiceUnavailableException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = FileAwaitingVirusScanException.class) ModelAndView fileAwaitingScanning(HttpServletRequest req, FileAwaitingVirusScanException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = FileQuarantinedException.class) ModelAndView fileQuarantined(HttpServletRequest req, FileQuarantinedException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = RegistrationTokenExpiredException.class) ModelAndView registrationTokenExpired(HttpServletRequest req, RegistrationTokenExpiredException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = UnableToAcceptInviteException.class) ModelAndView unableToAcceptInviteException(HttpServletRequest req, UnableToAcceptInviteException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = InviteClosedException.class) ModelAndView inviteClosedException(HttpServletRequest req, InviteClosedException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = InviteExpiredException.class) ModelAndView inviteClosedException(HttpServletRequest req, InviteExpiredException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = InviteAlreadySentException.class) ModelAndView inviteClosedException(HttpServletRequest req, InviteAlreadySentException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = ApplicationAssessorAssignException.class) ModelAndView applicationAssessorAssignException(HttpServletRequest req, ApplicationAssessorAssignException e); @ResponseStatus(HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = AssessmentWithdrawnException.class) ModelAndView assessmentWithdrawnException(HttpServletRequest req, AssessmentWithdrawnException e); @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(value = CompetitionFeedbackCantSendException.class) ModelAndView competitionFeedbackCantSendException(HttpServletRequest req, CompetitionFeedbackCantSendException e); static final String URL_HASH_INVALID_TEMPLATE; } | @Test public void createErrorModelAndViewWithUrlTitleAndMessage() { Exception exception = new IFSRuntimeException(); List<Object> arguments = asList("arg 1", "arg 2"); httpServletRequest.setRequestURI("/test.html"); when(messageSource.getMessage("sample.title.key", null, Locale.ENGLISH)).thenReturn("sample title"); when(messageSource.getMessage("sample.message.key", arguments.toArray(), Locale.ENGLISH)).thenReturn("sample user message"); when(messageSource.getMessage("org.innovateuk.ifs.commons.exception.IFSRuntimeException", arguments.toArray(), Locale.ENGLISH)).thenReturn("sample error message"); when(env.acceptsProfiles("debug")).thenReturn(true); ModelAndView mav = errorControllerAdvice.createErrorModelAndViewWithUrlTitleAndMessage(exception, httpServletRequest, arguments, INTERNAL_SERVER_ERROR, "sample.title.key", "sample.message.key"); ModelMap modelMap = mav.getModelMap(); assertEquals("title-and-message-error", mav.getViewName()); assertEquals("sample title", modelMap.get("title")); assertEquals("sample user message", modelMap.get("messageForUser")); assertEquals("internal_server_error", modelMap.get("errorMessageClass")); assertEquals("http: assertEquals("/", modelMap.get("userDashboardLink")); assertEquals("http: assertEquals(exception, modelMap.get("exception")); assertEquals(ExceptionUtils.getStackTrace(exception), modelMap.get("stacktrace")); assertEquals("sample error message", modelMap.get("message")); } |
ErrorControllerAdvice { protected ModelAndView createErrorModelAndViewWithUrlTitleMessageAndView(Exception e, HttpServletRequest req, List<Object> arguments, HttpStatus status, String titleKey, String messageKey, String viewTemplate) { return createModelAndView(e, req, arguments, status, true, titleKey, messageKey, viewTemplate); } ErrorControllerAdvice(); ErrorControllerAdvice(Environment env, MessageSource messageSource); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = {AutoSaveElementException.class}) @ResponseBody ObjectNode jsonAutosaveResponseHandler(AutoSaveElementException e); @ResponseStatus(HttpStatus.ALREADY_REPORTED) // 208 @ExceptionHandler(value = InvalidURLException.class) ModelAndView invalidUrlErrorHandler(HttpServletRequest req, InvalidURLException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = IncorrectArgumentTypeException.class) ModelAndView incorrectArgumentTypeErrorHandler(HttpServletRequest req, IncorrectArgumentTypeException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = ForbiddenActionException.class) ModelAndView forbiddenActionException(HttpServletRequest req, ForbiddenActionException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = AccessDeniedException.class) ModelAndView accessDeniedException(HttpServletRequest req, AccessDeniedException e); @ResponseStatus(value= HttpStatus.NOT_FOUND) // 404 @ExceptionHandler(value = ObjectNotFoundException.class) ModelAndView objectNotFoundHandler(HttpServletRequest req, ObjectNotFoundException e); @ResponseStatus(value= HttpStatus.NOT_FOUND) // 404 @ExceptionHandler(value = MethodArgumentTypeMismatchException.class) ModelAndView methodArgumentMismatchHandler(HttpServletRequest req, MethodArgumentTypeMismatchException e); @ResponseStatus(value= HttpStatus.NOT_FOUND) // 404 @ExceptionHandler(value = IncorrectStateForPageException.class) ModelAndView incorrectStateForPageHandler(HttpServletRequest req, IncorrectStateForPageException e); @ResponseStatus(value= HttpStatus.METHOD_NOT_ALLOWED) // 405 @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class) ModelAndView httpRequestMethodNotSupportedHandler(HttpServletRequest req, HttpRequestMethodNotSupportedException e); @ResponseStatus(value = HttpStatus.CONFLICT) // 409 @ExceptionHandler(value = FileAlreadyLinkedToFormInputResponseException.class) ModelAndView fileAlreadyLinkedToFormInputResponse(HttpServletRequest req, FileAlreadyLinkedToFormInputResponseException e); @ResponseStatus(value= HttpStatus.LENGTH_REQUIRED) // 411 @ExceptionHandler(value = LengthRequiredException.class) ModelAndView lengthRequiredErrorHandler(HttpServletRequest req, LengthRequiredException e); @ResponseStatus(value= HttpStatus.PAYLOAD_TOO_LARGE) // 413 @ExceptionHandler(value = {MaxUploadSizeExceededException.class, MultipartException.class, PayloadTooLargeException.class}) ModelAndView payloadTooLargeErrorHandler(HttpServletRequest req, MultipartException e); @ResponseStatus(value= HttpStatus.UNSUPPORTED_MEDIA_TYPE) // 415 @ExceptionHandler(value = UnsupportedMediaTypeException.class) ModelAndView unsupportedMediaTypeErrorHandler(HttpServletRequest req, UnsupportedMediaTypeException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToCreateFileException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToCreateFileException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToCreateFoldersException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToCreateFoldersException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToSendNotificationException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToSendNotificationException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToUpdateFileException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToUpdateFileException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToDeleteFileException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToDeleteFileException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = UnableToRenderNotificationTemplateException.class) ModelAndView defaultErrorHandler(HttpServletRequest req, UnableToRenderNotificationTemplateException e); @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR) //500 @ExceptionHandler(value = {GeneralUnexpectedErrorException.class, Exception.class}) ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e); @ResponseStatus(value= HttpStatus.SERVICE_UNAVAILABLE) //503 @ExceptionHandler(value = {ServiceUnavailableException.class}) ModelAndView defaultErrorHandler(HttpServletRequest req, ServiceUnavailableException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = FileAwaitingVirusScanException.class) ModelAndView fileAwaitingScanning(HttpServletRequest req, FileAwaitingVirusScanException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = FileQuarantinedException.class) ModelAndView fileQuarantined(HttpServletRequest req, FileQuarantinedException e); @ResponseStatus(value= HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = RegistrationTokenExpiredException.class) ModelAndView registrationTokenExpired(HttpServletRequest req, RegistrationTokenExpiredException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = UnableToAcceptInviteException.class) ModelAndView unableToAcceptInviteException(HttpServletRequest req, UnableToAcceptInviteException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = InviteClosedException.class) ModelAndView inviteClosedException(HttpServletRequest req, InviteClosedException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = InviteExpiredException.class) ModelAndView inviteClosedException(HttpServletRequest req, InviteExpiredException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = InviteAlreadySentException.class) ModelAndView inviteClosedException(HttpServletRequest req, InviteAlreadySentException e); @ResponseStatus(HttpStatus.BAD_REQUEST) // 400 @ExceptionHandler(value = ApplicationAssessorAssignException.class) ModelAndView applicationAssessorAssignException(HttpServletRequest req, ApplicationAssessorAssignException e); @ResponseStatus(HttpStatus.FORBIDDEN) // 403 @ExceptionHandler(value = AssessmentWithdrawnException.class) ModelAndView assessmentWithdrawnException(HttpServletRequest req, AssessmentWithdrawnException e); @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(value = CompetitionFeedbackCantSendException.class) ModelAndView competitionFeedbackCantSendException(HttpServletRequest req, CompetitionFeedbackCantSendException e); static final String URL_HASH_INVALID_TEMPLATE; } | @Test public void createErrorModelAndViewWithUrlTitleMessageAndView() { Exception exception = new IFSRuntimeException(); List<Object> arguments = asList("arg 1", "arg 2"); httpServletRequest.setRequestURI("/test.html"); when(messageSource.getMessage("sample.title.key", null, Locale.ENGLISH)).thenReturn("sample title"); when(messageSource.getMessage("sample.message.key", arguments.toArray(), Locale.ENGLISH)).thenReturn("sample user message"); when(messageSource.getMessage("org.innovateuk.ifs.commons.exception.IFSRuntimeException", arguments.toArray(), Locale.ENGLISH)).thenReturn("sample error message"); when(env.acceptsProfiles("debug")).thenReturn(true); ModelAndView mav = errorControllerAdvice.createErrorModelAndViewWithUrlTitleMessageAndView(exception, httpServletRequest, arguments, INTERNAL_SERVER_ERROR, "sample.title.key", "sample.message.key", "other-error-view"); ModelMap modelMap = mav.getModelMap(); assertEquals("other-error-view", mav.getViewName()); assertEquals("sample title", modelMap.get("title")); assertEquals("sample user message", modelMap.get("messageForUser")); assertEquals("internal_server_error", modelMap.get("errorMessageClass")); assertEquals("http: assertEquals("/", modelMap.get("userDashboardLink")); assertEquals("http: assertEquals(exception, modelMap.get("exception")); assertEquals(ExceptionUtils.getStackTrace(exception), modelMap.get("stacktrace")); assertEquals("sample error message", modelMap.get("message")); }
@Test public void shouldNotIncludeGoogleAnalyticsTagIfVariableNotPresent() { Exception exception = new IFSRuntimeException(); List<Object> arguments = asList("arg 1", "arg 2"); ModelAndView mav = errorControllerAdvice.createErrorModelAndViewWithUrlTitleMessageAndView(exception, httpServletRequest, arguments, INTERNAL_SERVER_ERROR, "sample.title.key", "sample.message.key", "other-error-view"); ModelMap modelMap = mav.getModelMap(); assertNull(modelMap.get("GoogleAnalyticsTrackingID")); }
@Test public void shouldIncludeGoogleAnalyticsTagIfVariablePresent() { ReflectionTestUtils.setField(errorControllerAdvice, "googleAnalyticsKeys", "testkey"); Exception exception = new IFSRuntimeException(); List<Object> arguments = asList("arg 1", "arg 2"); ModelAndView mav = errorControllerAdvice.createErrorModelAndViewWithUrlTitleMessageAndView(exception, httpServletRequest, arguments, INTERNAL_SERVER_ERROR, "sample.title.key", "sample.message.key", "other-error-view"); ModelMap modelMap = mav.getModelMap(); assertEquals("testkey", modelMap.get("GoogleAnalyticsTrackingID")); } |
QuestionPermissionRules { @PermissionRule(value = "READ", description = "Logged in users can see all questions") public boolean loggedInUsersCanSeeAllQuestions(QuestionResource questionResource, UserResource user){ return !isAnonymous(user); } @PermissionRule(value = "READ", description = "Logged in users can see all questions") boolean loggedInUsersCanSeeAllQuestions(QuestionResource questionResource, UserResource user); @PermissionRule(value = "READ", description = "Logged in users can see all questions") boolean loggedInUsersCanSeeAllQuestions(Question question, UserResource user); @PermissionRule(value = "UPDATE", description = "No users can currently update questions") boolean noUserCanUpdateAny(QuestionResource questionResource, UserResource user); @PermissionRule(value = "ASSESS", description = "Only questions for the assessors can be assessed") boolean onlyAssessableQuestionsCanBeAssessed(QuestionResource questionResource, UserResource user); } | @Test public void allUsersCanSeeQuestions() { assertTrue(rules.loggedInUsersCanSeeAllQuestions(questionResource, loggedInUser)); assertFalse(rules.loggedInUsersCanSeeAllQuestions(questionResource, anonymousUser())); } |
OrganisationServiceImpl implements OrganisationService { @Override public Long getOrganisationType(long userId, long applicationId) { final ProcessRoleResource processRoleResource = userRestService.findProcessRole(userId, applicationId).getSuccess(); if (processRoleResource != null && processRoleResource.getOrganisationId() != null) { final OrganisationResource organisationResource = organisationRestService.getOrganisationById(processRoleResource.getOrganisationId()).getSuccess(); return organisationResource.getOrganisationType(); } return null; } OrganisationServiceImpl(OrganisationRestService organisationRestService,
UserRestService userRestService, UserService userService); @Override Long getOrganisationType(long userId, long applicationId); @Override Optional<OrganisationResource> getOrganisationForUser(long userId, List<ProcessRoleResource> userApplicationRoles); @Override SortedSet<OrganisationResource> getApplicationOrganisations(List<ProcessRoleResource> userApplicationRoles); @Override SortedSet<OrganisationResource> getAcademicOrganisations(SortedSet<OrganisationResource> organisations); @Override Optional<OrganisationResource> getApplicationLeadOrganisation(List<ProcessRoleResource> userApplicationRoles); OrganisationResource getLeadOrganisation(long applicationId, List<OrganisationResource> applicationOrganisations); } | @Test public void getOrganisationType() { OrganisationResource organisation = newOrganisationResource() .withOrganisationTypeName(BUSINESS.name()) .withOrganisationType(BUSINESS.getId()) .withId(4L) .build(); ProcessRoleResource processRole = newProcessRoleResource() .withUser(user) .withApplication(3L) .withOrganisation(organisation.getId()) .build(); when(userRestService.findProcessRole(user.getId(), processRole.getApplicationId())).thenReturn(restSuccess(processRole)); when(organisationRestService.getOrganisationById(organisation.getId())).thenReturn(restSuccess(organisation)); Long returnedOrganisationType = service.getOrganisationType(user.getId(), processRole.getApplicationId()); verify(userRestService, times(1)).findProcessRole(user.getId(), processRole.getApplicationId()); verify(organisationRestService, times(1)).getOrganisationById(organisation.getId()); verifyNoMoreInteractions(userRestService); verifyNoMoreInteractions(organisationRestService); assertEquals(organisation.getOrganisationType(), returnedOrganisationType); } |
OrganisationServiceImpl implements OrganisationService { @Override public Optional<OrganisationResource> getOrganisationForUser(long userId, List<ProcessRoleResource> userApplicationRoles) { return userApplicationRoles.stream() .filter(uar -> uar.getUser().equals(userId)) .filter(uar -> uar.getOrganisationId() != null) .map(uar -> organisationRestService.getOrganisationById(uar.getOrganisationId()).getOptionalSuccessObject()) .filter(Optional::isPresent) .map(Optional::get) .findFirst(); } OrganisationServiceImpl(OrganisationRestService organisationRestService,
UserRestService userRestService, UserService userService); @Override Long getOrganisationType(long userId, long applicationId); @Override Optional<OrganisationResource> getOrganisationForUser(long userId, List<ProcessRoleResource> userApplicationRoles); @Override SortedSet<OrganisationResource> getApplicationOrganisations(List<ProcessRoleResource> userApplicationRoles); @Override SortedSet<OrganisationResource> getAcademicOrganisations(SortedSet<OrganisationResource> organisations); @Override Optional<OrganisationResource> getApplicationLeadOrganisation(List<ProcessRoleResource> userApplicationRoles); OrganisationResource getLeadOrganisation(long applicationId, List<OrganisationResource> applicationOrganisations); } | @Test public void getOrganisationForUser() { OrganisationResource organisation = newOrganisationResource().withId(4L).build(); ProcessRoleResource roleWithUser = newProcessRoleResource() .withUser(user) .withOrganisation(organisation.getId()) .build(); when(organisationRestService.getOrganisationById(organisation.getId())).thenReturn(restSuccess(organisation)); Optional<OrganisationResource> result = service.getOrganisationForUser(user.getId(), singletonList(roleWithUser)); verify(organisationRestService, times(1)).getOrganisationById(organisation.getId()); verifyNoMoreInteractions(organisationRestService); assertEquals(organisation, result.get()); } |
OrganisationServiceImpl implements OrganisationService { @Override public SortedSet<OrganisationResource> getApplicationOrganisations(List<ProcessRoleResource> userApplicationRoles) { Comparator<OrganisationResource> compareById = Comparator.comparingLong(OrganisationResource::getId); Supplier<SortedSet<OrganisationResource>> supplier = () -> new TreeSet<>(compareById); return userApplicationRoles.stream() .filter(uar -> uar.getRoleName().equals(Role.LEADAPPLICANT.getName()) || uar.getRoleName().equals(Role.COLLABORATOR.getName())) .map(uar -> organisationRestService.getOrganisationById(uar.getOrganisationId()).getSuccess()) .collect(Collectors.toCollection(supplier)); } OrganisationServiceImpl(OrganisationRestService organisationRestService,
UserRestService userRestService, UserService userService); @Override Long getOrganisationType(long userId, long applicationId); @Override Optional<OrganisationResource> getOrganisationForUser(long userId, List<ProcessRoleResource> userApplicationRoles); @Override SortedSet<OrganisationResource> getApplicationOrganisations(List<ProcessRoleResource> userApplicationRoles); @Override SortedSet<OrganisationResource> getAcademicOrganisations(SortedSet<OrganisationResource> organisations); @Override Optional<OrganisationResource> getApplicationLeadOrganisation(List<ProcessRoleResource> userApplicationRoles); OrganisationResource getLeadOrganisation(long applicationId, List<OrganisationResource> applicationOrganisations); } | @Test public void getApplicationOrganisations() { OrganisationResource leadOrganisation = newOrganisationResource().withId(3L).build(); OrganisationResource collaborator1 = newOrganisationResource().withId(18L).build(); OrganisationResource collaborator2 = newOrganisationResource().withId(2L).build(); when(organisationRestService.getOrganisationById(leadOrganisation.getId())).thenReturn(restSuccess(leadOrganisation)); when(organisationRestService.getOrganisationById(collaborator1.getId())).thenReturn(restSuccess(collaborator1)); when(organisationRestService.getOrganisationById(collaborator2.getId())).thenReturn(restSuccess(collaborator2)); List<ProcessRoleResource> processRoleResources = newProcessRoleResource() .withOrganisation(leadOrganisation.getId(), collaborator1.getId(), collaborator2.getId()) .withRole(LEADAPPLICANT, COLLABORATOR, COLLABORATOR, ASSESSOR) .build(3); SortedSet<OrganisationResource> sortedProcessRoles = service.getApplicationOrganisations(processRoleResources); verify(organisationRestService, times(1)).getOrganisationById(leadOrganisation.getId()); verify(organisationRestService, times(1)).getOrganisationById(collaborator1.getId()); verify(organisationRestService, times(1)).getOrganisationById(collaborator2.getId()); verifyNoMoreInteractions(organisationRestService); assertEquals(sortedProcessRoles.first(), collaborator2); assertEquals(sortedProcessRoles.last(), collaborator1); } |
OrganisationServiceImpl implements OrganisationService { @Override public SortedSet<OrganisationResource> getAcademicOrganisations(SortedSet<OrganisationResource> organisations) { Comparator<OrganisationResource> compareById = Comparator.comparingLong(OrganisationResource::getId); Supplier<TreeSet<OrganisationResource>> supplier = () -> new TreeSet<>(compareById); ArrayList<OrganisationResource> organisationList = new ArrayList<>(organisations); return organisationList.stream() .filter(o -> OrganisationTypeEnum.RESEARCH.getId() == o.getOrganisationType()) .collect(Collectors.toCollection(supplier)); } OrganisationServiceImpl(OrganisationRestService organisationRestService,
UserRestService userRestService, UserService userService); @Override Long getOrganisationType(long userId, long applicationId); @Override Optional<OrganisationResource> getOrganisationForUser(long userId, List<ProcessRoleResource> userApplicationRoles); @Override SortedSet<OrganisationResource> getApplicationOrganisations(List<ProcessRoleResource> userApplicationRoles); @Override SortedSet<OrganisationResource> getAcademicOrganisations(SortedSet<OrganisationResource> organisations); @Override Optional<OrganisationResource> getApplicationLeadOrganisation(List<ProcessRoleResource> userApplicationRoles); OrganisationResource getLeadOrganisation(long applicationId, List<OrganisationResource> applicationOrganisations); } | @Test public void getAcademicOrganisations() { OrganisationResource academicOrganisation = newOrganisationResource() .withOrganisationTypeName(RESEARCH.name()) .withOrganisationType(RESEARCH.getId()) .withId(12L) .build(); OrganisationResource leadOrganisation = newOrganisationResource() .withOrganisationTypeName(BUSINESS.name()) .withOrganisationType(BUSINESS.getId()) .withId(3L) .build(); SortedSet<OrganisationResource> sortedAcademicOrganisation = new TreeSet<>(Comparator.comparingLong(OrganisationResource::getId)); sortedAcademicOrganisation.add(academicOrganisation); sortedAcademicOrganisation.add(leadOrganisation); SortedSet<OrganisationResource> result = service.getAcademicOrganisations(sortedAcademicOrganisation); assertEquals(academicOrganisation, result.first()); assertEquals(1, result.size()); } |
OrganisationServiceImpl implements OrganisationService { @Override public Optional<OrganisationResource> getApplicationLeadOrganisation(List<ProcessRoleResource> userApplicationRoles) { return userApplicationRoles.stream() .filter(uar -> uar.getRoleName().equals(Role.LEADAPPLICANT.getName())) .map(uar -> organisationRestService.getOrganisationById(uar.getOrganisationId()).getSuccess()) .findFirst(); } OrganisationServiceImpl(OrganisationRestService organisationRestService,
UserRestService userRestService, UserService userService); @Override Long getOrganisationType(long userId, long applicationId); @Override Optional<OrganisationResource> getOrganisationForUser(long userId, List<ProcessRoleResource> userApplicationRoles); @Override SortedSet<OrganisationResource> getApplicationOrganisations(List<ProcessRoleResource> userApplicationRoles); @Override SortedSet<OrganisationResource> getAcademicOrganisations(SortedSet<OrganisationResource> organisations); @Override Optional<OrganisationResource> getApplicationLeadOrganisation(List<ProcessRoleResource> userApplicationRoles); OrganisationResource getLeadOrganisation(long applicationId, List<OrganisationResource> applicationOrganisations); } | @Test public void getApplicationLeadOrganisation() { OrganisationResource leadOrganisation = newOrganisationResource().withId(3L).build(); OrganisationResource collaborator = newOrganisationResource().withId(18L).build(); when(organisationRestService.getOrganisationById(leadOrganisation.getId())).thenReturn(restSuccess(leadOrganisation)); when(organisationRestService.getOrganisationById(collaborator.getId())).thenReturn(restSuccess(collaborator)); List<ProcessRoleResource> processRoleResources = newProcessRoleResource() .withOrganisation(leadOrganisation.getId(), collaborator.getId()) .withRole(LEADAPPLICANT, COLLABORATOR) .build(2); Optional<OrganisationResource> result = service.getApplicationLeadOrganisation(processRoleResources); verify(organisationRestService, times(1)).getOrganisationById(leadOrganisation.getId()); verifyNoMoreInteractions(organisationRestService); assertEquals(leadOrganisation, result.get()); } |
OrganisationServiceImpl implements OrganisationService { public OrganisationResource getLeadOrganisation(long applicationId, List<OrganisationResource> applicationOrganisations) { ProcessRoleResource leadApplicantUser = userService.getLeadApplicantProcessRole(applicationId); return applicationOrganisations.stream().filter(org -> org.getId().equals(leadApplicantUser.getOrganisationId())).findFirst().orElse(null); } OrganisationServiceImpl(OrganisationRestService organisationRestService,
UserRestService userRestService, UserService userService); @Override Long getOrganisationType(long userId, long applicationId); @Override Optional<OrganisationResource> getOrganisationForUser(long userId, List<ProcessRoleResource> userApplicationRoles); @Override SortedSet<OrganisationResource> getApplicationOrganisations(List<ProcessRoleResource> userApplicationRoles); @Override SortedSet<OrganisationResource> getAcademicOrganisations(SortedSet<OrganisationResource> organisations); @Override Optional<OrganisationResource> getApplicationLeadOrganisation(List<ProcessRoleResource> userApplicationRoles); OrganisationResource getLeadOrganisation(long applicationId, List<OrganisationResource> applicationOrganisations); } | @Test public void getLeadOrganisation() { OrganisationResource leadOrganisation = newOrganisationResource().withId(3L).build(); ProcessRoleResource processRole = newProcessRoleResource() .withApplication(123L) .withUser(user) .withRole(LEADAPPLICANT) .withOrganisation(leadOrganisation.getId()) .build(); when(userService.getLeadApplicantProcessRole(processRole.getApplicationId())).thenReturn(processRole); when(organisationRestService.getOrganisationById(leadOrganisation.getId())).thenReturn(restSuccess(leadOrganisation)); OrganisationResource result = service.getLeadOrganisation(processRole.getApplicationId(), singletonList(leadOrganisation)); verify(userService, times(1)).getLeadApplicantProcessRole(processRole.getApplicationId()); verifyNoMoreInteractions(userService); assertEquals(leadOrganisation, result); } |
UserServiceImpl implements UserService { @Override public void resendEmailVerificationNotification(String email) { try { userRestService.resendEmailVerificationNotification(email).getSuccess(); } catch (ObjectNotFoundException e) { LOG.debug(format("Purposely ignoring ObjectNotFoundException for email address: [%s] when resending email verification notification.", email), e); } } @Override Boolean isLeadApplicant(Long userId, ApplicationResource application); @Override ProcessRoleResource getLeadApplicantProcessRole(Long applicationId); @Override List<ProcessRoleResource> getOrganisationProcessRoles(ApplicationResource application, Long organisation); @Override List<ProcessRoleResource> getLeadPartnerOrganisationProcessRoles(ApplicationResource application); @Override ServiceResult<UserResource> updateDetails(Long id, String email, String firstName, String lastName, String title, String phoneNumber, boolean allowMarketingEmails); @Override Long getUserOrganisationId(Long userId, Long applicationId); @Override void resendEmailVerificationNotification(String email); @Override Boolean userHasApplicationForCompetition(Long userId, Long competitionId); @Override void sendPasswordResetNotification(String email); @Override Optional<UserResource> findUserByEmail(String email); @Override boolean existsAndHasRole(Long userId, Role role); } | @Test public void resendEmailVerificationNotification() { service.resendEmailVerificationNotification(EMAIL_THAT_EXISTS_FOR_USER); verify(userRestService, only()).resendEmailVerificationNotification(EMAIL_THAT_EXISTS_FOR_USER); }
@Test(expected = Test.None.class ) public void resendEmailVerificationNotification_notExists() { final String email = "[email protected]"; service.resendEmailVerificationNotification(email); verify(userRestService, only()).resendEmailVerificationNotification(email); }
@Test(expected = GeneralUnexpectedErrorException.class) public void resendEmailVerificationNotification_otherError() { service.resendEmailVerificationNotification(EMAIL_THAT_EXISTS_FOR_USER_BUT_CAUSES_OTHER_ERROR); verify(userRestService, only()).resendEmailVerificationNotification(EMAIL_THAT_EXISTS_FOR_USER_BUT_CAUSES_OTHER_ERROR); } |
UserServiceImpl implements UserService { @Override public Boolean userHasApplicationForCompetition(Long userId, Long competitionId) { return userRestService.userHasApplicationForCompetition(userId, competitionId).getSuccess(); } @Override Boolean isLeadApplicant(Long userId, ApplicationResource application); @Override ProcessRoleResource getLeadApplicantProcessRole(Long applicationId); @Override List<ProcessRoleResource> getOrganisationProcessRoles(ApplicationResource application, Long organisation); @Override List<ProcessRoleResource> getLeadPartnerOrganisationProcessRoles(ApplicationResource application); @Override ServiceResult<UserResource> updateDetails(Long id, String email, String firstName, String lastName, String title, String phoneNumber, boolean allowMarketingEmails); @Override Long getUserOrganisationId(Long userId, Long applicationId); @Override void resendEmailVerificationNotification(String email); @Override Boolean userHasApplicationForCompetition(Long userId, Long competitionId); @Override void sendPasswordResetNotification(String email); @Override Optional<UserResource> findUserByEmail(String email); @Override boolean existsAndHasRole(Long userId, Role role); } | @Test public void userHasApplicationForCompetition() { Long userId = 1L; Long competitionId = 2L; Boolean expected = true; when(userRestService.userHasApplicationForCompetition(userId, competitionId)).thenReturn(restSuccess(expected)); Boolean response = service.userHasApplicationForCompetition(userId, competitionId); assertEquals(expected, response); verify(userRestService, only()).userHasApplicationForCompetition(userId, competitionId); } |
QuestionPermissionRules { @PermissionRule(value = "UPDATE", description = "No users can currently update questions") public boolean noUserCanUpdateAny(QuestionResource questionResource, UserResource user){ return false; } @PermissionRule(value = "READ", description = "Logged in users can see all questions") boolean loggedInUsersCanSeeAllQuestions(QuestionResource questionResource, UserResource user); @PermissionRule(value = "READ", description = "Logged in users can see all questions") boolean loggedInUsersCanSeeAllQuestions(Question question, UserResource user); @PermissionRule(value = "UPDATE", description = "No users can currently update questions") boolean noUserCanUpdateAny(QuestionResource questionResource, UserResource user); @PermissionRule(value = "ASSESS", description = "Only questions for the assessors can be assessed") boolean onlyAssessableQuestionsCanBeAssessed(QuestionResource questionResource, UserResource user); } | @Test public void noUserCanUpdateAny() { assertFalse(rules.noUserCanUpdateAny(questionResource, loggedInUser)); } |
UserServiceImpl implements UserService { @Override public boolean existsAndHasRole(Long userId, Role role) { RestResult<UserResource> result = userRestService.retrieveUserById(userId); if (result.isFailure()) { return false; } UserResource user = result.getSuccess(); return user != null && user.hasRole(role); } @Override Boolean isLeadApplicant(Long userId, ApplicationResource application); @Override ProcessRoleResource getLeadApplicantProcessRole(Long applicationId); @Override List<ProcessRoleResource> getOrganisationProcessRoles(ApplicationResource application, Long organisation); @Override List<ProcessRoleResource> getLeadPartnerOrganisationProcessRoles(ApplicationResource application); @Override ServiceResult<UserResource> updateDetails(Long id, String email, String firstName, String lastName, String title, String phoneNumber, boolean allowMarketingEmails); @Override Long getUserOrganisationId(Long userId, Long applicationId); @Override void resendEmailVerificationNotification(String email); @Override Boolean userHasApplicationForCompetition(Long userId, Long competitionId); @Override void sendPasswordResetNotification(String email); @Override Optional<UserResource> findUserByEmail(String email); @Override boolean existsAndHasRole(Long userId, Role role); } | @Test public void existsAndHasRole() { Long userId = 1L; roleResource = COMP_ADMIN; UserResource userResource = newUserResource() .withId(userId) .withRolesGlobal(singletonList(roleResource)) .build(); when(userRestService.retrieveUserById(userId)).thenReturn(restSuccess(userResource)); assertTrue(service.existsAndHasRole(userId, COMP_ADMIN)); }
@Test public void existsAndHasRole_wrongRole() { Long userId = 1L; roleResource = Role.FINANCE_CONTACT; UserResource userResource = newUserResource() .withId(userId) .withRolesGlobal(singletonList(roleResource)) .build(); when(userRestService.retrieveUserById(userId)).thenReturn(restSuccess(userResource)); assertFalse(service.existsAndHasRole(userId, COMP_ADMIN)); }
@Test public void existsAndHasRole_userNotFound() { Long userId = 1L; Error error = CommonErrors.notFoundError(UserResource.class, userId); when(userRestService.retrieveUserById(userId)).thenReturn(restFailure(error)); assertFalse(service.existsAndHasRole(userId, COMP_ADMIN)); } |
UserServiceImpl implements UserService { @Override public Boolean isLeadApplicant(Long userId, ApplicationResource application) { List<ProcessRoleResource> userApplicationRoles = userRestService.findProcessRole(application.getId()).getSuccess(); return userApplicationRoles.stream().anyMatch(uar -> uar.getRoleName() .equals(Role.LEADAPPLICANT.getName()) && uar.getUser().equals(userId)); } @Override Boolean isLeadApplicant(Long userId, ApplicationResource application); @Override ProcessRoleResource getLeadApplicantProcessRole(Long applicationId); @Override List<ProcessRoleResource> getOrganisationProcessRoles(ApplicationResource application, Long organisation); @Override List<ProcessRoleResource> getLeadPartnerOrganisationProcessRoles(ApplicationResource application); @Override ServiceResult<UserResource> updateDetails(Long id, String email, String firstName, String lastName, String title, String phoneNumber, boolean allowMarketingEmails); @Override Long getUserOrganisationId(Long userId, Long applicationId); @Override void resendEmailVerificationNotification(String email); @Override Boolean userHasApplicationForCompetition(Long userId, Long competitionId); @Override void sendPasswordResetNotification(String email); @Override Optional<UserResource> findUserByEmail(String email); @Override boolean existsAndHasRole(Long userId, Role role); } | @Test public void isLeadApplicant() { when(userRestService.findProcessRole(applicationId)).thenReturn(restSuccess(processRoles)); assertTrue(service.isLeadApplicant(leadUser.getId(), application)); } |
UserServiceImpl implements UserService { @Override public ProcessRoleResource getLeadApplicantProcessRole(Long applicationId) { List<ProcessRoleResource> userApplicationRoles = userRestService.findProcessRole(applicationId).getSuccess(); return userApplicationRoles.stream().filter(uar -> uar.getRoleName().equals(Role.LEADAPPLICANT.getName())).findFirst().orElseThrow(() -> new ObjectNotFoundException("Lead applicant not found for application " + applicationId, emptyList())); } @Override Boolean isLeadApplicant(Long userId, ApplicationResource application); @Override ProcessRoleResource getLeadApplicantProcessRole(Long applicationId); @Override List<ProcessRoleResource> getOrganisationProcessRoles(ApplicationResource application, Long organisation); @Override List<ProcessRoleResource> getLeadPartnerOrganisationProcessRoles(ApplicationResource application); @Override ServiceResult<UserResource> updateDetails(Long id, String email, String firstName, String lastName, String title, String phoneNumber, boolean allowMarketingEmails); @Override Long getUserOrganisationId(Long userId, Long applicationId); @Override void resendEmailVerificationNotification(String email); @Override Boolean userHasApplicationForCompetition(Long userId, Long competitionId); @Override void sendPasswordResetNotification(String email); @Override Optional<UserResource> findUserByEmail(String email); @Override boolean existsAndHasRole(Long userId, Role role); } | @Test public void getLeadApplicantProcessRole() { when(userRestService.findProcessRole(applicationId)).thenReturn(restSuccess(processRoles)); assertEquals(processRoles.get(0), service.getLeadApplicantProcessRole(applicationId)); } |
UserServiceImpl implements UserService { @Override public List<ProcessRoleResource> getOrganisationProcessRoles(ApplicationResource application, Long organisation) { List<ProcessRoleResource> userApplicationRoles = userRestService.findProcessRole(application.getId()).getSuccess(); return userApplicationRoles.stream() .filter(prr -> organisation.equals(prr.getOrganisationId())) .collect(Collectors.toList()); } @Override Boolean isLeadApplicant(Long userId, ApplicationResource application); @Override ProcessRoleResource getLeadApplicantProcessRole(Long applicationId); @Override List<ProcessRoleResource> getOrganisationProcessRoles(ApplicationResource application, Long organisation); @Override List<ProcessRoleResource> getLeadPartnerOrganisationProcessRoles(ApplicationResource application); @Override ServiceResult<UserResource> updateDetails(Long id, String email, String firstName, String lastName, String title, String phoneNumber, boolean allowMarketingEmails); @Override Long getUserOrganisationId(Long userId, Long applicationId); @Override void resendEmailVerificationNotification(String email); @Override Boolean userHasApplicationForCompetition(Long userId, Long competitionId); @Override void sendPasswordResetNotification(String email); @Override Optional<UserResource> findUserByEmail(String email); @Override boolean existsAndHasRole(Long userId, Role role); } | @Test public void getOrganisationProcessRoles() { when(userRestService.findProcessRole(applicationId)).thenReturn(restSuccess(processRoles)); List<ProcessRoleResource> result = service.getOrganisationProcessRoles(application, 13L); verify(userRestService, times(1)).findProcessRole(applicationId); verifyNoMoreInteractions(userRestService); assertEquals(singletonList(processRoles.get(0)), result); } |
UserServiceImpl implements UserService { @Override public List<ProcessRoleResource> getLeadPartnerOrganisationProcessRoles(ApplicationResource application) { ProcessRoleResource leadProcessRole = getLeadApplicantProcessRole(application.getId()); if (leadProcessRole == null) { return new ArrayList<>(); } return userRestService.findProcessRole(application.getId()).getSuccess().stream() .filter(pr -> leadProcessRole.getOrganisationId().equals(pr.getOrganisationId())) .collect(Collectors.toList()); } @Override Boolean isLeadApplicant(Long userId, ApplicationResource application); @Override ProcessRoleResource getLeadApplicantProcessRole(Long applicationId); @Override List<ProcessRoleResource> getOrganisationProcessRoles(ApplicationResource application, Long organisation); @Override List<ProcessRoleResource> getLeadPartnerOrganisationProcessRoles(ApplicationResource application); @Override ServiceResult<UserResource> updateDetails(Long id, String email, String firstName, String lastName, String title, String phoneNumber, boolean allowMarketingEmails); @Override Long getUserOrganisationId(Long userId, Long applicationId); @Override void resendEmailVerificationNotification(String email); @Override Boolean userHasApplicationForCompetition(Long userId, Long competitionId); @Override void sendPasswordResetNotification(String email); @Override Optional<UserResource> findUserByEmail(String email); @Override boolean existsAndHasRole(Long userId, Role role); } | @Test public void getLeadPartnerOrganisationProcessRoles() { when(userRestService.findProcessRole(applicationId)).thenReturn(restSuccess(processRoles)); List<ProcessRoleResource> result = service.getLeadPartnerOrganisationProcessRoles(application); verify(userRestService, times(2)).findProcessRole(applicationId); verifyNoMoreInteractions(userRestService); assertEquals(singletonList(processRoles.get(0)), result); } |
UserServiceImpl implements UserService { @Override public Long getUserOrganisationId(Long userId, Long applicationId) { ProcessRoleResource userApplicationRole = userRestService.findProcessRole(userId, applicationId).getSuccess(); return userApplicationRole.getOrganisationId(); } @Override Boolean isLeadApplicant(Long userId, ApplicationResource application); @Override ProcessRoleResource getLeadApplicantProcessRole(Long applicationId); @Override List<ProcessRoleResource> getOrganisationProcessRoles(ApplicationResource application, Long organisation); @Override List<ProcessRoleResource> getLeadPartnerOrganisationProcessRoles(ApplicationResource application); @Override ServiceResult<UserResource> updateDetails(Long id, String email, String firstName, String lastName, String title, String phoneNumber, boolean allowMarketingEmails); @Override Long getUserOrganisationId(Long userId, Long applicationId); @Override void resendEmailVerificationNotification(String email); @Override Boolean userHasApplicationForCompetition(Long userId, Long competitionId); @Override void sendPasswordResetNotification(String email); @Override Optional<UserResource> findUserByEmail(String email); @Override boolean existsAndHasRole(Long userId, Role role); } | @Test public void getUserOrganisationId() { when(userRestService.findProcessRole(leadUser.getId(), applicationId)).thenReturn(restSuccess(processRoles.get(0))); Long result = service.getUserOrganisationId(leadUser.getId(), applicationId); verify(userRestService, times(1)).findProcessRole(leadUser.getId(), applicationId); verifyNoMoreInteractions(userRestService); assertEquals(processRoles.get(0).getOrganisationId(), result); } |
UserServiceImpl implements UserService { @Override public ServiceResult<UserResource> updateDetails(Long id, String email, String firstName, String lastName, String title, String phoneNumber, boolean allowMarketingEmails) { return userRestService.updateDetails(id, email, firstName, lastName, title, phoneNumber, allowMarketingEmails).toServiceResult(); } @Override Boolean isLeadApplicant(Long userId, ApplicationResource application); @Override ProcessRoleResource getLeadApplicantProcessRole(Long applicationId); @Override List<ProcessRoleResource> getOrganisationProcessRoles(ApplicationResource application, Long organisation); @Override List<ProcessRoleResource> getLeadPartnerOrganisationProcessRoles(ApplicationResource application); @Override ServiceResult<UserResource> updateDetails(Long id, String email, String firstName, String lastName, String title, String phoneNumber, boolean allowMarketingEmails); @Override Long getUserOrganisationId(Long userId, Long applicationId); @Override void resendEmailVerificationNotification(String email); @Override Boolean userHasApplicationForCompetition(Long userId, Long competitionId); @Override void sendPasswordResetNotification(String email); @Override Optional<UserResource> findUserByEmail(String email); @Override boolean existsAndHasRole(Long userId, Role role); } | @Test public void updateDetails() { when(userRestService.updateDetails(anyLong(), anyString(), anyString(), anyString(), anyString(), anyString(), anyBoolean())).thenReturn(restSuccess(new UserResource())); ServiceResult<UserResource> result = service.updateDetails(anyLong(), anyString(), anyString(), anyString(), anyString(), anyString(), anyBoolean()); verify(userRestService, times(1)).updateDetails(anyLong(), anyString(), anyString(), anyString(), anyString(), anyString(), anyBoolean()); verifyNoMoreInteractions(userRestService); assertTrue(result.isSuccess()); } |
UserServiceImpl implements UserService { @Override public void sendPasswordResetNotification(String email) { userRestService.sendPasswordResetNotification(email); } @Override Boolean isLeadApplicant(Long userId, ApplicationResource application); @Override ProcessRoleResource getLeadApplicantProcessRole(Long applicationId); @Override List<ProcessRoleResource> getOrganisationProcessRoles(ApplicationResource application, Long organisation); @Override List<ProcessRoleResource> getLeadPartnerOrganisationProcessRoles(ApplicationResource application); @Override ServiceResult<UserResource> updateDetails(Long id, String email, String firstName, String lastName, String title, String phoneNumber, boolean allowMarketingEmails); @Override Long getUserOrganisationId(Long userId, Long applicationId); @Override void resendEmailVerificationNotification(String email); @Override Boolean userHasApplicationForCompetition(Long userId, Long competitionId); @Override void sendPasswordResetNotification(String email); @Override Optional<UserResource> findUserByEmail(String email); @Override boolean existsAndHasRole(Long userId, Role role); } | @Test public void sendPasswordResetNotification() { String email = "[email protected]"; service.sendPasswordResetNotification(email); verify(userRestService).sendPasswordResetNotification(email); } |
SectionController { @GetMapping("/get-next-section/{sectionId}") public RestResult<SectionResource> getNextSection(@PathVariable("sectionId") final Long sectionId) { return sectionService.getNextSection(sectionId).toGetResponse(); } @GetMapping("/{sectionId}") RestResult<SectionResource> getById(@PathVariable("sectionId") final Long sectionId); @GetMapping("/get-child-sections/{parentId}") RestResult<List<SectionResource>> getChildSectionsByParentId(@PathVariable long parentId); @GetMapping("/get-next-section/{sectionId}") RestResult<SectionResource> getNextSection(@PathVariable("sectionId") final Long sectionId); @GetMapping("/get-previous-section/{sectionId}") RestResult<SectionResource> getPreviousSection(@PathVariable("sectionId") final Long sectionId); @GetMapping("/get-section-by-question-id/{questionId}") RestResult<SectionResource> getSectionByQuestionId(@PathVariable("questionId") final Long questionId); @GetMapping("/get-questions-for-section-and-subsections/{sectionId}") RestResult<Set<Long>> getQuestionsForSectionAndSubsections(@PathVariable("sectionId") final Long sectionId); @GetMapping("/get-sections-by-competition-id-and-type/{competitionId}/{type}") RestResult<List<SectionResource>> getSectionsByCompetitionIdAndType(@PathVariable("competitionId") final Long competitionId, @PathVariable("type") SectionType type); @GetMapping("/get-by-competition/{competitionId}") RestResult<List<SectionResource>> getSectionsByCompetitionId(@PathVariable("competitionId") final Long competitionId); @GetMapping("/get-by-competition-id-visible-for-assessment/{competitionId}") RestResult<List<SectionResource>> getByCompetitionIdVisibleForAssessment(@PathVariable("competitionId") long competitionId); } | @Test public void getNextSectionTest() throws Exception { Section section = newSection().withCompetitionAndPriority(newCompetition().build(), 1).build(); SectionResource nextSection = newSectionResource().build(); when(sectionService.getNextSection(section.getId())).thenReturn(serviceSuccess(nextSection)); mockMvc.perform(get("/section/get-next-section/" + section.getId()) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(objectMapper.writeValueAsString(nextSection))); } |
UserServiceImpl implements UserService { @Override public Optional<UserResource> findUserByEmail(String email) { return userRestService.findUserByEmail(email).getOptionalSuccessObject(); } @Override Boolean isLeadApplicant(Long userId, ApplicationResource application); @Override ProcessRoleResource getLeadApplicantProcessRole(Long applicationId); @Override List<ProcessRoleResource> getOrganisationProcessRoles(ApplicationResource application, Long organisation); @Override List<ProcessRoleResource> getLeadPartnerOrganisationProcessRoles(ApplicationResource application); @Override ServiceResult<UserResource> updateDetails(Long id, String email, String firstName, String lastName, String title, String phoneNumber, boolean allowMarketingEmails); @Override Long getUserOrganisationId(Long userId, Long applicationId); @Override void resendEmailVerificationNotification(String email); @Override Boolean userHasApplicationForCompetition(Long userId, Long competitionId); @Override void sendPasswordResetNotification(String email); @Override Optional<UserResource> findUserByEmail(String email); @Override boolean existsAndHasRole(Long userId, Role role); } | @Test public void findUserByEmail() { String email = "[email protected]"; UserResource user = newUserResource().withEmail(email).build(); when(userRestService.findUserByEmail(email)).thenReturn(restSuccess(user)); Optional<UserResource> result = service.findUserByEmail(email); verify(userRestService).findUserByEmail(email); verifyNoMoreInteractions(userRestService); assertEquals(user, result.get()); } |
ProcessRoleServiceImpl implements ProcessRoleService { @Override public List<ProcessRoleResource> findAssignableProcessRoles(Long applicationId) { return userRestService.findAssignableProcessRoles(applicationId).getSuccess(); } @Override List<ProcessRoleResource> findAssignableProcessRoles(Long applicationId); @Override Future<ProcessRoleResource> getById(Long id); } | @Test public void findAssignableProcessRoles() throws Exception { long applicationId = 1; List<ProcessRoleResource> resources = newArrayList(new ProcessRoleResource()); RestResult<List<ProcessRoleResource>> restResult = restSuccess(resources); when(userRestService.findAssignableProcessRoles(applicationId)).thenReturn(restResult); List<ProcessRoleResource> actualResources = service.findAssignableProcessRoles(applicationId); verify(userRestService, times(1)).findAssignableProcessRoles(applicationId); verifyNoMoreInteractions(userRestService); assertEquals(resources, actualResources); } |
ProcessRoleServiceImpl implements ProcessRoleService { @Override public Future<ProcessRoleResource> getById(Long id) { return adapt(userRestService.findProcessRoleById(id), RestResult::getSuccess); } @Override List<ProcessRoleResource> findAssignableProcessRoles(Long applicationId); @Override Future<ProcessRoleResource> getById(Long id); } | @Test public void getById() throws Exception { long id = 1; ProcessRoleResource resource = new ProcessRoleResource(); RestResult<ProcessRoleResource> restResult = restSuccess(resource); Future future = mock(Future.class); when(future.get()).thenReturn(restResult); when(userRestService.findProcessRoleById(id)).thenReturn(future); Future<ProcessRoleResource> returnedResponse = service.getById(id); ProcessRoleResource actualResources = returnedResponse.get(); verify(userRestService, times(1)).findProcessRoleById(id); verifyNoMoreInteractions(userRestService); assertEquals(resource, actualResources); } |
NavigationUtils { public String getRedirectToDashboardUrlForRole(Role role) { if (LIVE_PROJECTS_USER.equals(role)) { return "redirect:" + liveProjectsLandingPageUrl; } String roleUrl = DEFAULT_LANDING_PAGE_URLS_FOR_ROLES.get(role); return format("redirect:/%s", hasText(roleUrl) ? roleUrl : "dashboard"); } private NavigationUtils(); String getLiveProjectsLandingPageUrl(); String getRedirectToDashboardUrlForRole(Role role); String getDirectDashboardUrlForRole(HttpServletRequest request, Role role); String getRedirectToLandingPageUrl(HttpServletRequest request); String getDirectLandingPageUrl(HttpServletRequest request); String getRedirectToSameDomainUrl(HttpServletRequest request, String url); String getDirectToSameDomainUrl(HttpServletRequest request, String url); } | @Test public void getRedirectToDashboardUrlForLiveProjectUser() throws Exception { assertEquals("redirect:https: navigationUtils.getRedirectToDashboardUrlForRole(LIVE_PROJECTS_USER)); }
@Test public void getRedirectToDashboardUrlForApplicantRole() throws Exception { assertEquals("redirect:/applicant/dashboard", navigationUtils.getRedirectToDashboardUrlForRole(APPLICANT)); }
@Test public void getRedirectToDashboardUrlForNoLandingPageRole() throws Exception { assertEquals("redirect:/dashboard", navigationUtils.getRedirectToDashboardUrlForRole(COMP_EXEC)); }
@Test public void getRedirectToDashboardUrlForNullRole() throws Exception { assertEquals("redirect:/dashboard", navigationUtils.getRedirectToDashboardUrlForRole(null)); } |
NavigationUtils { public String getDirectDashboardUrlForRole(HttpServletRequest request, Role role) { if (LIVE_PROJECTS_USER.equals(role)) { return liveProjectsLandingPageUrl; } String roleUrl = DEFAULT_LANDING_PAGE_URLS_FOR_ROLES.get(role); return getDirectToSameDomainUrl(request, roleUrl); } private NavigationUtils(); String getLiveProjectsLandingPageUrl(); String getRedirectToDashboardUrlForRole(Role role); String getDirectDashboardUrlForRole(HttpServletRequest request, Role role); String getRedirectToLandingPageUrl(HttpServletRequest request); String getDirectLandingPageUrl(HttpServletRequest request); String getRedirectToSameDomainUrl(HttpServletRequest request, String url); String getDirectToSameDomainUrl(HttpServletRequest request, String url); } | @Test public void getDirectDashboardUrlForApplicantRole() throws Exception { assertEquals("https: }
@Test public void getDirectDashboardUrlForKnowledgeTransferAdvisor() throws Exception { assertEquals("https: } |
NavigationUtils { public String getRedirectToLandingPageUrl(HttpServletRequest request) { return String.format("redirect:%s: request.getScheme(), request.getServerName(), request.getServerPort()); } private NavigationUtils(); String getLiveProjectsLandingPageUrl(); String getRedirectToDashboardUrlForRole(Role role); String getDirectDashboardUrlForRole(HttpServletRequest request, Role role); String getRedirectToLandingPageUrl(HttpServletRequest request); String getDirectLandingPageUrl(HttpServletRequest request); String getRedirectToSameDomainUrl(HttpServletRequest request, String url); String getDirectToSameDomainUrl(HttpServletRequest request, String url); } | @Test public void getRedirectToLandingPageUrl() throws Exception { assertEquals("redirect:https: } |
NavigationUtils { public String getDirectLandingPageUrl(HttpServletRequest request) { return String.format("%s: request.getScheme(), request.getServerName(), request.getServerPort()); } private NavigationUtils(); String getLiveProjectsLandingPageUrl(); String getRedirectToDashboardUrlForRole(Role role); String getDirectDashboardUrlForRole(HttpServletRequest request, Role role); String getRedirectToLandingPageUrl(HttpServletRequest request); String getDirectLandingPageUrl(HttpServletRequest request); String getRedirectToSameDomainUrl(HttpServletRequest request, String url); String getDirectToSameDomainUrl(HttpServletRequest request, String url); } | @Test public void getDirectLandingPageUrl() throws Exception { assertEquals("https: } |
SectionController { @GetMapping("/get-previous-section/{sectionId}") public RestResult<SectionResource> getPreviousSection(@PathVariable("sectionId") final Long sectionId) { return sectionService.getPreviousSection(sectionId).toGetResponse(); } @GetMapping("/{sectionId}") RestResult<SectionResource> getById(@PathVariable("sectionId") final Long sectionId); @GetMapping("/get-child-sections/{parentId}") RestResult<List<SectionResource>> getChildSectionsByParentId(@PathVariable long parentId); @GetMapping("/get-next-section/{sectionId}") RestResult<SectionResource> getNextSection(@PathVariable("sectionId") final Long sectionId); @GetMapping("/get-previous-section/{sectionId}") RestResult<SectionResource> getPreviousSection(@PathVariable("sectionId") final Long sectionId); @GetMapping("/get-section-by-question-id/{questionId}") RestResult<SectionResource> getSectionByQuestionId(@PathVariable("questionId") final Long questionId); @GetMapping("/get-questions-for-section-and-subsections/{sectionId}") RestResult<Set<Long>> getQuestionsForSectionAndSubsections(@PathVariable("sectionId") final Long sectionId); @GetMapping("/get-sections-by-competition-id-and-type/{competitionId}/{type}") RestResult<List<SectionResource>> getSectionsByCompetitionIdAndType(@PathVariable("competitionId") final Long competitionId, @PathVariable("type") SectionType type); @GetMapping("/get-by-competition/{competitionId}") RestResult<List<SectionResource>> getSectionsByCompetitionId(@PathVariable("competitionId") final Long competitionId); @GetMapping("/get-by-competition-id-visible-for-assessment/{competitionId}") RestResult<List<SectionResource>> getByCompetitionIdVisibleForAssessment(@PathVariable("competitionId") long competitionId); } | @Test public void getPreviousSectionTest() throws Exception { Section section = newSection().withCompetitionAndPriority(newCompetition().build(), 1).build(); SectionResource previousSection = newSectionResource().build(); when(sectionService.getPreviousSection(section.getId())).thenReturn(serviceSuccess(previousSection)); mockMvc.perform(get("/section/get-previous-section/" + section.getId()) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(objectMapper.writeValueAsString(previousSection))); } |
NavigationUtils { public String getRedirectToSameDomainUrl(HttpServletRequest request, String url) { return String.format("redirect:%s: request.getScheme(), request.getServerName(), request.getServerPort(), url); } private NavigationUtils(); String getLiveProjectsLandingPageUrl(); String getRedirectToDashboardUrlForRole(Role role); String getDirectDashboardUrlForRole(HttpServletRequest request, Role role); String getRedirectToLandingPageUrl(HttpServletRequest request); String getDirectLandingPageUrl(HttpServletRequest request); String getRedirectToSameDomainUrl(HttpServletRequest request, String url); String getDirectToSameDomainUrl(HttpServletRequest request, String url); } | @Test public void getRedirectToSameDomainUrl() throws Exception { String url = "management/dashboard"; assertEquals("redirect:https: } |
ThymeleafUtil { public String formPostUri(final HttpServletRequest request) { if (request == null) { throw new IllegalArgumentException("Cannot determine request URI with query string for null request."); } LOG.debug("Creating URI for request " + request.getClass() + " with URI " + request.getRequestURI()); return UriComponentsBuilder.fromPath(request.getServletPath()).build().normalize().toUriString(); } ThymeleafUtil(IExpressionContext context); String formPostUri(final HttpServletRequest request); int wordsRemaining(Integer maxWordCount, String content); long calculatePercentage(long part, long total); boolean hasErrorsStartingWith(String form, String startsWith); } | @Test public void formPostUri() throws Exception { final String servletPath = "/application/1/form"; final String queryString = "test=true,newApplication=true"; final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getServletPath()).thenReturn(servletPath); when(request.getQueryString()).thenReturn(queryString); assertEquals(servletPath, thymeleafUtil.formPostUri(request)); }
@Test(expected = IllegalArgumentException.class) public void formPostUri_null() throws Exception { thymeleafUtil.formPostUri(null); }
@Test public void formPostUri_noQueryString() throws Exception { final String servletPath = "/application/1/form"; final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getServletPath()).thenReturn(servletPath); assertEquals(servletPath, thymeleafUtil.formPostUri(request)); } |
ThymeleafUtil { public int wordsRemaining(Integer maxWordCount, String content) { return ofNullable(maxWordCount).map(maxWordCountValue -> maxWordCountValue - countWords(content)).orElse(0); } ThymeleafUtil(IExpressionContext context); String formPostUri(final HttpServletRequest request); int wordsRemaining(Integer maxWordCount, String content); long calculatePercentage(long part, long total); boolean hasErrorsStartingWith(String form, String startsWith); } | @Test public void wordsRemaining() throws Exception { assertEquals(85, thymeleafUtil.wordsRemaining(100, join(" ", nCopies(15, "content")))); }
@Test public void wordsRemaining_greaterThanMaxWordCount() throws Exception { assertEquals(-15, thymeleafUtil.wordsRemaining(100, join(" ", nCopies(115, "content")))); }
@Test public void wordsRemaining_valueWithHtml() throws Exception { assertEquals(85, thymeleafUtil.wordsRemaining(100, "<td><p style=\"font-variant: small-caps\">This value is made up of fifteen words even though it is wrapped within HTML.</p></td>")); }
@Test public void wordsRemaining_noMaxWordCount() throws Exception { assertEquals(0, thymeleafUtil.wordsRemaining(null, join(" ", nCopies(8, "content")))); }
@Test public void wordsRemaining_noContent() throws Exception { assertEquals(100, thymeleafUtil.wordsRemaining(100, null)); }
@Test public void wordsRemaining_emptyContent() throws Exception { assertEquals(100, thymeleafUtil.wordsRemaining(100, "")); } |
SectionController { @GetMapping("/get-by-competition-id-visible-for-assessment/{competitionId}") public RestResult<List<SectionResource>> getByCompetitionIdVisibleForAssessment(@PathVariable("competitionId") long competitionId) { return sectionService.getByCompetitionIdVisibleForAssessment(competitionId).toGetResponse(); } @GetMapping("/{sectionId}") RestResult<SectionResource> getById(@PathVariable("sectionId") final Long sectionId); @GetMapping("/get-child-sections/{parentId}") RestResult<List<SectionResource>> getChildSectionsByParentId(@PathVariable long parentId); @GetMapping("/get-next-section/{sectionId}") RestResult<SectionResource> getNextSection(@PathVariable("sectionId") final Long sectionId); @GetMapping("/get-previous-section/{sectionId}") RestResult<SectionResource> getPreviousSection(@PathVariable("sectionId") final Long sectionId); @GetMapping("/get-section-by-question-id/{questionId}") RestResult<SectionResource> getSectionByQuestionId(@PathVariable("questionId") final Long questionId); @GetMapping("/get-questions-for-section-and-subsections/{sectionId}") RestResult<Set<Long>> getQuestionsForSectionAndSubsections(@PathVariable("sectionId") final Long sectionId); @GetMapping("/get-sections-by-competition-id-and-type/{competitionId}/{type}") RestResult<List<SectionResource>> getSectionsByCompetitionIdAndType(@PathVariable("competitionId") final Long competitionId, @PathVariable("type") SectionType type); @GetMapping("/get-by-competition/{competitionId}") RestResult<List<SectionResource>> getSectionsByCompetitionId(@PathVariable("competitionId") final Long competitionId); @GetMapping("/get-by-competition-id-visible-for-assessment/{competitionId}") RestResult<List<SectionResource>> getByCompetitionIdVisibleForAssessment(@PathVariable("competitionId") long competitionId); } | @Test public void getByCompetitionIdVisibleForAssessment() throws Exception { List<SectionResource> expected = newSectionResource().build(2); long competitionId = 1L; when(sectionService.getByCompetitionIdVisibleForAssessment(competitionId)).thenReturn(serviceSuccess(expected)); mockMvc.perform(RestDocumentationRequestBuilders.get("/section/get-by-competition-id-visible-for-assessment/{competitionId}", competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(expected))); verify(sectionService, only()).getByCompetitionIdVisibleForAssessment(competitionId); } |
HttpUtils { public static Optional<String> requestParameterPresent(String parameterName, HttpServletRequest request) { Map<String, String> params = simpleMapValue(request.getParameterMap(), array -> array != null && array.length > 0 ? array[0] : null); String defaultMatch = params.get(parameterName); if (defaultMatch != null) { return ofNullable(defaultMatch); } String matchForMMYYYY = processForMMYYYY(params).get(parameterName); if (matchForMMYYYY != null) { return ofNullable(matchForMMYYYY); } return Optional.empty(); } private HttpUtils(); static Optional<String> requestParameterPresent(String parameterName, HttpServletRequest request); static MultiValueMap<String, String> getQueryStringParameters(HttpServletRequest request); static String getFullRequestUrl(HttpServletRequest request); static final String MM_YYYY_MONTH_APPEND; static final String MM_YYYY_YEAR_APPEND; } | @Test public void requestParameterPresent_notPresent() { assertEquals(Optional.empty(), HttpUtils.requestParameterPresent("testParameter", new MockHttpServletRequest())); }
@Test public void requestParameterPresent_present() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("testParameter", "param value"); assertEquals(Optional.of("param value"), HttpUtils.requestParameterPresent("testParameter", request)); }
@Test public void requestParameterPresent_presentButBlank() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("testParameter", ""); assertEquals(Optional.of(""), HttpUtils.requestParameterPresent("testParameter", request)); }
@Test public void requestParameterPresent_presentButNull() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("testParameter", (String) null); assertEquals(Optional.empty(), HttpUtils.requestParameterPresent("testParameter", request)); }
@Test public void requestParameterPresent_MMYYYY() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("testParameter" + HttpUtils.MM_YYYY_MONTH_APPEND, "12"); request.addParameter("testParameter" + HttpUtils.MM_YYYY_YEAR_APPEND, "2011"); assertEquals(Optional.of("12-2011"), HttpUtils.requestParameterPresent("testParameter", request)); }
@Test public void requestParameterPresent_MMYYYY_monthMissing() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("testParameter" + HttpUtils.MM_YYYY_YEAR_APPEND, "2011"); assertEquals(Optional.of("-2011"), HttpUtils.requestParameterPresent("testParameter", request)); }
@Test public void requestParameterPresent_MMYYYY_yearMissing() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("testParameter" + HttpUtils.MM_YYYY_MONTH_APPEND, "12"); assertEquals(Optional.of("12-"), HttpUtils.requestParameterPresent("testParameter", request)); }
@Test public void requestParameterPresent_MMYYYY_monthIsShort() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("testParameter" + HttpUtils.MM_YYYY_MONTH_APPEND, "1"); request.addParameter("testParameter" + HttpUtils.MM_YYYY_YEAR_APPEND, "2011"); assertEquals(Optional.of("01-2011"), HttpUtils.requestParameterPresent("testParameter", request)); }
@Test public void requestParameterPresent_MMYYYY_monthIsLong() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("testParameter" + HttpUtils.MM_YYYY_MONTH_APPEND, "111"); request.addParameter("testParameter" + HttpUtils.MM_YYYY_YEAR_APPEND, "2011"); assertEquals(Optional.of("111-2011"), HttpUtils.requestParameterPresent("testParameter", request)); }
@Test public void requestParameterPresent_MMYYYY_yearIsShort() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("testParameter" + HttpUtils.MM_YYYY_MONTH_APPEND, "11"); request.addParameter("testParameter" + HttpUtils.MM_YYYY_YEAR_APPEND, "201"); assertEquals(Optional.of("11-0201"), HttpUtils.requestParameterPresent("testParameter", request)); }
@Test public void requestParameterPresent_MMYYYY_yearIsLong() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("testParameter" + HttpUtils.MM_YYYY_MONTH_APPEND, "11"); request.addParameter("testParameter" + HttpUtils.MM_YYYY_YEAR_APPEND, "20111"); assertEquals(Optional.of("11-20111"), HttpUtils.requestParameterPresent("testParameter", request)); } |
SectionController { @GetMapping("/get-child-sections/{parentId}") public RestResult<List<SectionResource>> getChildSectionsByParentId(@PathVariable long parentId) { return sectionService.getChildSectionsByParentId(parentId).toGetResponse(); } @GetMapping("/{sectionId}") RestResult<SectionResource> getById(@PathVariable("sectionId") final Long sectionId); @GetMapping("/get-child-sections/{parentId}") RestResult<List<SectionResource>> getChildSectionsByParentId(@PathVariable long parentId); @GetMapping("/get-next-section/{sectionId}") RestResult<SectionResource> getNextSection(@PathVariable("sectionId") final Long sectionId); @GetMapping("/get-previous-section/{sectionId}") RestResult<SectionResource> getPreviousSection(@PathVariable("sectionId") final Long sectionId); @GetMapping("/get-section-by-question-id/{questionId}") RestResult<SectionResource> getSectionByQuestionId(@PathVariable("questionId") final Long questionId); @GetMapping("/get-questions-for-section-and-subsections/{sectionId}") RestResult<Set<Long>> getQuestionsForSectionAndSubsections(@PathVariable("sectionId") final Long sectionId); @GetMapping("/get-sections-by-competition-id-and-type/{competitionId}/{type}") RestResult<List<SectionResource>> getSectionsByCompetitionIdAndType(@PathVariable("competitionId") final Long competitionId, @PathVariable("type") SectionType type); @GetMapping("/get-by-competition/{competitionId}") RestResult<List<SectionResource>> getSectionsByCompetitionId(@PathVariable("competitionId") final Long competitionId); @GetMapping("/get-by-competition-id-visible-for-assessment/{competitionId}") RestResult<List<SectionResource>> getByCompetitionIdVisibleForAssessment(@PathVariable("competitionId") long competitionId); } | @Test public void getChildSectionsByParentId() throws Exception { Section parentSection = newSection().withId(30L).build(); List<SectionResource> childSections = newSectionResource().withParentSection(parentSection.getId()).build(4); when(sectionService.getChildSectionsByParentId(parentSection.getId())).thenReturn(serviceSuccess(childSections)); mockMvc.perform(get("/section/get-child-sections/" + parentSection.getId()) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); verify(sectionService, only()).getChildSectionsByParentId(parentSection.getId()); } |
HttpUtils { public static MultiValueMap<String, String> getQueryStringParameters(HttpServletRequest request) { return new LinkedMultiValueMap<>( UriComponentsBuilder.newInstance() .query(request.getQueryString()) .build() .getQueryParams() ); } private HttpUtils(); static Optional<String> requestParameterPresent(String parameterName, HttpServletRequest request); static MultiValueMap<String, String> getQueryStringParameters(HttpServletRequest request); static String getFullRequestUrl(HttpServletRequest request); static final String MM_YYYY_MONTH_APPEND; static final String MM_YYYY_YEAR_APPEND; } | @Test public void getQueryStringParameters() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setQueryString("first=a&second=b&second=c"); MultiValueMap<String, String> map = HttpUtils.getQueryStringParameters(request); assertEquals(1, map.get("first").size()); assertEquals("a", map.get("first").get(0)); assertEquals(2, map.get("second").size()); assertEquals("b", map.get("second").get(0)); assertEquals("c", map.get("second").get(1)); } |
HttpUtils { public static String getFullRequestUrl(HttpServletRequest request) { StringBuffer requestURL = request.getRequestURL(); String queryString = request.getQueryString(); if (queryString == null) { return requestURL.toString(); } else { return requestURL.append('?').append(queryString).toString(); } } private HttpUtils(); static Optional<String> requestParameterPresent(String parameterName, HttpServletRequest request); static MultiValueMap<String, String> getQueryStringParameters(HttpServletRequest request); static String getFullRequestUrl(HttpServletRequest request); static final String MM_YYYY_MONTH_APPEND; static final String MM_YYYY_YEAR_APPEND; } | @Test public void getFullRequestUrl() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test"); request.setQueryString("param=value"); assertEquals("http: }
@Test public void getFullRequestUrl_noQuery() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test"); assertEquals("http: } |
GoogleAnalyticsDataLayerInterceptor extends HandlerInterceptorAdapter { @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { if (modelAndView == null) { return; } final GoogleAnalyticsDataLayer dl = getOrCreateDataLayer(modelAndView); if (modelAndView.getViewName() != null && modelAndView.getViewName().startsWith("redirect:")) { return; } setCompetitionName(dl, request, modelAndView); setUserRoles(dl, request); setApplicationId(dl, request, modelAndView); } @Override void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView); } | @Test public void postHandle() { final long expectedCompetitionId = 7L; httpServletRequest.setAttribute(URI_TEMPLATE_VARIABLES_ATTRIBUTE, singletonMap("competitionId", Long.toString(expectedCompetitionId))); when(googleAnalyticsDataLayerRestServiceMock.getCompetitionName(expectedCompetitionId)).thenReturn(RestResult.restSuccess(toJson(expectedCompName))); googleAnalyticsDataLayerInterceptor.postHandle(httpServletRequest, httpServletResponseMock, null, mav); GoogleAnalyticsDataLayer expectedDataLayer = new GoogleAnalyticsDataLayer(); expectedDataLayer.setCompetitionName(expectedCompName); expectedDataLayer.setUserRoles(emptyList()); assertEquals(expectedDataLayer, mav.getModel().get(ANALYTICS_DATA_LAYER_NAME)); verify(googleAnalyticsDataLayerRestServiceMock, only()).getCompetitionName(expectedCompetitionId); } |
CsrfTokenService { CsrfToken generateToken() { return new DefaultCsrfToken(CSRF_HEADER_NAME, CSRF_PARAMETER_NAME, encryptToken()); } @Value("${ifs.web.security.csrf.encryption.password}") void setEncryptionPassword(final String encryptionPassword); @Value("${ifs.web.security.csrf.encryption.salt}") void setEncryptionSalt(final String encryptionSalt); @Value("${ifs.web.security.csrf.token.validity.mins}") void setTokenValidityMins(final int tokenValidityMins); } | @Test public void test_generateToken() throws Exception { final CsrfToken token = tokenUtility.generateToken(); assertEquals("X-CSRF-TOKEN", token.getHeaderName()); assertEquals("_csrf", token.getParameterName()); final String decrypted = encryptor.decrypt(token.getToken()); final CsrfUidToken parsed = CsrfUidToken.parse(decrypted); assertEquals(UID, parsed.getuId()); }
@Test public void test_generateToken_anonymous() throws Exception { SecurityContextHolder.getContext().setAuthentication(null); final CsrfToken token = tokenUtility.generateToken(); final String decrypted = encryptor.decrypt(token.getToken()); final CsrfUidToken parsed = CsrfUidToken.parse(decrypted); assertEquals("ANONYMOUS", parsed.getuId()); } |
CsrfTokenService { void validateToken(final HttpServletRequest request) throws CsrfException { final CsrfUidToken csrfUidToken = decryptToken(request); if (!isUIdValid(csrfUidToken.getuId())) { throw new CsrfException("User id not recognised while validating CSRF token."); } if (!isTimestampValid(csrfUidToken.getTimestamp())) { throw new CsrfException("Timestamp not valid while validating CSRF token."); } } @Value("${ifs.web.security.csrf.encryption.password}") void setEncryptionPassword(final String encryptionPassword); @Value("${ifs.web.security.csrf.encryption.salt}") void setEncryptionSalt(final String encryptionSalt); @Value("${ifs.web.security.csrf.token.validity.mins}") void setTokenValidityMins(final int tokenValidityMins); } | @Test public void test_validateToken_expired() throws Exception { final Instant oldTimestamp = Instant.now().minus(TOKEN_VALIDITY_MINS+1, ChronoUnit.MINUTES); thrown.expect(CsrfException.class); thrown.expectMessage("Timestamp not valid while validating CSRF token."); tokenUtility.validateToken(mockRequestWithHeaderValue(token(UID, oldTimestamp))); }
@Test public void test_validateToken_wrong_uid() throws Exception { final String wrongUid = randomUUID().toString(); thrown.expect(CsrfException.class); thrown.expectMessage("User id not recognised while validating CSRF token"); tokenUtility.validateToken(mockRequestWithHeaderValue(token(wrongUid, recentTimestamp()))); }
@Test public void test_validateToken_anonymous() throws Exception { SecurityContextHolder.getContext().setAuthentication(null); tokenUtility.validateToken(mockRequestWithHeaderValue(token("ANONYMOUS", recentTimestamp()))); }
@Test public void test_validateToken_requestBody_absent() throws Exception { thrown.expect(CsrfException.class); thrown.expectMessage(format("CSRF Token not found. Expected token in header with name '%s' or request parameter with name '%s'.", "X-CSRF-TOKEN", "_csrf")); tokenUtility.validateToken(mockRequest()); }
@Test public void test_validateToken_requestHeader_present() throws Exception { tokenUtility.validateToken(mockRequestWithHeaderValue(validToken())); }
@Test public void test_validateToken_requestHeader_malformed() throws Exception { thrown.expect(CsrfException.class); thrown.expectMessage("CSRF Token could not be decrypted"); tokenUtility.validateToken(mockRequestWithHeaderValue(malformedToken())); }
@Test public void test_validateToken_requestHeader_empty() throws Exception { thrown.expect(CsrfException.class); thrown.expectMessage("CSRF Token could not be decrypted"); tokenUtility.validateToken(mockRequestWithHeaderValue(EMPTY)); }
@Test public void test_validateToken_requestBody_present() throws Exception { tokenUtility.validateToken(mockRequestWithParameterValue(validToken())); }
@Test public void test_validateToken_requestBody_malformed() throws Exception { thrown.expect(CsrfException.class); thrown.expectMessage("CSRF Token could not be decrypted"); tokenUtility.validateToken(mockRequestWithParameterValue(malformedToken())); }
@Test public void test_validateToken_requestBody_empty() throws Exception { thrown.expect(CsrfException.class); thrown.expectMessage("CSRF Token could not be decrypted"); tokenUtility.validateToken(mockRequestWithParameterValue(EMPTY)); } |
FormInputController { @GetMapping("/find-by-question-id/{questionId}") public RestResult<List<FormInputResource>> findByQuestionId(@PathVariable("questionId") Long questionId) { return formInputService.findByQuestionId(questionId).toGetResponse(); } @GetMapping("/{id}") RestResult<FormInputResource> findOne(@PathVariable("id") Long id); @GetMapping("/find-by-question-id/{questionId}") RestResult<List<FormInputResource>> findByQuestionId(@PathVariable("questionId") Long questionId); @GetMapping("find-by-question-id/{questionId}/scope/{scope}") RestResult<List<FormInputResource>> findByQuestionIdAndScope(@PathVariable("questionId") Long questionId, @PathVariable("scope") FormInputScope scope); @GetMapping("/find-by-competition-id/{competitionId}") RestResult<List<FormInputResource>> findByCompetitionId(@PathVariable("competitionId") Long competitionId); @GetMapping("/find-by-competition-id/{competitionId}/scope/{scope}") RestResult<List<FormInputResource>> findByCompetitionIdAndScope(@PathVariable("competitionId") Long competitionId, @PathVariable("scope") FormInputScope scope); @DeleteMapping("/{id}") RestResult<Void> delete(@PathVariable("id") Long id); @GetMapping(value = "/file/{formInputId}", produces = "application/json") @ResponseBody ResponseEntity<Object> downloadFile(@PathVariable long formInputId); @GetMapping(value = "/file-details/{formInputId}", produces = "application/json") RestResult<FileEntryResource> findFile(@PathVariable long formInputId); } | @Test public void testFindByQuestionId() throws Exception { Long questionId = 1L; List<FormInputResource> expected = newFormInputResource().build(1); when(formInputServiceMock.findByQuestionId(questionId)).thenReturn(serviceSuccess(expected)); mockMvc.perform(get("/forminput/find-by-question-id/{id}", questionId)) .andExpect(status().isOk()) .andExpect(content().string(objectMapper.writeValueAsString(expected))); verify(formInputServiceMock, only()).findByQuestionId(questionId); } |
CsrfStatelessFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (!isResourceRequest(request)) { final CsrfToken token = tokenService.generateToken(); request.setAttribute(CsrfToken.class.getName(), token); setTokenAsCookie(response, token); } if (!requireCsrfProtectionMatcher.matches(request)) { filterChain.doFilter(request, response); return; } try { tokenService.validateToken(request); } catch (final CsrfException e) { LOG.warn("Handling access denied for exception", e); accessDeniedHandler.handle(request, response, e); return; } filterChain.doFilter(request, response); } @Value("${ifsEnableDevTools:false}") void setEnableDevTools(boolean enableDevTools); } | @Test public void test_doFilterInternal_invalid() throws Exception { final MockHttpServletRequest invalidRequest = new MockHttpServletRequest(); invalidRequest.setMethod(POST.toString()); final CsrfException expectedException = new CsrfException("Not allowed"); doThrow(expectedException).when(tokenUtility).validateToken(same(invalidRequest)); filter.doFilterInternal(invalidRequest, response, filterChain); verify(accessDeniedHandler, times(1)).handle(invalidRequest, response, expectedException); verifyZeroInteractions(filterChain); } |
LocalDatePropertyEditor extends PropertyEditorSupport { @Override public void setAsText(String dateFieldName) throws IllegalArgumentException { Map<String, String[]> parameterMap = webRequest.getParameterMap(); Integer year = returnZeroWhenNotValid(parameterMap, dateFieldName + ".year", ChronoField.YEAR, LocalDate.MIN.getYear()); Integer month = returnZeroWhenNotValid(parameterMap, dateFieldName + ".monthValue", ChronoField.MONTH_OF_YEAR, LocalDate.MIN.getMonthValue()); Integer day = returnZeroWhenNotValid(parameterMap, dateFieldName + ".dayOfMonth", ChronoField.DAY_OF_MONTH, LocalDate.MIN.getDayOfMonth()); try { setValue(LocalDate.of(year, month, day)); } catch (Exception ex) { LOG.error(ex); setValue(LocalDate.MIN); } } LocalDatePropertyEditor(WebRequest webRequest); @Override void setAsText(String dateFieldName); static LocalDate convertMinLocalDateToNull(LocalDate localDate); } | @Test public void testSetAsText() { MockHttpServletRequest request = createMockRequestWithDate("2017", "7", "2"); LocalDatePropertyEditor editor = new LocalDatePropertyEditor(new DispatcherServletWebRequest(request)); editor.setAsText("myField"); assertEquals("2017-07-02", editor.getAsText()); }
@Test public void testSetAsTextWithInvalidValuesForMonthDefaultsToOne() { MockHttpServletRequest request = createMockRequestWithDate("2016", "NaN", "3"); LocalDatePropertyEditor editor = new LocalDatePropertyEditor(new DispatcherServletWebRequest(request)); editor.setAsText("myField"); assertEquals("2016-01-03", editor.getAsText()); }
@Test public void testSetAsTextWithInvalidValuesForDayDefaultsToOne() { MockHttpServletRequest request = createMockRequestWithDate("2016", "3", "hello"); LocalDatePropertyEditor editor = new LocalDatePropertyEditor(new DispatcherServletWebRequest(request)); editor.setAsText("myField"); assertEquals("2016-03-01", editor.getAsText()); }
@Test public void testSetAsTextWithInvalidValuesForDateDefaultsToOne() { MockHttpServletRequest request = createMockRequestWithDate("2016", "3", "35"); LocalDatePropertyEditor editor = new LocalDatePropertyEditor(new DispatcherServletWebRequest(request)); editor.setAsText("myField"); assertEquals("2016-03-01", editor.getAsText()); }
@Test public void testSetAsTextWithInvalidValuesForYearDefaultsToThisYear() { int thisYear = LocalDate.MIN.getYear(); MockHttpServletRequest request = createMockRequestWithDate("hello", "3", "5"); LocalDatePropertyEditor editor = new LocalDatePropertyEditor(new DispatcherServletWebRequest(request)); editor.setAsText("myField"); assertEquals(thisYear + "-03-05", editor.getAsText()); } |
FormInputController { @GetMapping("find-by-question-id/{questionId}/scope/{scope}") public RestResult<List<FormInputResource>> findByQuestionIdAndScope(@PathVariable("questionId") Long questionId, @PathVariable("scope") FormInputScope scope) { return formInputService.findByQuestionIdAndScope(questionId, scope).toGetResponse(); } @GetMapping("/{id}") RestResult<FormInputResource> findOne(@PathVariable("id") Long id); @GetMapping("/find-by-question-id/{questionId}") RestResult<List<FormInputResource>> findByQuestionId(@PathVariable("questionId") Long questionId); @GetMapping("find-by-question-id/{questionId}/scope/{scope}") RestResult<List<FormInputResource>> findByQuestionIdAndScope(@PathVariable("questionId") Long questionId, @PathVariable("scope") FormInputScope scope); @GetMapping("/find-by-competition-id/{competitionId}") RestResult<List<FormInputResource>> findByCompetitionId(@PathVariable("competitionId") Long competitionId); @GetMapping("/find-by-competition-id/{competitionId}/scope/{scope}") RestResult<List<FormInputResource>> findByCompetitionIdAndScope(@PathVariable("competitionId") Long competitionId, @PathVariable("scope") FormInputScope scope); @DeleteMapping("/{id}") RestResult<Void> delete(@PathVariable("id") Long id); @GetMapping(value = "/file/{formInputId}", produces = "application/json") @ResponseBody ResponseEntity<Object> downloadFile(@PathVariable long formInputId); @GetMapping(value = "/file-details/{formInputId}", produces = "application/json") RestResult<FileEntryResource> findFile(@PathVariable long formInputId); } | @Test public void testFindByQuestionIdAndScope() throws Exception { List<FormInputResource> expected = newFormInputResource() .build(2); Long questionId = 1L; FormInputScope scope = APPLICATION; when(formInputServiceMock.findByQuestionIdAndScope(questionId, scope)).thenReturn(serviceSuccess(expected)); mockMvc.perform(get("/forminput/find-by-question-id/{questionId}/scope/{scope}", questionId, scope)) .andExpect(status().isOk()) .andExpect(jsonPath("$", hasSize(2))) .andExpect(content().string(objectMapper.writeValueAsString(expected))); verify(formInputServiceMock, only()).findByQuestionIdAndScope(questionId, scope); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.